1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
8 #include <sys/sendfile.h>
12 #include "alloc-util.h"
13 #include "btrfs-util.h"
14 #include "chattr-util.h"
16 #include "dirent-util.h"
22 #include "missing_syscall.h"
23 #include "mkdir-label.h"
24 #include "mountpoint-util.h"
25 #include "nulstr-util.h"
27 #include "selinux-util.h"
28 #include "signal-util.h"
29 #include "stat-util.h"
30 #include "stdio-util.h"
31 #include "string-util.h"
33 #include "sync-util.h"
34 #include "time-util.h"
35 #include "tmpfile-util.h"
36 #include "umask-util.h"
37 #include "user-util.h"
38 #include "xattr-util.h"
40 #define COPY_BUFFER_SIZE (16U*1024U)
42 /* A safety net for descending recursively into file system trees to copy. On Linux PATH_MAX is 4096, which means the
43 * deepest valid path one can build is around 2048, which we hence use as a safety net here, to not spin endlessly in
44 * case of bind mount cycles and suchlike. */
45 #define COPY_DEPTH_MAX 2048U
47 static ssize_t
try_copy_file_range(
48 int fd_in
, loff_t
*off_in
,
49 int fd_out
, loff_t
*off_out
,
59 r
= copy_file_range(fd_in
, off_in
, fd_out
, off_out
, len
, flags
);
61 have
= r
>= 0 || errno
!= ENOSYS
;
71 FD_IS_NONBLOCKING_PIPE
,
74 static int fd_is_nonblock_pipe(int fd
) {
78 /* Checks whether the specified file descriptor refers to a pipe, and if so if O_NONBLOCK is set. */
80 if (fstat(fd
, &st
) < 0)
83 if (!S_ISFIFO(st
.st_mode
))
86 flags
= fcntl(fd
, F_GETFL
);
90 return FLAGS_SET(flags
, O_NONBLOCK
) ? FD_IS_NONBLOCKING_PIPE
: FD_IS_BLOCKING_PIPE
;
93 static int look_for_signals(CopyFlags copy_flags
) {
96 if ((copy_flags
& (COPY_SIGINT
|COPY_SIGTERM
)) == 0)
99 r
= pop_pending_signal(copy_flags
& COPY_SIGINT
? SIGINT
: 0,
100 copy_flags
& COPY_SIGTERM
? SIGTERM
: 0);
104 return log_debug_errno(SYNTHETIC_ERRNO(EINTR
),
105 "Got %s, cancelling copy operation.", signal_to_string(r
));
110 static int create_hole(int fd
, off_t size
) {
114 offset
= lseek(fd
, 0, SEEK_CUR
);
118 end
= lseek(fd
, 0, SEEK_END
);
122 /* If we're not at the end of the target file, try to punch a hole in the existing space using fallocate(). */
125 fallocate(fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
, offset
, MIN(size
, end
- offset
)) < 0 &&
126 !ERRNO_IS_NOT_SUPPORTED(errno
))
129 if (end
- offset
>= size
) {
130 /* If we've created the full hole, set the file pointer to the end of the hole we created and exit. */
131 if (lseek(fd
, offset
+ size
, SEEK_SET
) < 0)
137 /* If we haven't created the full hole, use ftruncate() to grow the file (and the hole) to the
138 * required size and move the file pointer to the end of the file. */
140 size
-= end
- offset
;
142 if (ftruncate(fd
, end
+ size
) < 0)
145 if (lseek(fd
, 0, SEEK_END
) < 0)
154 CopyFlags copy_flags
,
156 size_t *ret_remains_size
,
157 copy_progress_bytes_t progress
,
160 bool try_cfr
= true, try_sendfile
= true, try_splice
= true, copied_something
= false;
161 int r
, nonblock_pipe
= -1;
162 size_t m
= SSIZE_MAX
; /* that is the maximum that sendfile and c_f_r accept */
167 /* Tries to copy bytes from the file descriptor 'fdf' to 'fdt' in the smartest possible way. Copies a maximum
168 * of 'max_bytes', which may be specified as UINT64_MAX, in which no maximum is applied. Returns negative on
169 * error, zero if EOF is hit before the bytes limit is hit and positive otherwise. If the copy fails for some
170 * reason but we read but didn't yet write some data an ret_remains/ret_remains_size is not NULL, then it will
171 * be initialized with an allocated buffer containing this "remaining" data. Note that these two parameters are
172 * initialized with a valid buffer only on failure and only if there's actually data already read. Otherwise
173 * these parameters if non-NULL are set to NULL. */
177 if (ret_remains_size
)
178 *ret_remains_size
= 0;
180 /* Try btrfs reflinks first. This only works on regular, seekable files, hence let's check the file offsets of
181 * source and destination first. */
182 if ((copy_flags
& COPY_REFLINK
)) {
185 foffset
= lseek(fdf
, 0, SEEK_CUR
);
189 toffset
= lseek(fdt
, 0, SEEK_CUR
);
192 if (foffset
== 0 && toffset
== 0 && max_bytes
== UINT64_MAX
)
193 r
= btrfs_reflink(fdf
, fdt
); /* full file reflink */
195 r
= btrfs_clone_range(fdf
, foffset
, fdt
, toffset
, max_bytes
== UINT64_MAX
? 0 : max_bytes
); /* partial reflink */
199 /* This worked, yay! Now — to be fully correct — let's adjust the file pointers */
200 if (max_bytes
== UINT64_MAX
) {
202 /* We cloned to the end of the source file, let's position the read
203 * pointer there, and query it at the same time. */
204 t
= lseek(fdf
, 0, SEEK_END
);
210 /* Let's adjust the destination file write pointer by the same number
212 t
= lseek(fdt
, toffset
+ (t
- foffset
), SEEK_SET
);
216 return 0; /* we copied the whole thing, hence hit EOF, return 0 */
218 t
= lseek(fdf
, foffset
+ max_bytes
, SEEK_SET
);
222 t
= lseek(fdt
, toffset
+ max_bytes
, SEEK_SET
);
226 return 1; /* we copied only some number of bytes, which worked, but this means we didn't hit EOF, return 1 */
237 return 1; /* return > 0 if we hit the max_bytes limit */
239 r
= look_for_signals(copy_flags
);
243 if (max_bytes
!= UINT64_MAX
&& m
> max_bytes
)
246 if (copy_flags
& COPY_HOLES
) {
249 c
= lseek(fdf
, 0, SEEK_CUR
);
253 /* To see if we're in a hole, we search for the next data offset. */
254 e
= lseek(fdf
, c
, SEEK_DATA
);
255 if (e
< 0 && errno
== ENXIO
)
256 /* If errno == ENXIO, that means we've reached the final hole of the file and
257 * that hole isn't followed by more data. */
258 e
= lseek(fdf
, 0, SEEK_END
);
262 /* If we're in a hole (current offset is not a data offset), create a hole of the
263 * same size in the target file. */
265 r
= create_hole(fdt
, e
- c
);
270 c
= e
; /* Set c to the start of the data segment. */
272 /* After copying a potential hole, find the end of the data segment by looking for
273 * the next hole. If we get ENXIO, we're at EOF. */
274 e
= lseek(fdf
, c
, SEEK_HOLE
);
281 /* SEEK_HOLE modifies the file offset so we need to move back to the initial offset. */
282 if (lseek(fdf
, c
, SEEK_SET
) < 0)
285 /* Make sure we're not copying more than the current data segment. */
286 m
= MIN(m
, (size_t) e
- c
);
289 /* First try copy_file_range(), unless we already tried */
291 n
= try_copy_file_range(fdf
, NULL
, fdt
, NULL
, m
, 0u);
293 if (!IN_SET(n
, -EINVAL
, -ENOSYS
, -EXDEV
, -EBADF
))
297 /* use fallback below */
298 } else if (n
== 0) { /* likely EOF */
300 if (copied_something
)
303 /* So, we hit EOF immediately, without having copied a single byte. This
304 * could indicate two things: the file is actually empty, or we are on some
305 * virtual file system such as procfs/sysfs where the syscall actually
306 * doesn't work but doesn't return an error. Try to handle that, by falling
307 * back to simple read()s in case we encounter empty files.
309 * See: https://lwn.net/Articles/846403/ */
310 try_cfr
= try_sendfile
= try_splice
= false;
316 /* First try sendfile(), unless we already tried */
318 n
= sendfile(fdt
, fdf
, NULL
, m
);
320 if (!IN_SET(errno
, EINVAL
, ENOSYS
))
323 try_sendfile
= false;
324 /* use fallback below */
325 } else if (n
== 0) { /* likely EOF */
327 if (copied_something
)
330 try_sendfile
= try_splice
= false; /* same logic as above for copy_file_range() */
336 /* Then try splice, unless we already tried. */
339 /* splice()'s asynchronous I/O support is a bit weird. When it encounters a pipe file
340 * descriptor, then it will ignore its O_NONBLOCK flag and instead only honour the
341 * SPLICE_F_NONBLOCK flag specified in its flag parameter. Let's hide this behaviour
342 * here, and check if either of the specified fds are a pipe, and if so, let's pass
343 * the flag automatically, depending on O_NONBLOCK being set.
345 * Here's a twist though: when we use it to move data between two pipes of which one
346 * has O_NONBLOCK set and the other has not, then we have no individual control over
347 * O_NONBLOCK behaviour. Hence in that case we can't use splice() and still guarantee
348 * systematic O_NONBLOCK behaviour, hence don't. */
350 if (nonblock_pipe
< 0) {
353 /* Check if either of these fds is a pipe, and if so non-blocking or not */
354 a
= fd_is_nonblock_pipe(fdf
);
358 b
= fd_is_nonblock_pipe(fdt
);
362 if ((a
== FD_IS_NO_PIPE
&& b
== FD_IS_NO_PIPE
) ||
363 (a
== FD_IS_BLOCKING_PIPE
&& b
== FD_IS_NONBLOCKING_PIPE
) ||
364 (a
== FD_IS_NONBLOCKING_PIPE
&& b
== FD_IS_BLOCKING_PIPE
))
366 /* splice() only works if one of the fds is a pipe. If neither is,
367 * let's skip this step right-away. As mentioned above, if one of the
368 * two fds refers to a blocking pipe and the other to a non-blocking
369 * pipe, we can't use splice() either, hence don't try either. This
370 * hence means we can only use splice() if either only one of the two
371 * fds is a pipe, or if both are pipes with the same nonblocking flag
376 nonblock_pipe
= a
== FD_IS_NONBLOCKING_PIPE
|| b
== FD_IS_NONBLOCKING_PIPE
;
381 n
= splice(fdf
, NULL
, fdt
, NULL
, m
, nonblock_pipe
? SPLICE_F_NONBLOCK
: 0);
383 if (!IN_SET(errno
, EINVAL
, ENOSYS
))
387 /* use fallback below */
388 } else if (n
== 0) { /* likely EOF */
390 if (copied_something
)
393 try_splice
= false; /* same logic as above for copy_file_range() + sendfile() */
399 /* As a fallback just copy bits by hand */
401 uint8_t buf
[MIN(m
, COPY_BUFFER_SIZE
)], *p
= buf
;
404 n
= read(fdf
, buf
, sizeof buf
);
407 if (n
== 0) /* EOF */
414 k
= write(fdt
, p
, z
);
428 if (ret_remains_size
)
429 *ret_remains_size
= z
;
442 r
= progress(n
, userdata
);
447 if (max_bytes
!= UINT64_MAX
) {
448 assert(max_bytes
>= (uint64_t) n
);
452 /* sendfile accepts at most SSIZE_MAX-offset bytes to copy, so reduce our maximum by the
453 * amount we already copied, but don't go below our copy buffer size, unless we are close the
454 * limit of bytes we are allowed to copy. */
455 m
= MAX(MIN(COPY_BUFFER_SIZE
, max_bytes
), m
- n
);
457 copied_something
= true;
460 return 0; /* return 0 if we hit EOF earlier than the size limit */
463 static int fd_copy_symlink(
466 const struct stat
*st
,
471 CopyFlags copy_flags
) {
473 _cleanup_free_
char *target
= NULL
;
480 r
= readlinkat_malloc(df
, from
, &target
);
484 if (copy_flags
& COPY_MAC_CREATE
) {
485 r
= mac_selinux_create_file_prepare_at(dt
, to
, S_IFLNK
);
489 r
= symlinkat(target
, dt
, to
);
490 if (copy_flags
& COPY_MAC_CREATE
)
491 mac_selinux_create_file_clear();
496 uid_is_valid(override_uid
) ? override_uid
: st
->st_uid
,
497 gid_is_valid(override_gid
) ? override_gid
: st
->st_gid
,
498 AT_SYMLINK_NOFOLLOW
) < 0)
501 (void) utimensat(dt
, to
, (struct timespec
[]) { st
->st_atim
, st
->st_mtim
}, AT_SYMLINK_NOFOLLOW
);
505 /* Encapsulates the database we store potential hardlink targets in */
506 typedef struct HardlinkContext
{
507 int dir_fd
; /* An fd to the directory we use as lookup table. Never AT_FDCWD. Lazily created, when
508 * we add the first entry. */
510 /* These two fields are used to create the hardlink repository directory above — via
511 * mkdirat(parent_fd, subdir) — and are kept so that we can automatically remove the directory again
512 * when we are done. */
513 int parent_fd
; /* Possibly AT_FDCWD */
517 static int hardlink_context_setup(
521 CopyFlags copy_flags
) {
523 _cleanup_close_
int dt_copy
= -1;
527 assert(c
->dir_fd
< 0 && c
->dir_fd
!= AT_FDCWD
);
528 assert(c
->parent_fd
< 0);
531 /* If hardlink recreation is requested we have to maintain a database of inodes that are potential
532 * hardlink sources. Given that generally disk sizes have to be assumed to be larger than what fits
533 * into physical RAM we cannot maintain that database in dynamic memory alone. Here we opt to
534 * maintain it on disk, to simplify things: inside the destination directory we'll maintain a
535 * temporary directory consisting of hardlinks of every inode we copied that might be subject of
536 * hardlinks. We can then use that as hardlink source later on. Yes, this means additional disk IO
537 * but thankfully Linux is optimized for this kind of thing. If this ever becomes a performance
538 * bottleneck we can certainly place an in-memory hash table in front of this, but for the beginning,
539 * let's keep things simple, and just use the disk as lookup table for inodes.
541 * Note that this should have zero performance impact as long as .n_link of all files copied remains
542 * <= 0, because in that case we will not actually allocate the hardlink inode lookup table directory
543 * on disk (we do so lazily, when the first candidate with .n_link > 1 is seen). This means, in the
544 * common case where hardlinks are not used at all or only for few files the fact that we store the
545 * table on disk shouldn't matter perfomance-wise. */
547 if (!FLAGS_SET(copy_flags
, COPY_HARDLINKS
))
555 dt_copy
= fcntl(dt
, F_DUPFD_CLOEXEC
, 3);
560 r
= tempfn_random_child(to
, "hardlink", &c
->subdir
);
564 c
->parent_fd
= TAKE_FD(dt_copy
);
566 /* We don't actually create the directory we keep the table in here, that's done on-demand when the
567 * first entry is added, using hardlink_context_realize() below. */
571 static int hardlink_context_realize(HardlinkContext
*c
) {
575 if (c
->dir_fd
>= 0) /* Already realized */
578 if (c
->parent_fd
< 0 && c
->parent_fd
!= AT_FDCWD
) /* Not configured */
583 c
->dir_fd
= open_mkdir_at(c
->parent_fd
, c
->subdir
, O_EXCL
|O_CLOEXEC
, 0700);
590 static void hardlink_context_destroy(HardlinkContext
*c
) {
595 /* Automatically remove the hardlink lookup table directory again after we are done. This is used via
596 * _cleanup_() so that we really delete this, even on failure. */
598 if (c
->dir_fd
>= 0) {
599 r
= rm_rf_children(TAKE_FD(c
->dir_fd
), REMOVE_PHYSICAL
, NULL
); /* consumes dir_fd in all cases, even on failure */
601 log_debug_errno(r
, "Failed to remove hardlink store (%s) contents, ignoring: %m", c
->subdir
);
603 assert(c
->parent_fd
>= 0 || c
->parent_fd
== AT_FDCWD
);
606 if (unlinkat(c
->parent_fd
, c
->subdir
, AT_REMOVEDIR
) < 0)
607 log_debug_errno(errno
, "Failed to remove hardlink store (%s) directory, ignoring: %m", c
->subdir
);
610 assert_cc(AT_FDCWD
< 0);
611 c
->parent_fd
= safe_close(c
->parent_fd
);
613 c
->subdir
= mfree(c
->subdir
);
616 static int try_hardlink(
618 const struct stat
*st
,
622 char dev_ino
[DECIMAL_STR_MAX(dev_t
)*2 + DECIMAL_STR_MAX(uint64_t) + 4];
625 assert(dt
>= 0 || dt
== AT_FDCWD
);
628 if (!c
) /* No temporary hardlink directory, don't bother */
631 if (st
->st_nlink
<= 1) /* Source not hardlinked, don't bother */
634 if (c
->dir_fd
< 0) /* not yet realized, hence empty */
637 xsprintf(dev_ino
, "%u:%u:%" PRIu64
, major(st
->st_dev
), minor(st
->st_dev
), (uint64_t) st
->st_ino
);
638 if (linkat(c
->dir_fd
, dev_ino
, dt
, to
, 0) < 0) {
639 if (errno
!= ENOENT
) /* doesn't exist in store yet */
640 log_debug_errno(errno
, "Failed to hardlink %s to %s, ignoring: %m", dev_ino
, to
);
647 static int memorize_hardlink(
649 const struct stat
*st
,
653 char dev_ino
[DECIMAL_STR_MAX(dev_t
)*2 + DECIMAL_STR_MAX(uint64_t) + 4];
657 assert(dt
>= 0 || dt
== AT_FDCWD
);
660 if (!c
) /* No temporary hardlink directory, don't bother */
663 if (st
->st_nlink
<= 1) /* Source not hardlinked, don't bother */
666 r
= hardlink_context_realize(c
); /* Create the hardlink store lazily */
670 xsprintf(dev_ino
, "%u:%u:%" PRIu64
, major(st
->st_dev
), minor(st
->st_dev
), (uint64_t) st
->st_ino
);
671 if (linkat(dt
, to
, c
->dir_fd
, dev_ino
, 0) < 0) {
672 log_debug_errno(errno
, "Failed to hardlink %s to %s, ignoring: %m", to
, dev_ino
);
679 static int fd_copy_tree_generic(
682 const struct stat
*st
,
685 dev_t original_device
,
689 CopyFlags copy_flags
,
691 HardlinkContext
*hardlink_context
,
692 const char *display_path
,
693 copy_progress_path_t progress_path
,
694 copy_progress_bytes_t progress_bytes
,
697 static int fd_copy_regular(
700 const struct stat
*st
,
705 CopyFlags copy_flags
,
706 HardlinkContext
*hardlink_context
,
707 copy_progress_bytes_t progress
,
710 _cleanup_close_
int fdf
= -1, fdt
= -1;
717 r
= try_hardlink(hardlink_context
, st
, dt
, to
);
720 if (r
> 0) /* worked! */
723 fdf
= openat(df
, from
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
727 if (copy_flags
& COPY_MAC_CREATE
) {
728 r
= mac_selinux_create_file_prepare_at(dt
, to
, S_IFREG
);
732 fdt
= openat(dt
, to
, O_WRONLY
|O_CREAT
|O_EXCL
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
, st
->st_mode
& 07777);
733 if (copy_flags
& COPY_MAC_CREATE
)
734 mac_selinux_create_file_clear();
738 r
= copy_bytes_full(fdf
, fdt
, UINT64_MAX
, copy_flags
, NULL
, NULL
, progress
, userdata
);
743 uid_is_valid(override_uid
) ? override_uid
: st
->st_uid
,
744 gid_is_valid(override_gid
) ? override_gid
: st
->st_gid
) < 0)
747 if (fchmod(fdt
, st
->st_mode
& 07777) < 0)
750 (void) futimens(fdt
, (struct timespec
[]) { st
->st_atim
, st
->st_mtim
});
751 (void) copy_xattr(fdf
, fdt
, copy_flags
);
753 if (copy_flags
& COPY_FSYNC
) {
754 if (fsync(fdt
) < 0) {
760 q
= close_nointr(TAKE_FD(fdt
)); /* even if this fails, the fd is now invalidated */
766 (void) memorize_hardlink(hardlink_context
, st
, dt
, to
);
770 (void) unlinkat(dt
, to
, 0);
774 static int fd_copy_fifo(
777 const struct stat
*st
,
782 CopyFlags copy_flags
,
783 HardlinkContext
*hardlink_context
) {
790 r
= try_hardlink(hardlink_context
, st
, dt
, to
);
793 if (r
> 0) /* worked! */
796 if (copy_flags
& COPY_MAC_CREATE
) {
797 r
= mac_selinux_create_file_prepare_at(dt
, to
, S_IFIFO
);
801 r
= mkfifoat(dt
, to
, st
->st_mode
& 07777);
802 if (copy_flags
& COPY_MAC_CREATE
)
803 mac_selinux_create_file_clear();
808 uid_is_valid(override_uid
) ? override_uid
: st
->st_uid
,
809 gid_is_valid(override_gid
) ? override_gid
: st
->st_gid
,
810 AT_SYMLINK_NOFOLLOW
) < 0)
813 if (fchmodat(dt
, to
, st
->st_mode
& 07777, 0) < 0)
816 (void) utimensat(dt
, to
, (struct timespec
[]) { st
->st_atim
, st
->st_mtim
}, AT_SYMLINK_NOFOLLOW
);
818 (void) memorize_hardlink(hardlink_context
, st
, dt
, to
);
822 static int fd_copy_node(
825 const struct stat
*st
,
830 CopyFlags copy_flags
,
831 HardlinkContext
*hardlink_context
) {
838 r
= try_hardlink(hardlink_context
, st
, dt
, to
);
841 if (r
> 0) /* worked! */
844 if (copy_flags
& COPY_MAC_CREATE
) {
845 r
= mac_selinux_create_file_prepare_at(dt
, to
, st
->st_mode
& S_IFMT
);
849 r
= mknodat(dt
, to
, st
->st_mode
, st
->st_rdev
);
850 if (copy_flags
& COPY_MAC_CREATE
)
851 mac_selinux_create_file_clear();
856 uid_is_valid(override_uid
) ? override_uid
: st
->st_uid
,
857 gid_is_valid(override_gid
) ? override_gid
: st
->st_gid
,
858 AT_SYMLINK_NOFOLLOW
) < 0)
861 if (fchmodat(dt
, to
, st
->st_mode
& 07777, 0) < 0)
864 (void) utimensat(dt
, to
, (struct timespec
[]) { st
->st_atim
, st
->st_mtim
}, AT_SYMLINK_NOFOLLOW
);
866 (void) memorize_hardlink(hardlink_context
, st
, dt
, to
);
870 static int fd_copy_directory(
873 const struct stat
*st
,
876 dev_t original_device
,
880 CopyFlags copy_flags
,
882 HardlinkContext
*hardlink_context
,
883 const char *display_path
,
884 copy_progress_path_t progress_path
,
885 copy_progress_bytes_t progress_bytes
,
888 _cleanup_(hardlink_context_destroy
) HardlinkContext our_hardlink_context
= {
893 _cleanup_close_
int fdf
= -1, fdt
= -1;
894 _cleanup_closedir_
DIR *d
= NULL
;
895 bool exists
, created
;
902 return -ENAMETOOLONG
;
905 fdf
= openat(df
, from
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
907 fdf
= fcntl(df
, F_DUPFD_CLOEXEC
, 3);
911 if (!hardlink_context
) {
912 /* If recreating hardlinks is requested let's set up a context for that now. */
913 r
= hardlink_context_setup(&our_hardlink_context
, dt
, to
, copy_flags
);
916 if (r
> 0) /* It's enabled and allocated, let's now use the same context for all recursive
917 * invocations from here down */
918 hardlink_context
= &our_hardlink_context
;
921 d
= take_fdopendir(&fdf
);
926 if (copy_flags
& COPY_MERGE_EMPTY
) {
927 r
= dir_is_empty_at(dt
, to
, /* ignore_hidden_or_backup= */ false);
928 if (r
< 0 && r
!= -ENOENT
)
937 if (copy_flags
& COPY_MAC_CREATE
)
938 r
= mkdirat_label(dt
, to
, st
->st_mode
& 07777);
940 r
= mkdirat(dt
, to
, st
->st_mode
& 07777);
943 else if (errno
== EEXIST
&& (copy_flags
& COPY_MERGE
))
949 fdt
= openat(dt
, to
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
955 FOREACH_DIRENT_ALL(de
, d
, return -errno
) {
956 const char *child_display_path
= NULL
;
957 _cleanup_free_
char *dp
= NULL
;
961 if (dot_or_dot_dot(de
->d_name
))
964 r
= look_for_signals(copy_flags
);
968 if (fstatat(dirfd(d
), de
->d_name
, &buf
, AT_SYMLINK_NOFOLLOW
) < 0) {
975 child_display_path
= dp
= path_join(display_path
, de
->d_name
);
977 child_display_path
= de
->d_name
;
979 r
= progress_path(child_display_path
, &buf
, userdata
);
984 if (set_contains(denylist
, &buf
)) {
985 log_debug("%s/%s is in the denylist, skipping", from
, de
->d_name
);
989 if (S_ISDIR(buf
.st_mode
)) {
991 * Don't descend into directories on other file systems, if this is requested. We do a simple
992 * .st_dev check here, which basically comes for free. Note that we do this check only on
993 * directories, not other kind of file system objects, for two reason:
995 * • The kernel's overlayfs pseudo file system that overlays multiple real file systems
996 * propagates the .st_dev field of the file system a file originates from all the way up
997 * through the stack to stat(). It doesn't do that for directories however. This means that
998 * comparing .st_dev on non-directories suggests that they all are mount points. To avoid
999 * confusion we hence avoid relying on this check for regular files.
1001 * • The main reason we do this check at all is to protect ourselves from bind mount cycles,
1002 * where we really want to avoid descending down in all eternity. However the .st_dev check
1003 * is usually not sufficient for this protection anyway, as bind mount cycles from the same
1004 * file system onto itself can't be detected that way. (Note we also do a recursion depth
1005 * check, which is probably the better protection in this regard, which is why
1006 * COPY_SAME_MOUNT is optional).
1009 if (FLAGS_SET(copy_flags
, COPY_SAME_MOUNT
)) {
1010 if (buf
.st_dev
!= original_device
)
1013 r
= fd_is_mount_point(dirfd(d
), de
->d_name
, 0);
1021 q
= fd_copy_tree_generic(dirfd(d
), de
->d_name
, &buf
, fdt
, de
->d_name
, original_device
,
1022 depth_left
-1, override_uid
, override_gid
, copy_flags
, denylist
,
1023 hardlink_context
, child_display_path
, progress_path
, progress_bytes
,
1026 if (q
== -EINTR
) /* Propagate SIGINT/SIGTERM up instantly */
1028 if (q
== -EEXIST
&& (copy_flags
& COPY_MERGE
))
1036 uid_is_valid(override_uid
) ? override_uid
: st
->st_uid
,
1037 gid_is_valid(override_gid
) ? override_gid
: st
->st_gid
) < 0)
1040 if (fchmod(fdt
, st
->st_mode
& 07777) < 0)
1043 (void) copy_xattr(dirfd(d
), fdt
, copy_flags
);
1044 (void) futimens(fdt
, (struct timespec
[]) { st
->st_atim
, st
->st_mtim
});
1047 if (copy_flags
& COPY_FSYNC_FULL
) {
1055 static int fd_copy_leaf(
1058 const struct stat
*st
,
1063 CopyFlags copy_flags
,
1064 HardlinkContext
*hardlink_context
,
1065 const char *display_path
,
1066 copy_progress_bytes_t progress_bytes
,
1070 if (S_ISREG(st
->st_mode
))
1071 r
= fd_copy_regular(df
, from
, st
, dt
, to
, override_uid
, override_gid
, copy_flags
, hardlink_context
, progress_bytes
, userdata
);
1072 else if (S_ISLNK(st
->st_mode
))
1073 r
= fd_copy_symlink(df
, from
, st
, dt
, to
, override_uid
, override_gid
, copy_flags
);
1074 else if (S_ISFIFO(st
->st_mode
))
1075 r
= fd_copy_fifo(df
, from
, st
, dt
, to
, override_uid
, override_gid
, copy_flags
, hardlink_context
);
1076 else if (S_ISBLK(st
->st_mode
) || S_ISCHR(st
->st_mode
) || S_ISSOCK(st
->st_mode
))
1077 r
= fd_copy_node(df
, from
, st
, dt
, to
, override_uid
, override_gid
, copy_flags
, hardlink_context
);
1084 static int fd_copy_tree_generic(
1087 const struct stat
*st
,
1090 dev_t original_device
,
1091 unsigned depth_left
,
1094 CopyFlags copy_flags
,
1095 const Set
*denylist
,
1096 HardlinkContext
*hardlink_context
,
1097 const char *display_path
,
1098 copy_progress_path_t progress_path
,
1099 copy_progress_bytes_t progress_bytes
,
1103 if (S_ISDIR(st
->st_mode
))
1104 return fd_copy_directory(df
, from
, st
, dt
, to
, original_device
, depth_left
-1, override_uid
,
1105 override_gid
, copy_flags
, denylist
, hardlink_context
, display_path
,
1106 progress_path
, progress_bytes
, userdata
);
1108 r
= fd_copy_leaf(df
, from
, st
, dt
, to
, override_uid
, override_gid
, copy_flags
, hardlink_context
, display_path
, progress_bytes
, userdata
);
1109 /* We just tried to copy a leaf node of the tree. If it failed because the node already exists *and* the COPY_REPLACE flag has been provided, we should unlink the node and re-copy. */
1110 if (r
== -EEXIST
&& (copy_flags
& COPY_REPLACE
)) {
1111 /* This codepath is us trying to address an error to copy, if the unlink fails, lets just return the original error. */
1112 if (unlinkat(dt
, to
, 0) < 0)
1115 r
= fd_copy_leaf(df
, from
, st
, dt
, to
, override_uid
, override_gid
, copy_flags
, hardlink_context
, display_path
, progress_bytes
, userdata
);
1121 int copy_tree_at_full(
1128 CopyFlags copy_flags
,
1129 const Set
*denylist
,
1130 copy_progress_path_t progress_path
,
1131 copy_progress_bytes_t progress_bytes
,
1140 if (fstatat(fdf
, from
, &st
, AT_SYMLINK_NOFOLLOW
) < 0)
1143 r
= fd_copy_tree_generic(fdf
, from
, &st
, fdt
, to
, st
.st_dev
, COPY_DEPTH_MAX
, override_uid
,
1144 override_gid
, copy_flags
, denylist
, NULL
, NULL
, progress_path
,
1145 progress_bytes
, userdata
);
1149 if (S_ISDIR(st
.st_mode
) && (copy_flags
& COPY_SYNCFS
)) {
1150 /* If the top-level inode is a directory run syncfs() now. */
1151 r
= syncfs_path(fdt
, to
);
1154 } else if ((copy_flags
& (COPY_FSYNC_FULL
|COPY_SYNCFS
)) != 0) {
1155 /* fsync() the parent dir of what we just copied if COPY_FSYNC_FULL is set. Also do this in
1156 * case COPY_SYNCFS is set but the top-level inode wasn't actually a directory. We do this so that
1157 * COPY_SYNCFS provides reasonable synchronization semantics on any kind of inode: when the
1158 * copy operation is done the whole inode — regardless of its type — and all its children
1159 * will be synchronized to disk. */
1160 r
= fsync_parent_at(fdt
, to
);
1168 static int sync_dir_by_flags(const char *path
, CopyFlags copy_flags
) {
1170 if (copy_flags
& COPY_SYNCFS
)
1171 return syncfs_path(AT_FDCWD
, path
);
1172 if (copy_flags
& COPY_FSYNC_FULL
)
1173 return fsync_parent_at(AT_FDCWD
, path
);
1178 int copy_directory_fd_full(
1181 CopyFlags copy_flags
,
1182 copy_progress_path_t progress_path
,
1183 copy_progress_bytes_t progress_bytes
,
1192 if (fstat(dirfd
, &st
) < 0)
1195 r
= stat_verify_directory(&st
);
1199 r
= fd_copy_directory(
1205 UID_INVALID
, GID_INVALID
,
1214 r
= sync_dir_by_flags(to
, copy_flags
);
1221 int copy_directory_full(
1224 CopyFlags copy_flags
,
1225 copy_progress_path_t progress_path
,
1226 copy_progress_bytes_t progress_bytes
,
1235 if (lstat(from
, &st
) < 0)
1238 r
= stat_verify_directory(&st
);
1242 r
= fd_copy_directory(
1248 UID_INVALID
, GID_INVALID
,
1257 r
= sync_dir_by_flags(to
, copy_flags
);
1264 int copy_file_fd_full(
1267 CopyFlags copy_flags
,
1268 copy_progress_bytes_t progress_bytes
,
1271 _cleanup_close_
int fdf
= -1;
1278 fdf
= open(from
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
1282 r
= fd_verify_regular(fdf
);
1286 if (fstat(fdt
, &st
) < 0)
1289 r
= copy_bytes_full(fdf
, fdt
, UINT64_MAX
, copy_flags
, NULL
, NULL
, progress_bytes
, userdata
);
1293 /* Make sure to copy file attributes only over if target is a regular
1294 * file (so that copying a file to /dev/null won't alter the access
1295 * mode/ownership of that device node...) */
1296 if (S_ISREG(st
.st_mode
)) {
1297 (void) copy_times(fdf
, fdt
, copy_flags
);
1298 (void) copy_xattr(fdf
, fdt
, copy_flags
);
1301 if (copy_flags
& COPY_FSYNC_FULL
) {
1302 r
= fsync_full(fdt
);
1305 } else if (copy_flags
& COPY_FSYNC
) {
1318 unsigned chattr_flags
,
1319 unsigned chattr_mask
,
1320 CopyFlags copy_flags
,
1321 copy_progress_bytes_t progress_bytes
,
1324 _cleanup_close_
int fdf
= -1, fdt
= -1;
1331 fdf
= open(from
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
1335 if (fstat(fdf
, &st
) < 0)
1338 r
= stat_verify_regular(&st
);
1342 RUN_WITH_UMASK(0000) {
1343 if (copy_flags
& COPY_MAC_CREATE
) {
1344 r
= mac_selinux_create_file_prepare(to
, S_IFREG
);
1348 fdt
= open(to
, flags
|O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
,
1349 mode
!= MODE_INVALID
? mode
: st
.st_mode
);
1350 if (copy_flags
& COPY_MAC_CREATE
)
1351 mac_selinux_create_file_clear();
1356 if (!FLAGS_SET(flags
, O_EXCL
)) { /* if O_EXCL was used we created the thing as regular file, no need to check again */
1357 r
= fd_verify_regular(fdt
);
1362 if (chattr_mask
!= 0)
1363 (void) chattr_fd(fdt
, chattr_flags
, chattr_mask
& CHATTR_EARLY_FL
, NULL
);
1365 r
= copy_bytes_full(fdf
, fdt
, UINT64_MAX
, copy_flags
, NULL
, NULL
, progress_bytes
, userdata
);
1369 (void) copy_times(fdf
, fdt
, copy_flags
);
1370 (void) copy_xattr(fdf
, fdt
, copy_flags
);
1372 if (chattr_mask
!= 0)
1373 (void) chattr_fd(fdt
, chattr_flags
, chattr_mask
& ~CHATTR_EARLY_FL
, NULL
);
1375 if (copy_flags
& (COPY_FSYNC
|COPY_FSYNC_FULL
)) {
1376 if (fsync(fdt
) < 0) {
1382 r
= close_nointr(TAKE_FD(fdt
)); /* even if this fails, the fd is now invalidated */
1386 if (copy_flags
& COPY_FSYNC_FULL
) {
1387 r
= fsync_parent_at(AT_FDCWD
, to
);
1395 /* Only unlink if we definitely are the ones who created the file */
1396 if (FLAGS_SET(flags
, O_EXCL
))
1402 int copy_file_atomic_full(
1406 unsigned chattr_flags
,
1407 unsigned chattr_mask
,
1408 CopyFlags copy_flags
,
1409 copy_progress_bytes_t progress_bytes
,
1412 _cleanup_(unlink_and_freep
) char *t
= NULL
;
1413 _cleanup_close_
int fdt
= -1;
1419 /* We try to use O_TMPFILE here to create the file if we can. Note that this only works if COPY_REPLACE is not
1420 * set though as we need to use linkat() for linking the O_TMPFILE file into the file system but that system
1421 * call can't replace existing files. Hence, if COPY_REPLACE is set we create a temporary name in the file
1422 * system right-away and unconditionally which we then can renameat() to the right name after we completed
1425 if (copy_flags
& COPY_REPLACE
) {
1426 _cleanup_free_
char *f
= NULL
;
1428 r
= tempfn_random(to
, NULL
, &f
);
1432 if (copy_flags
& COPY_MAC_CREATE
) {
1433 r
= mac_selinux_create_file_prepare(to
, S_IFREG
);
1437 fdt
= open(f
, O_CREAT
|O_EXCL
|O_NOFOLLOW
|O_NOCTTY
|O_WRONLY
|O_CLOEXEC
, 0600);
1438 if (copy_flags
& COPY_MAC_CREATE
)
1439 mac_selinux_create_file_clear();
1445 if (copy_flags
& COPY_MAC_CREATE
) {
1446 r
= mac_selinux_create_file_prepare(to
, S_IFREG
);
1450 fdt
= open_tmpfile_linkable(to
, O_WRONLY
|O_CLOEXEC
, &t
);
1451 if (copy_flags
& COPY_MAC_CREATE
)
1452 mac_selinux_create_file_clear();
1457 if (chattr_mask
!= 0)
1458 (void) chattr_fd(fdt
, chattr_flags
, chattr_mask
& CHATTR_EARLY_FL
, NULL
);
1460 r
= copy_file_fd_full(from
, fdt
, copy_flags
, progress_bytes
, userdata
);
1464 if (fchmod(fdt
, mode
) < 0)
1467 if ((copy_flags
& (COPY_FSYNC
|COPY_FSYNC_FULL
))) {
1473 if (copy_flags
& COPY_REPLACE
) {
1474 if (renameat(AT_FDCWD
, t
, AT_FDCWD
, to
) < 0)
1477 r
= link_tmpfile(fdt
, t
, to
);
1484 if (chattr_mask
!= 0)
1485 (void) chattr_fd(fdt
, chattr_flags
, chattr_mask
& ~CHATTR_EARLY_FL
, NULL
);
1487 r
= close_nointr(TAKE_FD(fdt
)); /* even if this fails, the fd is now invalidated */
1491 if (copy_flags
& COPY_FSYNC_FULL
) {
1492 /* Sync the parent directory */
1493 r
= fsync_parent_at(AT_FDCWD
, to
);
1505 int copy_times(int fdf
, int fdt
, CopyFlags flags
) {
1511 if (fstat(fdf
, &st
) < 0)
1514 if (futimens(fdt
, (struct timespec
[2]) { st
.st_atim
, st
.st_mtim
}) < 0)
1517 if (FLAGS_SET(flags
, COPY_CRTIME
)) {
1520 if (fd_getcrtime(fdf
, &crtime
) >= 0)
1521 (void) fd_setcrtime(fdt
, crtime
);
1527 int copy_access(int fdf
, int fdt
) {
1533 /* Copies just the access mode (and not the ownership) from fdf to fdt */
1535 if (fstat(fdf
, &st
) < 0)
1538 return RET_NERRNO(fchmod(fdt
, st
.st_mode
& 07777));
1541 int copy_rights_with_fallback(int fdf
, int fdt
, const char *patht
) {
1547 /* Copies both access mode and ownership from fdf to fdt */
1549 if (fstat(fdf
, &st
) < 0)
1552 return fchmod_and_chown_with_fallback(fdt
, patht
, st
.st_mode
& 07777, st
.st_uid
, st
.st_gid
);
1555 int copy_xattr(int fdf
, int fdt
, CopyFlags copy_flags
) {
1556 _cleanup_free_
char *names
= NULL
;
1560 r
= flistxattr_malloc(fdf
, &names
);
1564 NULSTR_FOREACH(p
, names
) {
1565 _cleanup_free_
char *value
= NULL
;
1567 if (!FLAGS_SET(copy_flags
, COPY_ALL_XATTRS
) && !startswith(p
, "user."))
1570 r
= fgetxattr_malloc(fdf
, p
, &value
);
1572 continue; /* gone by now */
1576 if (fsetxattr(fdt
, p
, value
, r
, 0) < 0)