1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
5 #include <linux/btrfs.h>
10 #include <sys/sendfile.h>
11 #include <sys/xattr.h>
14 #include "alloc-util.h"
15 #include "btrfs-util.h"
16 #include "chattr-util.h"
18 #include "dirent-util.h"
24 #include "missing_fs.h"
25 #include "missing_syscall.h"
26 #include "mkdir-label.h"
27 #include "mountpoint-util.h"
28 #include "nulstr-util.h"
30 #include "selinux-util.h"
31 #include "signal-util.h"
32 #include "stat-util.h"
33 #include "stdio-util.h"
34 #include "string-util.h"
36 #include "sync-util.h"
37 #include "time-util.h"
38 #include "tmpfile-util.h"
39 #include "umask-util.h"
40 #include "user-util.h"
41 #include "xattr-util.h"
43 #define COPY_BUFFER_SIZE (16U*1024U)
45 /* A safety net for descending recursively into file system trees to copy. On Linux PATH_MAX is 4096, which means the
46 * deepest valid path one can build is around 2048, which we hence use as a safety net here, to not spin endlessly in
47 * case of bind mount cycles and suchlike. */
48 #define COPY_DEPTH_MAX 2048U
50 static ssize_t
try_copy_file_range(
51 int fd_in
, loff_t
*off_in
,
52 int fd_out
, loff_t
*off_out
,
62 r
= copy_file_range(fd_in
, off_in
, fd_out
, off_out
, len
, flags
);
64 have
= r
>= 0 || errno
!= ENOSYS
;
74 FD_IS_NONBLOCKING_PIPE
,
77 static int fd_is_nonblock_pipe(int fd
) {
81 /* Checks whether the specified file descriptor refers to a pipe, and if so if O_NONBLOCK is set. */
83 if (fstat(fd
, &st
) < 0)
86 if (!S_ISFIFO(st
.st_mode
))
89 flags
= fcntl(fd
, F_GETFL
);
93 return FLAGS_SET(flags
, O_NONBLOCK
) ? FD_IS_NONBLOCKING_PIPE
: FD_IS_BLOCKING_PIPE
;
96 static int look_for_signals(CopyFlags copy_flags
) {
99 if ((copy_flags
& (COPY_SIGINT
|COPY_SIGTERM
)) == 0)
102 r
= pop_pending_signal(copy_flags
& COPY_SIGINT
? SIGINT
: 0,
103 copy_flags
& COPY_SIGTERM
? SIGTERM
: 0);
107 return log_debug_errno(SYNTHETIC_ERRNO(EINTR
),
108 "Got %s, cancelling copy operation.", signal_to_string(r
));
113 static int create_hole(int fd
, off_t size
) {
117 offset
= lseek(fd
, 0, SEEK_CUR
);
121 end
= lseek(fd
, 0, SEEK_END
);
125 /* If we're not at the end of the target file, try to punch a hole in the existing space using fallocate(). */
128 fallocate(fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
, offset
, MIN(size
, end
- offset
)) < 0 &&
129 !ERRNO_IS_NOT_SUPPORTED(errno
))
132 if (end
- offset
>= size
) {
133 /* If we've created the full hole, set the file pointer to the end of the hole we created and exit. */
134 if (lseek(fd
, offset
+ size
, SEEK_SET
) < 0)
140 /* If we haven't created the full hole, use ftruncate() to grow the file (and the hole) to the
141 * required size and move the file pointer to the end of the file. */
143 size
-= end
- offset
;
145 if (ftruncate(fd
, end
+ size
) < 0)
148 if (lseek(fd
, 0, SEEK_END
) < 0)
157 CopyFlags copy_flags
,
159 size_t *ret_remains_size
,
160 copy_progress_bytes_t progress
,
163 _cleanup_close_
int fdf_opened
= -EBADF
, fdt_opened
= -EBADF
;
164 bool try_cfr
= true, try_sendfile
= true, try_splice
= true, copied_something
= false;
165 int r
, nonblock_pipe
= -1;
166 size_t m
= SSIZE_MAX
; /* that is the maximum that sendfile and c_f_r accept */
171 /* Tries to copy bytes from the file descriptor 'fdf' to 'fdt' in the smartest possible way. Copies a maximum
172 * of 'max_bytes', which may be specified as UINT64_MAX, in which no maximum is applied. Returns negative on
173 * error, zero if EOF is hit before the bytes limit is hit and positive otherwise. If the copy fails for some
174 * reason but we read but didn't yet write some data an ret_remains/ret_remains_size is not NULL, then it will
175 * be initialized with an allocated buffer containing this "remaining" data. Note that these two parameters are
176 * initialized with a valid buffer only on failure and only if there's actually data already read. Otherwise
177 * these parameters if non-NULL are set to NULL. */
181 if (ret_remains_size
)
182 *ret_remains_size
= 0;
184 fdf
= fd_reopen_condition(fdf
, O_CLOEXEC
| O_NOCTTY
| O_RDONLY
, O_PATH
, &fdf_opened
);
187 fdt
= fd_reopen_condition(fdt
, O_CLOEXEC
| O_NOCTTY
| O_RDWR
, O_PATH
, &fdt_opened
);
191 /* Try btrfs reflinks first. This only works on regular, seekable files, hence let's check the file offsets of
192 * source and destination first. */
193 if ((copy_flags
& COPY_REFLINK
)) {
196 foffset
= lseek(fdf
, 0, SEEK_CUR
);
200 toffset
= lseek(fdt
, 0, SEEK_CUR
);
203 if (foffset
== 0 && toffset
== 0 && max_bytes
== UINT64_MAX
)
204 r
= reflink(fdf
, fdt
); /* full file reflink */
206 r
= reflink_range(fdf
, foffset
, fdt
, toffset
, max_bytes
== UINT64_MAX
? 0 : max_bytes
); /* partial reflink */
210 /* This worked, yay! Now — to be fully correct — let's adjust the file pointers */
211 if (max_bytes
== UINT64_MAX
) {
213 /* We cloned to the end of the source file, let's position the read
214 * pointer there, and query it at the same time. */
215 t
= lseek(fdf
, 0, SEEK_END
);
221 /* Let's adjust the destination file write pointer by the same number
223 t
= lseek(fdt
, toffset
+ (t
- foffset
), SEEK_SET
);
227 return 0; /* we copied the whole thing, hence hit EOF, return 0 */
229 t
= lseek(fdf
, foffset
+ max_bytes
, SEEK_SET
);
233 t
= lseek(fdt
, toffset
+ max_bytes
, SEEK_SET
);
237 return 1; /* we copied only some number of bytes, which worked, but this means we didn't hit EOF, return 1 */
250 r
= look_for_signals(copy_flags
);
254 if (max_bytes
!= UINT64_MAX
&& m
> max_bytes
)
257 if (copy_flags
& COPY_HOLES
) {
260 c
= lseek(fdf
, 0, SEEK_CUR
);
264 /* To see if we're in a hole, we search for the next data offset. */
265 e
= lseek(fdf
, c
, SEEK_DATA
);
266 if (e
< 0 && errno
== ENXIO
)
267 /* If errno == ENXIO, that means we've reached the final hole of the file and
268 * that hole isn't followed by more data. */
269 e
= lseek(fdf
, 0, SEEK_END
);
273 /* If we're in a hole (current offset is not a data offset), create a hole of the
274 * same size in the target file. */
276 r
= create_hole(fdt
, e
- c
);
281 c
= e
; /* Set c to the start of the data segment. */
283 /* After copying a potential hole, find the end of the data segment by looking for
284 * the next hole. If we get ENXIO, we're at EOF. */
285 e
= lseek(fdf
, c
, SEEK_HOLE
);
292 /* SEEK_HOLE modifies the file offset so we need to move back to the initial offset. */
293 if (lseek(fdf
, c
, SEEK_SET
) < 0)
296 /* Make sure we're not copying more than the current data segment. */
297 m
= MIN(m
, (size_t) e
- c
);
300 /* First try copy_file_range(), unless we already tried */
302 n
= try_copy_file_range(fdf
, NULL
, fdt
, NULL
, m
, 0u);
304 if (!IN_SET(n
, -EINVAL
, -ENOSYS
, -EXDEV
, -EBADF
))
308 /* use fallback below */
309 } else if (n
== 0) { /* likely EOF */
311 if (copied_something
)
314 /* So, we hit EOF immediately, without having copied a single byte. This
315 * could indicate two things: the file is actually empty, or we are on some
316 * virtual file system such as procfs/sysfs where the syscall actually
317 * doesn't work but doesn't return an error. Try to handle that, by falling
318 * back to simple read()s in case we encounter empty files.
320 * See: https://lwn.net/Articles/846403/ */
321 try_cfr
= try_sendfile
= try_splice
= false;
327 /* First try sendfile(), unless we already tried */
329 n
= sendfile(fdt
, fdf
, NULL
, m
);
331 if (!IN_SET(errno
, EINVAL
, ENOSYS
))
334 try_sendfile
= false;
335 /* use fallback below */
336 } else if (n
== 0) { /* likely EOF */
338 if (copied_something
)
341 try_sendfile
= try_splice
= false; /* same logic as above for copy_file_range() */
347 /* Then try splice, unless we already tried. */
350 /* splice()'s asynchronous I/O support is a bit weird. When it encounters a pipe file
351 * descriptor, then it will ignore its O_NONBLOCK flag and instead only honour the
352 * SPLICE_F_NONBLOCK flag specified in its flag parameter. Let's hide this behaviour
353 * here, and check if either of the specified fds are a pipe, and if so, let's pass
354 * the flag automatically, depending on O_NONBLOCK being set.
356 * Here's a twist though: when we use it to move data between two pipes of which one
357 * has O_NONBLOCK set and the other has not, then we have no individual control over
358 * O_NONBLOCK behaviour. Hence in that case we can't use splice() and still guarantee
359 * systematic O_NONBLOCK behaviour, hence don't. */
361 if (nonblock_pipe
< 0) {
364 /* Check if either of these fds is a pipe, and if so non-blocking or not */
365 a
= fd_is_nonblock_pipe(fdf
);
369 b
= fd_is_nonblock_pipe(fdt
);
373 if ((a
== FD_IS_NO_PIPE
&& b
== FD_IS_NO_PIPE
) ||
374 (a
== FD_IS_BLOCKING_PIPE
&& b
== FD_IS_NONBLOCKING_PIPE
) ||
375 (a
== FD_IS_NONBLOCKING_PIPE
&& b
== FD_IS_BLOCKING_PIPE
))
377 /* splice() only works if one of the fds is a pipe. If neither is,
378 * let's skip this step right-away. As mentioned above, if one of the
379 * two fds refers to a blocking pipe and the other to a non-blocking
380 * pipe, we can't use splice() either, hence don't try either. This
381 * hence means we can only use splice() if either only one of the two
382 * fds is a pipe, or if both are pipes with the same nonblocking flag
387 nonblock_pipe
= a
== FD_IS_NONBLOCKING_PIPE
|| b
== FD_IS_NONBLOCKING_PIPE
;
392 n
= splice(fdf
, NULL
, fdt
, NULL
, m
, nonblock_pipe
? SPLICE_F_NONBLOCK
: 0);
394 if (!IN_SET(errno
, EINVAL
, ENOSYS
))
398 /* use fallback below */
399 } else if (n
== 0) { /* likely EOF */
401 if (copied_something
)
404 try_splice
= false; /* same logic as above for copy_file_range() + sendfile() */
410 /* As a fallback just copy bits by hand */
412 uint8_t buf
[MIN(m
, COPY_BUFFER_SIZE
)], *p
= buf
;
415 n
= read(fdf
, buf
, sizeof buf
);
418 if (n
== 0) /* EOF */
425 k
= write(fdt
, p
, z
);
439 if (ret_remains_size
)
440 *ret_remains_size
= z
;
453 r
= progress(n
, userdata
);
458 if (max_bytes
!= UINT64_MAX
) {
459 assert(max_bytes
>= (uint64_t) n
);
463 /* sendfile accepts at most SSIZE_MAX-offset bytes to copy, so reduce our maximum by the
464 * amount we already copied, but don't go below our copy buffer size, unless we are close the
465 * limit of bytes we are allowed to copy. */
466 m
= MAX(MIN(COPY_BUFFER_SIZE
, max_bytes
), m
- n
);
468 copied_something
= true;
471 if (copy_flags
& COPY_TRUNCATE
) {
472 off_t off
= lseek(fdt
, 0, SEEK_CUR
);
476 if (ftruncate(fdt
, off
) < 0)
480 return max_bytes
<= 0; /* return 0 if we hit EOF earlier than the size limit */
483 static int fd_copy_symlink(
486 const struct stat
*st
,
491 CopyFlags copy_flags
) {
493 _cleanup_free_
char *target
= NULL
;
500 r
= readlinkat_malloc(df
, from
, &target
);
504 if (copy_flags
& COPY_MAC_CREATE
) {
505 r
= mac_selinux_create_file_prepare_at(dt
, to
, S_IFLNK
);
509 r
= RET_NERRNO(symlinkat(target
, dt
, to
));
510 if (copy_flags
& COPY_MAC_CREATE
)
511 mac_selinux_create_file_clear();
513 if (FLAGS_SET(copy_flags
, COPY_GRACEFUL_WARN
) && (ERRNO_IS_PRIVILEGE(r
) || ERRNO_IS_NOT_SUPPORTED(r
))) {
514 log_notice_errno(r
, "Failed to copy symlink '%s', ignoring: %m", from
);
522 uid_is_valid(override_uid
) ? override_uid
: st
->st_uid
,
523 gid_is_valid(override_gid
) ? override_gid
: st
->st_gid
,
524 AT_SYMLINK_NOFOLLOW
) < 0)
527 (void) copy_xattr(df
, from
, dt
, to
, copy_flags
);
528 (void) utimensat(dt
, to
, (struct timespec
[]) { st
->st_atim
, st
->st_mtim
}, AT_SYMLINK_NOFOLLOW
);
532 /* Encapsulates the database we store potential hardlink targets in */
533 typedef struct HardlinkContext
{
534 int dir_fd
; /* An fd to the directory we use as lookup table. Never AT_FDCWD. Lazily created, when
535 * we add the first entry. */
537 /* These two fields are used to create the hardlink repository directory above — via
538 * mkdirat(parent_fd, subdir) — and are kept so that we can automatically remove the directory again
539 * when we are done. */
540 int parent_fd
; /* Possibly AT_FDCWD */
544 static int hardlink_context_setup(
548 CopyFlags copy_flags
) {
550 _cleanup_close_
int dt_copy
= -EBADF
;
554 assert(c
->dir_fd
< 0 && c
->dir_fd
!= AT_FDCWD
);
555 assert(c
->parent_fd
< 0);
558 /* If hardlink recreation is requested we have to maintain a database of inodes that are potential
559 * hardlink sources. Given that generally disk sizes have to be assumed to be larger than what fits
560 * into physical RAM we cannot maintain that database in dynamic memory alone. Here we opt to
561 * maintain it on disk, to simplify things: inside the destination directory we'll maintain a
562 * temporary directory consisting of hardlinks of every inode we copied that might be subject of
563 * hardlinks. We can then use that as hardlink source later on. Yes, this means additional disk IO
564 * but thankfully Linux is optimized for this kind of thing. If this ever becomes a performance
565 * bottleneck we can certainly place an in-memory hash table in front of this, but for the beginning,
566 * let's keep things simple, and just use the disk as lookup table for inodes.
568 * Note that this should have zero performance impact as long as .n_link of all files copied remains
569 * <= 0, because in that case we will not actually allocate the hardlink inode lookup table directory
570 * on disk (we do so lazily, when the first candidate with .n_link > 1 is seen). This means, in the
571 * common case where hardlinks are not used at all or only for few files the fact that we store the
572 * table on disk shouldn't matter perfomance-wise. */
574 if (!FLAGS_SET(copy_flags
, COPY_HARDLINKS
))
582 dt_copy
= fcntl(dt
, F_DUPFD_CLOEXEC
, 3);
587 r
= tempfn_random_child(to
, "hardlink", &c
->subdir
);
591 c
->parent_fd
= TAKE_FD(dt_copy
);
593 /* We don't actually create the directory we keep the table in here, that's done on-demand when the
594 * first entry is added, using hardlink_context_realize() below. */
598 static int hardlink_context_realize(HardlinkContext
*c
) {
602 if (c
->dir_fd
>= 0) /* Already realized */
605 if (c
->parent_fd
< 0 && c
->parent_fd
!= AT_FDCWD
) /* Not configured */
610 c
->dir_fd
= open_mkdir_at(c
->parent_fd
, c
->subdir
, O_EXCL
|O_CLOEXEC
, 0700);
617 static void hardlink_context_destroy(HardlinkContext
*c
) {
622 /* Automatically remove the hardlink lookup table directory again after we are done. This is used via
623 * _cleanup_() so that we really delete this, even on failure. */
625 if (c
->dir_fd
>= 0) {
626 r
= rm_rf_children(TAKE_FD(c
->dir_fd
), REMOVE_PHYSICAL
, NULL
); /* consumes dir_fd in all cases, even on failure */
628 log_debug_errno(r
, "Failed to remove hardlink store (%s) contents, ignoring: %m", c
->subdir
);
630 assert(c
->parent_fd
>= 0 || c
->parent_fd
== AT_FDCWD
);
633 if (unlinkat(c
->parent_fd
, c
->subdir
, AT_REMOVEDIR
) < 0)
634 log_debug_errno(errno
, "Failed to remove hardlink store (%s) directory, ignoring: %m", c
->subdir
);
637 assert_cc(AT_FDCWD
< 0);
638 c
->parent_fd
= safe_close(c
->parent_fd
);
640 c
->subdir
= mfree(c
->subdir
);
643 static int try_hardlink(
645 const struct stat
*st
,
649 char dev_ino
[DECIMAL_STR_MAX(dev_t
)*2 + DECIMAL_STR_MAX(uint64_t) + 4];
652 assert(dt
>= 0 || dt
== AT_FDCWD
);
655 if (!c
) /* No temporary hardlink directory, don't bother */
658 if (st
->st_nlink
<= 1) /* Source not hardlinked, don't bother */
661 if (c
->dir_fd
< 0) /* not yet realized, hence empty */
664 xsprintf(dev_ino
, "%u:%u:%" PRIu64
, major(st
->st_dev
), minor(st
->st_dev
), (uint64_t) st
->st_ino
);
665 if (linkat(c
->dir_fd
, dev_ino
, dt
, to
, 0) < 0) {
666 if (errno
!= ENOENT
) /* doesn't exist in store yet */
667 log_debug_errno(errno
, "Failed to hardlink %s to %s, ignoring: %m", dev_ino
, to
);
674 static int memorize_hardlink(
676 const struct stat
*st
,
680 char dev_ino
[DECIMAL_STR_MAX(dev_t
)*2 + DECIMAL_STR_MAX(uint64_t) + 4];
684 assert(dt
>= 0 || dt
== AT_FDCWD
);
687 if (!c
) /* No temporary hardlink directory, don't bother */
690 if (st
->st_nlink
<= 1) /* Source not hardlinked, don't bother */
693 r
= hardlink_context_realize(c
); /* Create the hardlink store lazily */
697 xsprintf(dev_ino
, "%u:%u:%" PRIu64
, major(st
->st_dev
), minor(st
->st_dev
), (uint64_t) st
->st_ino
);
698 if (linkat(dt
, to
, c
->dir_fd
, dev_ino
, 0) < 0) {
699 log_debug_errno(errno
, "Failed to hardlink %s to %s, ignoring: %m", to
, dev_ino
);
706 static int fd_copy_tree_generic(
709 const struct stat
*st
,
712 dev_t original_device
,
716 CopyFlags copy_flags
,
718 HardlinkContext
*hardlink_context
,
719 const char *display_path
,
720 copy_progress_path_t progress_path
,
721 copy_progress_bytes_t progress_bytes
,
724 static int fd_copy_regular(
727 const struct stat
*st
,
732 CopyFlags copy_flags
,
733 HardlinkContext
*hardlink_context
,
734 copy_progress_bytes_t progress
,
737 _cleanup_close_
int fdf
= -EBADF
, fdt
= -EBADF
;
744 r
= try_hardlink(hardlink_context
, st
, dt
, to
);
747 if (r
> 0) /* worked! */
750 fdf
= openat(df
, from
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
754 if (copy_flags
& COPY_MAC_CREATE
) {
755 r
= mac_selinux_create_file_prepare_at(dt
, to
, S_IFREG
);
759 fdt
= openat(dt
, to
, O_WRONLY
|O_CREAT
|O_EXCL
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
, st
->st_mode
& 07777);
760 if (copy_flags
& COPY_MAC_CREATE
)
761 mac_selinux_create_file_clear();
765 r
= copy_bytes_full(fdf
, fdt
, UINT64_MAX
, copy_flags
, NULL
, NULL
, progress
, userdata
);
770 uid_is_valid(override_uid
) ? override_uid
: st
->st_uid
,
771 gid_is_valid(override_gid
) ? override_gid
: st
->st_gid
) < 0)
774 if (fchmod(fdt
, st
->st_mode
& 07777) < 0)
777 (void) futimens(fdt
, (struct timespec
[]) { st
->st_atim
, st
->st_mtim
});
778 (void) copy_xattr(fdf
, NULL
, fdt
, NULL
, copy_flags
);
780 if (copy_flags
& COPY_FSYNC
) {
781 if (fsync(fdt
) < 0) {
787 q
= close_nointr(TAKE_FD(fdt
)); /* even if this fails, the fd is now invalidated */
793 (void) memorize_hardlink(hardlink_context
, st
, dt
, to
);
797 (void) unlinkat(dt
, to
, 0);
801 static int fd_copy_fifo(
804 const struct stat
*st
,
809 CopyFlags copy_flags
,
810 HardlinkContext
*hardlink_context
) {
817 r
= try_hardlink(hardlink_context
, st
, dt
, to
);
820 if (r
> 0) /* worked! */
823 if (copy_flags
& COPY_MAC_CREATE
) {
824 r
= mac_selinux_create_file_prepare_at(dt
, to
, S_IFIFO
);
828 r
= RET_NERRNO(mkfifoat(dt
, to
, st
->st_mode
& 07777));
829 if (copy_flags
& COPY_MAC_CREATE
)
830 mac_selinux_create_file_clear();
832 if (FLAGS_SET(copy_flags
, COPY_GRACEFUL_WARN
) && (ERRNO_IS_PRIVILEGE(r
) || ERRNO_IS_NOT_SUPPORTED(r
))) {
833 log_notice_errno(r
, "Failed to copy fifo '%s', ignoring: %m", from
);
841 uid_is_valid(override_uid
) ? override_uid
: st
->st_uid
,
842 gid_is_valid(override_gid
) ? override_gid
: st
->st_gid
,
843 AT_SYMLINK_NOFOLLOW
) < 0)
846 if (fchmodat(dt
, to
, st
->st_mode
& 07777, 0) < 0)
849 (void) utimensat(dt
, to
, (struct timespec
[]) { st
->st_atim
, st
->st_mtim
}, AT_SYMLINK_NOFOLLOW
);
851 (void) memorize_hardlink(hardlink_context
, st
, dt
, to
);
855 static int fd_copy_node(
858 const struct stat
*st
,
863 CopyFlags copy_flags
,
864 HardlinkContext
*hardlink_context
) {
871 r
= try_hardlink(hardlink_context
, st
, dt
, to
);
874 if (r
> 0) /* worked! */
877 if (copy_flags
& COPY_MAC_CREATE
) {
878 r
= mac_selinux_create_file_prepare_at(dt
, to
, st
->st_mode
& S_IFMT
);
882 r
= RET_NERRNO(mknodat(dt
, to
, st
->st_mode
, st
->st_rdev
));
883 if (copy_flags
& COPY_MAC_CREATE
)
884 mac_selinux_create_file_clear();
886 if (FLAGS_SET(copy_flags
, COPY_GRACEFUL_WARN
) && (ERRNO_IS_PRIVILEGE(r
) || ERRNO_IS_NOT_SUPPORTED(r
))) {
887 log_notice_errno(r
, "Failed to copy node '%s', ignoring: %m", from
);
895 uid_is_valid(override_uid
) ? override_uid
: st
->st_uid
,
896 gid_is_valid(override_gid
) ? override_gid
: st
->st_gid
,
897 AT_SYMLINK_NOFOLLOW
) < 0)
900 if (fchmodat(dt
, to
, st
->st_mode
& 07777, 0) < 0)
903 (void) utimensat(dt
, to
, (struct timespec
[]) { st
->st_atim
, st
->st_mtim
}, AT_SYMLINK_NOFOLLOW
);
905 (void) memorize_hardlink(hardlink_context
, st
, dt
, to
);
909 static int fd_copy_directory(
912 const struct stat
*st
,
915 dev_t original_device
,
919 CopyFlags copy_flags
,
921 HardlinkContext
*hardlink_context
,
922 const char *display_path
,
923 copy_progress_path_t progress_path
,
924 copy_progress_bytes_t progress_bytes
,
927 _cleanup_(hardlink_context_destroy
) HardlinkContext our_hardlink_context
= {
932 _cleanup_close_
int fdf
= -EBADF
, fdt
= -EBADF
;
933 _cleanup_closedir_
DIR *d
= NULL
;
934 bool exists
, created
;
941 return -ENAMETOOLONG
;
944 fdf
= openat(df
, from
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
946 fdf
= fcntl(df
, F_DUPFD_CLOEXEC
, 3);
950 if (!hardlink_context
) {
951 /* If recreating hardlinks is requested let's set up a context for that now. */
952 r
= hardlink_context_setup(&our_hardlink_context
, dt
, to
, copy_flags
);
955 if (r
> 0) /* It's enabled and allocated, let's now use the same context for all recursive
956 * invocations from here down */
957 hardlink_context
= &our_hardlink_context
;
960 d
= take_fdopendir(&fdf
);
965 if (copy_flags
& COPY_MERGE_EMPTY
) {
966 r
= dir_is_empty_at(dt
, to
, /* ignore_hidden_or_backup= */ false);
967 if (r
< 0 && r
!= -ENOENT
)
976 if (copy_flags
& COPY_MAC_CREATE
)
977 r
= mkdirat_label(dt
, to
, st
->st_mode
& 07777);
979 r
= mkdirat(dt
, to
, st
->st_mode
& 07777);
982 else if (errno
== EEXIST
&& (copy_flags
& COPY_MERGE
))
988 fdt
= openat(dt
, to
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
994 if (PTR_TO_INT(hashmap_get(denylist
, st
)) == DENY_CONTENTS
) {
995 log_debug("%s is in the denylist, not recursing", from
);
999 FOREACH_DIRENT_ALL(de
, d
, return -errno
) {
1000 const char *child_display_path
= NULL
;
1001 _cleanup_free_
char *dp
= NULL
;
1005 if (dot_or_dot_dot(de
->d_name
))
1008 r
= look_for_signals(copy_flags
);
1012 if (fstatat(dirfd(d
), de
->d_name
, &buf
, AT_SYMLINK_NOFOLLOW
) < 0) {
1017 if (progress_path
) {
1019 child_display_path
= dp
= path_join(display_path
, de
->d_name
);
1021 child_display_path
= de
->d_name
;
1023 r
= progress_path(child_display_path
, &buf
, userdata
);
1028 if (PTR_TO_INT(hashmap_get(denylist
, &buf
)) == DENY_INODE
) {
1029 log_debug("%s/%s is in the denylist, ignoring", from
, de
->d_name
);
1033 if (S_ISDIR(buf
.st_mode
)) {
1035 * Don't descend into directories on other file systems, if this is requested. We do a simple
1036 * .st_dev check here, which basically comes for free. Note that we do this check only on
1037 * directories, not other kind of file system objects, for two reason:
1039 * • The kernel's overlayfs pseudo file system that overlays multiple real file systems
1040 * propagates the .st_dev field of the file system a file originates from all the way up
1041 * through the stack to stat(). It doesn't do that for directories however. This means that
1042 * comparing .st_dev on non-directories suggests that they all are mount points. To avoid
1043 * confusion we hence avoid relying on this check for regular files.
1045 * • The main reason we do this check at all is to protect ourselves from bind mount cycles,
1046 * where we really want to avoid descending down in all eternity. However the .st_dev check
1047 * is usually not sufficient for this protection anyway, as bind mount cycles from the same
1048 * file system onto itself can't be detected that way. (Note we also do a recursion depth
1049 * check, which is probably the better protection in this regard, which is why
1050 * COPY_SAME_MOUNT is optional).
1053 if (FLAGS_SET(copy_flags
, COPY_SAME_MOUNT
)) {
1054 if (buf
.st_dev
!= original_device
)
1057 r
= fd_is_mount_point(dirfd(d
), de
->d_name
, 0);
1065 q
= fd_copy_tree_generic(dirfd(d
), de
->d_name
, &buf
, fdt
, de
->d_name
, original_device
,
1066 depth_left
-1, override_uid
, override_gid
, copy_flags
, denylist
,
1067 hardlink_context
, child_display_path
, progress_path
, progress_bytes
,
1070 if (q
== -EINTR
) /* Propagate SIGINT/SIGTERM up instantly */
1072 if (q
== -EEXIST
&& (copy_flags
& COPY_MERGE
))
1081 uid_is_valid(override_uid
) ? override_uid
: st
->st_uid
,
1082 gid_is_valid(override_gid
) ? override_gid
: st
->st_gid
) < 0)
1085 if (fchmod(fdt
, st
->st_mode
& 07777) < 0)
1088 (void) copy_xattr(dirfd(d
), NULL
, fdt
, NULL
, copy_flags
);
1089 (void) futimens(fdt
, (struct timespec
[]) { st
->st_atim
, st
->st_mtim
});
1092 if (copy_flags
& COPY_FSYNC_FULL
) {
1100 static int fd_copy_leaf(
1103 const struct stat
*st
,
1108 CopyFlags copy_flags
,
1109 HardlinkContext
*hardlink_context
,
1110 const char *display_path
,
1111 copy_progress_bytes_t progress_bytes
,
1115 if (S_ISREG(st
->st_mode
))
1116 r
= fd_copy_regular(df
, from
, st
, dt
, to
, override_uid
, override_gid
, copy_flags
, hardlink_context
, progress_bytes
, userdata
);
1117 else if (S_ISLNK(st
->st_mode
))
1118 r
= fd_copy_symlink(df
, from
, st
, dt
, to
, override_uid
, override_gid
, copy_flags
);
1119 else if (S_ISFIFO(st
->st_mode
))
1120 r
= fd_copy_fifo(df
, from
, st
, dt
, to
, override_uid
, override_gid
, copy_flags
, hardlink_context
);
1121 else if (S_ISBLK(st
->st_mode
) || S_ISCHR(st
->st_mode
) || S_ISSOCK(st
->st_mode
))
1122 r
= fd_copy_node(df
, from
, st
, dt
, to
, override_uid
, override_gid
, copy_flags
, hardlink_context
);
1129 static int fd_copy_tree_generic(
1132 const struct stat
*st
,
1135 dev_t original_device
,
1136 unsigned depth_left
,
1139 CopyFlags copy_flags
,
1141 HardlinkContext
*hardlink_context
,
1142 const char *display_path
,
1143 copy_progress_path_t progress_path
,
1144 copy_progress_bytes_t progress_bytes
,
1148 if (S_ISDIR(st
->st_mode
))
1149 return fd_copy_directory(df
, from
, st
, dt
, to
, original_device
, depth_left
-1, override_uid
,
1150 override_gid
, copy_flags
, denylist
, hardlink_context
, display_path
,
1151 progress_path
, progress_bytes
, userdata
);
1153 DenyType t
= PTR_TO_INT(hashmap_get(denylist
, st
));
1154 if (t
== DENY_INODE
) {
1155 log_debug("%s is in the denylist, ignoring", from
);
1157 } else if (t
== DENY_CONTENTS
)
1158 log_debug("%s is configured to have its contents excluded, but is not a directory", from
);
1160 r
= fd_copy_leaf(df
, from
, st
, dt
, to
, override_uid
, override_gid
, copy_flags
, hardlink_context
, display_path
, progress_bytes
, userdata
);
1161 /* 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. */
1162 if (r
== -EEXIST
&& (copy_flags
& COPY_REPLACE
)) {
1163 /* This codepath is us trying to address an error to copy, if the unlink fails, lets just return the original error. */
1164 if (unlinkat(dt
, to
, 0) < 0)
1167 r
= fd_copy_leaf(df
, from
, st
, dt
, to
, override_uid
, override_gid
, copy_flags
, hardlink_context
, display_path
, progress_bytes
, userdata
);
1173 int copy_tree_at_full(
1180 CopyFlags copy_flags
,
1182 copy_progress_path_t progress_path
,
1183 copy_progress_bytes_t progress_bytes
,
1192 if (fstatat(fdf
, from
, &st
, AT_SYMLINK_NOFOLLOW
) < 0)
1195 r
= fd_copy_tree_generic(fdf
, from
, &st
, fdt
, to
, st
.st_dev
, COPY_DEPTH_MAX
, override_uid
,
1196 override_gid
, copy_flags
, denylist
, NULL
, NULL
, progress_path
,
1197 progress_bytes
, userdata
);
1201 if (S_ISDIR(st
.st_mode
) && (copy_flags
& COPY_SYNCFS
)) {
1202 /* If the top-level inode is a directory run syncfs() now. */
1203 r
= syncfs_path(fdt
, to
);
1206 } else if ((copy_flags
& (COPY_FSYNC_FULL
|COPY_SYNCFS
)) != 0) {
1207 /* fsync() the parent dir of what we just copied if COPY_FSYNC_FULL is set. Also do this in
1208 * case COPY_SYNCFS is set but the top-level inode wasn't actually a directory. We do this so that
1209 * COPY_SYNCFS provides reasonable synchronization semantics on any kind of inode: when the
1210 * copy operation is done the whole inode — regardless of its type — and all its children
1211 * will be synchronized to disk. */
1212 r
= fsync_parent_at(fdt
, to
);
1220 static int sync_dir_by_flags(int dir_fd
, const char *path
, CopyFlags copy_flags
) {
1221 assert(dir_fd
>= 0 || dir_fd
== AT_FDCWD
);
1224 if (copy_flags
& COPY_SYNCFS
)
1225 return syncfs_path(dir_fd
, path
);
1226 if (copy_flags
& COPY_FSYNC_FULL
)
1227 return fsync_parent_at(dir_fd
, path
);
1232 int copy_directory_at_full(
1237 CopyFlags copy_flags
,
1238 copy_progress_path_t progress_path
,
1239 copy_progress_bytes_t progress_bytes
,
1245 assert(dir_fdf
>= 0 || dir_fdf
== AT_FDCWD
);
1246 assert(dir_fdt
>= 0 || dir_fdt
== AT_FDCWD
);
1249 if (fstatat(dir_fdf
, strempty(from
), &st
, AT_SYMLINK_NOFOLLOW
|(isempty(from
) ? AT_EMPTY_PATH
: 0)) < 0)
1252 r
= stat_verify_directory(&st
);
1256 r
= fd_copy_directory(
1262 UID_INVALID
, GID_INVALID
,
1271 r
= sync_dir_by_flags(dir_fdt
, to
, copy_flags
);
1278 int copy_file_fd_at_full(
1282 CopyFlags copy_flags
,
1283 copy_progress_bytes_t progress_bytes
,
1286 _cleanup_close_
int fdf
= -EBADF
;
1290 assert(dir_fdf
>= 0 || dir_fdf
== AT_FDCWD
);
1294 fdf
= openat(dir_fdf
, from
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
1298 r
= fd_verify_regular(fdf
);
1302 if (fstat(fdt
, &st
) < 0)
1305 r
= copy_bytes_full(fdf
, fdt
, UINT64_MAX
, copy_flags
, NULL
, NULL
, progress_bytes
, userdata
);
1309 /* Make sure to copy file attributes only over if target is a regular
1310 * file (so that copying a file to /dev/null won't alter the access
1311 * mode/ownership of that device node...) */
1312 if (S_ISREG(st
.st_mode
)) {
1313 (void) copy_times(fdf
, fdt
, copy_flags
);
1314 (void) copy_xattr(fdf
, NULL
, fdt
, NULL
, copy_flags
);
1317 if (copy_flags
& COPY_FSYNC_FULL
) {
1318 r
= fsync_full(fdt
);
1321 } else if (copy_flags
& COPY_FSYNC
) {
1329 int copy_file_at_full(
1336 unsigned chattr_flags
,
1337 unsigned chattr_mask
,
1338 CopyFlags copy_flags
,
1339 copy_progress_bytes_t progress_bytes
,
1342 _cleanup_close_
int fdf
= -EBADF
, fdt
= -EBADF
;
1346 assert(dir_fdf
>= 0 || dir_fdf
== AT_FDCWD
);
1347 assert(dir_fdt
>= 0 || dir_fdt
== AT_FDCWD
);
1351 fdf
= openat(dir_fdf
, from
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
1355 if (fstat(fdf
, &st
) < 0)
1358 r
= stat_verify_regular(&st
);
1363 if (copy_flags
& COPY_MAC_CREATE
) {
1364 r
= mac_selinux_create_file_prepare_at(dir_fdt
, to
, S_IFREG
);
1368 fdt
= openat(dir_fdt
, to
, flags
|O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
,
1369 mode
!= MODE_INVALID
? mode
: st
.st_mode
);
1370 if (copy_flags
& COPY_MAC_CREATE
)
1371 mac_selinux_create_file_clear();
1376 if (!FLAGS_SET(flags
, O_EXCL
)) { /* if O_EXCL was used we created the thing as regular file, no need to check again */
1377 r
= fd_verify_regular(fdt
);
1382 if (chattr_mask
!= 0)
1383 (void) chattr_fd(fdt
, chattr_flags
, chattr_mask
& CHATTR_EARLY_FL
, NULL
);
1385 r
= copy_bytes_full(fdf
, fdt
, UINT64_MAX
, copy_flags
, NULL
, NULL
, progress_bytes
, userdata
);
1389 (void) copy_times(fdf
, fdt
, copy_flags
);
1390 (void) copy_xattr(fdf
, NULL
, fdt
, NULL
, copy_flags
);
1392 if (chattr_mask
!= 0)
1393 (void) chattr_fd(fdt
, chattr_flags
, chattr_mask
& ~CHATTR_EARLY_FL
, NULL
);
1395 if (copy_flags
& (COPY_FSYNC
|COPY_FSYNC_FULL
)) {
1396 if (fsync(fdt
) < 0) {
1402 r
= close_nointr(TAKE_FD(fdt
)); /* even if this fails, the fd is now invalidated */
1406 if (copy_flags
& COPY_FSYNC_FULL
) {
1407 r
= fsync_parent_at(dir_fdt
, to
);
1415 /* Only unlink if we definitely are the ones who created the file */
1416 if (FLAGS_SET(flags
, O_EXCL
))
1417 (void) unlinkat(dir_fdt
, to
, 0);
1422 int copy_file_atomic_at_full(
1428 unsigned chattr_flags
,
1429 unsigned chattr_mask
,
1430 CopyFlags copy_flags
,
1431 copy_progress_bytes_t progress_bytes
,
1434 _cleanup_(unlink_and_freep
) char *t
= NULL
;
1435 _cleanup_close_
int fdt
= -EBADF
;
1441 if (copy_flags
& COPY_MAC_CREATE
) {
1442 r
= mac_selinux_create_file_prepare_at(dir_fdt
, to
, S_IFREG
);
1446 fdt
= open_tmpfile_linkable_at(dir_fdt
, to
, O_WRONLY
|O_CLOEXEC
, &t
);
1447 if (copy_flags
& COPY_MAC_CREATE
)
1448 mac_selinux_create_file_clear();
1452 if (chattr_mask
!= 0)
1453 (void) chattr_fd(fdt
, chattr_flags
, chattr_mask
& CHATTR_EARLY_FL
, NULL
);
1455 r
= copy_file_fd_at_full(dir_fdf
, from
, fdt
, copy_flags
, progress_bytes
, userdata
);
1459 if (fchmod(fdt
, mode
) < 0)
1462 if ((copy_flags
& (COPY_FSYNC
|COPY_FSYNC_FULL
))) {
1468 r
= link_tmpfile_at(fdt
, dir_fdt
, t
, to
, copy_flags
& COPY_REPLACE
);
1474 if (chattr_mask
!= 0)
1475 (void) chattr_fd(fdt
, chattr_flags
, chattr_mask
& ~CHATTR_EARLY_FL
, NULL
);
1477 r
= close_nointr(TAKE_FD(fdt
)); /* even if this fails, the fd is now invalidated */
1481 if (copy_flags
& COPY_FSYNC_FULL
) {
1482 /* Sync the parent directory */
1483 r
= fsync_parent_at(dir_fdt
, to
);
1491 (void) unlinkat(dir_fdt
, to
, 0);
1495 int copy_times(int fdf
, int fdt
, CopyFlags flags
) {
1501 if (fstat(fdf
, &st
) < 0)
1504 if (futimens(fdt
, (struct timespec
[2]) { st
.st_atim
, st
.st_mtim
}) < 0)
1507 if (FLAGS_SET(flags
, COPY_CRTIME
)) {
1510 if (fd_getcrtime(fdf
, &crtime
) >= 0)
1511 (void) fd_setcrtime(fdt
, crtime
);
1517 int copy_access(int fdf
, int fdt
) {
1523 /* Copies just the access mode (and not the ownership) from fdf to fdt */
1525 if (fstat(fdf
, &st
) < 0)
1528 return RET_NERRNO(fchmod(fdt
, st
.st_mode
& 07777));
1531 int copy_rights_with_fallback(int fdf
, int fdt
, const char *patht
) {
1537 /* Copies both access mode and ownership from fdf to fdt */
1539 if (fstat(fdf
, &st
) < 0)
1542 return fchmod_and_chown_with_fallback(fdt
, patht
, st
.st_mode
& 07777, st
.st_uid
, st
.st_gid
);
1545 int copy_xattr(int df
, const char *from
, int dt
, const char *to
, CopyFlags copy_flags
) {
1546 _cleanup_free_
char *names
= NULL
;
1549 r
= listxattr_at_malloc(df
, from
, 0, &names
);
1553 NULSTR_FOREACH(p
, names
) {
1554 _cleanup_free_
char *value
= NULL
;
1556 if (!FLAGS_SET(copy_flags
, COPY_ALL_XATTRS
) && !startswith(p
, "user."))
1559 r
= getxattr_at_malloc(df
, from
, p
, 0, &value
);
1561 continue; /* gone by now */
1565 if (xsetxattr(dt
, to
, p
, value
, r
, 0) < 0)
1572 int reflink(int infd
, int outfd
) {
1578 /* Make sure we invoke the ioctl on a regular file, so that no device driver accidentally gets it. */
1580 r
= fd_verify_regular(outfd
);
1584 /* FICLONE was introduced in Linux 4.5 but it uses the same number as BTRFS_IOC_CLONE introduced earlier */
1586 assert_cc(FICLONE
== BTRFS_IOC_CLONE
);
1588 return RET_NERRNO(ioctl(outfd
, FICLONE
, infd
));
1591 assert_cc(sizeof(struct file_clone_range
) == sizeof(struct btrfs_ioctl_clone_range_args
));
1593 int reflink_range(int infd
, uint64_t in_offset
, int outfd
, uint64_t out_offset
, uint64_t sz
) {
1594 struct file_clone_range args
= {
1596 .src_offset
= in_offset
,
1598 .dest_offset
= out_offset
,
1605 /* Inside the kernel, FICLONE is identical to FICLONERANGE with offsets and size set to zero, let's
1606 * simplify things and use the simple ioctl in that case. Also, do the same if the size is
1607 * UINT64_MAX, which is how we usually encode "everything". */
1608 if (in_offset
== 0 && out_offset
== 0 && IN_SET(sz
, 0, UINT64_MAX
))
1609 return reflink(infd
, outfd
);
1611 r
= fd_verify_regular(outfd
);
1615 assert_cc(FICLONERANGE
== BTRFS_IOC_CLONE_RANGE
);
1617 return RET_NERRNO(ioctl(outfd
, FICLONERANGE
, &args
));