1 /* SPDX-License-Identifier: LGPL-2.1+ */
10 #include <sys/sendfile.h>
12 #include <sys/xattr.h>
16 #include "alloc-util.h"
17 #include "btrfs-util.h"
18 #include "chattr-util.h"
20 #include "dirent-util.h"
27 #include "mountpoint-util.h"
28 #include "string-util.h"
30 #include "time-util.h"
31 #include "umask-util.h"
32 #include "user-util.h"
33 #include "xattr-util.h"
35 #define COPY_BUFFER_SIZE (16U*1024U)
37 /* A safety net for descending recursively into file system trees to copy. On Linux PATH_MAX is 4096, which means the
38 * deepest valid path one can build is around 2048, which we hence use as a safety net here, to not spin endlessly in
39 * case of bind mount cycles and suchlike. */
40 #define COPY_DEPTH_MAX 2048U
42 static ssize_t
try_copy_file_range(
43 int fd_in
, loff_t
*off_in
,
44 int fd_out
, loff_t
*off_out
,
54 r
= copy_file_range(fd_in
, off_in
, fd_out
, off_out
, len
, flags
);
56 have
= r
>= 0 || errno
!= ENOSYS
;
66 FD_IS_NONBLOCKING_PIPE
,
69 static int fd_is_nonblock_pipe(int fd
) {
73 /* Checks whether the specified file descriptor refers to a pipe, and if so if O_NONBLOCK is set. */
75 if (fstat(fd
, &st
) < 0)
78 if (!S_ISFIFO(st
.st_mode
))
81 flags
= fcntl(fd
, F_GETFL
);
85 return FLAGS_SET(flags
, O_NONBLOCK
) ? FD_IS_NONBLOCKING_PIPE
: FD_IS_BLOCKING_PIPE
;
93 size_t *ret_remains_size
,
94 copy_progress_bytes_t progress
,
97 bool try_cfr
= true, try_sendfile
= true, try_splice
= true;
98 int r
, nonblock_pipe
= -1;
99 size_t m
= SSIZE_MAX
; /* that is the maximum that sendfile and c_f_r accept */
104 /* Tries to copy bytes from the file descriptor 'fdf' to 'fdt' in the smartest possible way. Copies a maximum
105 * of 'max_bytes', which may be specified as UINT64_MAX, in which no maximum is applied. Returns negative on
106 * error, zero if EOF is hit before the bytes limit is hit and positive otherwise. If the copy fails for some
107 * reason but we read but didn't yet write some data an ret_remains/ret_remains_size is not NULL, then it will
108 * be initialized with an allocated buffer containing this "remaining" data. Note that these two parameters are
109 * initialized with a valid buffer only on failure and only if there's actually data already read. Otherwise
110 * these parameters if non-NULL are set to NULL. */
114 if (ret_remains_size
)
115 *ret_remains_size
= 0;
117 /* Try btrfs reflinks first. This only works on regular, seekable files, hence let's check the file offsets of
118 * source and destination first. */
119 if ((copy_flags
& COPY_REFLINK
)) {
122 foffset
= lseek(fdf
, 0, SEEK_CUR
);
126 toffset
= lseek(fdt
, 0, SEEK_CUR
);
129 if (foffset
== 0 && toffset
== 0 && max_bytes
== UINT64_MAX
)
130 r
= btrfs_reflink(fdf
, fdt
); /* full file reflink */
132 r
= btrfs_clone_range(fdf
, foffset
, fdt
, toffset
, max_bytes
== UINT64_MAX
? 0 : max_bytes
); /* partial reflink */
136 /* This worked, yay! Now — to be fully correct — let's adjust the file pointers */
137 if (max_bytes
== UINT64_MAX
) {
139 /* We cloned to the end of the source file, let's position the read
140 * pointer there, and query it at the same time. */
141 t
= lseek(fdf
, 0, SEEK_END
);
147 /* Let's adjust the destination file write pointer by the same number
149 t
= lseek(fdt
, toffset
+ (t
- foffset
), SEEK_SET
);
153 return 0; /* we copied the whole thing, hence hit EOF, return 0 */
155 t
= lseek(fdf
, foffset
+ max_bytes
, SEEK_SET
);
159 t
= lseek(fdt
, toffset
+ max_bytes
, SEEK_SET
);
163 return 1; /* we copied only some number of bytes, which worked, but this means we didn't hit EOF, return 1 */
174 return 1; /* return > 0 if we hit the max_bytes limit */
176 if (max_bytes
!= UINT64_MAX
&& m
> max_bytes
)
179 /* First try copy_file_range(), unless we already tried */
181 n
= try_copy_file_range(fdf
, NULL
, fdt
, NULL
, m
, 0u);
183 if (!IN_SET(n
, -EINVAL
, -ENOSYS
, -EXDEV
, -EBADF
))
187 /* use fallback below */
188 } else if (n
== 0) /* EOF */
195 /* First try sendfile(), unless we already tried */
197 n
= sendfile(fdt
, fdf
, NULL
, m
);
199 if (!IN_SET(errno
, EINVAL
, ENOSYS
))
202 try_sendfile
= false;
203 /* use fallback below */
204 } else if (n
== 0) /* EOF */
211 /* Then try splice, unless we already tried. */
214 /* splice()'s asynchronous I/O support is a bit weird. When it encounters a pipe file
215 * descriptor, then it will ignore its O_NONBLOCK flag and instead only honour the
216 * SPLICE_F_NONBLOCK flag specified in its flag parameter. Let's hide this behaviour here, and
217 * check if either of the specified fds are a pipe, and if so, let's pass the flag
218 * automatically, depending on O_NONBLOCK being set.
220 * Here's a twist though: when we use it to move data between two pipes of which one has
221 * O_NONBLOCK set and the other has not, then we have no individual control over O_NONBLOCK
222 * behaviour. Hence in that case we can't use splice() and still guarantee systematic
223 * O_NONBLOCK behaviour, hence don't. */
225 if (nonblock_pipe
< 0) {
228 /* Check if either of these fds is a pipe, and if so non-blocking or not */
229 a
= fd_is_nonblock_pipe(fdf
);
233 b
= fd_is_nonblock_pipe(fdt
);
237 if ((a
== FD_IS_NO_PIPE
&& b
== FD_IS_NO_PIPE
) ||
238 (a
== FD_IS_BLOCKING_PIPE
&& b
== FD_IS_NONBLOCKING_PIPE
) ||
239 (a
== FD_IS_NONBLOCKING_PIPE
&& b
== FD_IS_BLOCKING_PIPE
))
241 /* splice() only works if one of the fds is a pipe. If neither is, let's skip
242 * this step right-away. As mentioned above, if one of the two fds refers to a
243 * blocking pipe and the other to a non-blocking pipe, we can't use splice()
244 * either, hence don't try either. This hence means we can only use splice() if
245 * either only one of the two fds is a pipe, or if both are pipes with the same
246 * nonblocking flag setting. */
250 nonblock_pipe
= a
== FD_IS_NONBLOCKING_PIPE
|| b
== FD_IS_NONBLOCKING_PIPE
;
255 n
= splice(fdf
, NULL
, fdt
, NULL
, m
, nonblock_pipe
? SPLICE_F_NONBLOCK
: 0);
257 if (!IN_SET(errno
, EINVAL
, ENOSYS
))
261 /* use fallback below */
262 } else if (n
== 0) /* EOF */
269 /* As a fallback just copy bits by hand */
271 uint8_t buf
[MIN(m
, COPY_BUFFER_SIZE
)], *p
= buf
;
274 n
= read(fdf
, buf
, sizeof buf
);
277 if (n
== 0) /* EOF */
284 k
= write(fdt
, p
, z
);
298 if (ret_remains_size
)
299 *ret_remains_size
= z
;
312 r
= progress(n
, userdata
);
317 if (max_bytes
!= (uint64_t) -1) {
318 assert(max_bytes
>= (uint64_t) n
);
322 /* sendfile accepts at most SSIZE_MAX-offset bytes to copy,
323 * so reduce our maximum by the amount we already copied,
324 * but don't go below our copy buffer size, unless we are
325 * close the limit of bytes we are allowed to copy. */
326 m
= MAX(MIN(COPY_BUFFER_SIZE
, max_bytes
), m
- n
);
329 return 0; /* return 0 if we hit EOF earlier than the size limit */
332 static int fd_copy_symlink(
335 const struct stat
*st
,
340 CopyFlags copy_flags
) {
342 _cleanup_free_
char *target
= NULL
;
349 r
= readlinkat_malloc(df
, from
, &target
);
353 if (symlinkat(target
, dt
, to
) < 0)
357 uid_is_valid(override_uid
) ? override_uid
: st
->st_uid
,
358 gid_is_valid(override_gid
) ? override_gid
: st
->st_gid
,
359 AT_SYMLINK_NOFOLLOW
) < 0)
365 static int fd_copy_regular(
368 const struct stat
*st
,
373 CopyFlags copy_flags
,
374 copy_progress_bytes_t progress
,
377 _cleanup_close_
int fdf
= -1, fdt
= -1;
378 struct timespec ts
[2];
385 fdf
= openat(df
, from
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
389 fdt
= openat(dt
, to
, O_WRONLY
|O_CREAT
|O_EXCL
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
, st
->st_mode
& 07777);
393 r
= copy_bytes_full(fdf
, fdt
, (uint64_t) -1, copy_flags
, NULL
, NULL
, progress
, userdata
);
395 (void) unlinkat(dt
, to
, 0);
400 uid_is_valid(override_uid
) ? override_uid
: st
->st_uid
,
401 gid_is_valid(override_gid
) ? override_gid
: st
->st_gid
) < 0)
404 if (fchmod(fdt
, st
->st_mode
& 07777) < 0)
409 (void) futimens(fdt
, ts
);
410 (void) copy_xattr(fdf
, fdt
);
417 (void) unlinkat(dt
, to
, 0);
423 static int fd_copy_fifo(
426 const struct stat
*st
,
431 CopyFlags copy_flags
) {
438 r
= mkfifoat(dt
, to
, st
->st_mode
& 07777);
443 uid_is_valid(override_uid
) ? override_uid
: st
->st_uid
,
444 gid_is_valid(override_gid
) ? override_gid
: st
->st_gid
,
445 AT_SYMLINK_NOFOLLOW
) < 0)
448 if (fchmodat(dt
, to
, st
->st_mode
& 07777, 0) < 0)
454 static int fd_copy_node(
457 const struct stat
*st
,
462 CopyFlags copy_flags
) {
469 r
= mknodat(dt
, to
, st
->st_mode
, st
->st_rdev
);
474 uid_is_valid(override_uid
) ? override_uid
: st
->st_uid
,
475 gid_is_valid(override_gid
) ? override_gid
: st
->st_gid
,
476 AT_SYMLINK_NOFOLLOW
) < 0)
479 if (fchmodat(dt
, to
, st
->st_mode
& 07777, 0) < 0)
485 static int fd_copy_directory(
488 const struct stat
*st
,
491 dev_t original_device
,
495 CopyFlags copy_flags
,
496 const char *display_path
,
497 copy_progress_path_t progress_path
,
498 copy_progress_bytes_t progress_bytes
,
501 _cleanup_close_
int fdf
= -1, fdt
= -1;
502 _cleanup_closedir_
DIR *d
= NULL
;
511 return -ENAMETOOLONG
;
514 fdf
= openat(df
, from
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
516 fdf
= fcntl(df
, F_DUPFD_CLOEXEC
, 3);
525 r
= mkdirat(dt
, to
, st
->st_mode
& 07777);
528 else if (errno
== EEXIST
&& (copy_flags
& COPY_MERGE
))
533 fdt
= openat(dt
, to
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
);
539 FOREACH_DIRENT_ALL(de
, d
, return -errno
) {
540 const char *child_display_path
= NULL
;
541 _cleanup_free_
char *dp
= NULL
;
545 if (dot_or_dot_dot(de
->d_name
))
548 if (fstatat(dirfd(d
), de
->d_name
, &buf
, AT_SYMLINK_NOFOLLOW
) < 0) {
555 child_display_path
= dp
= strjoin(display_path
, "/", de
->d_name
);
557 child_display_path
= de
->d_name
;
559 r
= progress_path(child_display_path
, &buf
, userdata
);
564 if (S_ISDIR(buf
.st_mode
)) {
566 * Don't descend into directories on other file systems, if this is requested. We do a simple
567 * .st_dev check here, which basically comes for free. Note that we do this check only on
568 * directories, not other kind of file system objects, for two reason:
570 * • The kernel's overlayfs pseudo file system that overlays multiple real file systems
571 * propagates the .st_dev field of the file system a file originates from all the way up
572 * through the stack to stat(). It doesn't do that for directories however. This means that
573 * comparing .st_dev on non-directories suggests that they all are mount points. To avoid
574 * confusion we hence avoid relying on this check for regular files.
576 * • The main reason we do this check at all is to protect ourselves from bind mount cycles,
577 * where we really want to avoid descending down in all eternity. However the .st_dev check
578 * is usually not sufficient for this protection anyway, as bind mount cycles from the same
579 * file system onto itself can't be detected that way. (Note we also do a recursion depth
580 * check, which is probably the better protection in this regard, which is why
581 * COPY_SAME_MOUNT is optional).
584 if (FLAGS_SET(copy_flags
, COPY_SAME_MOUNT
)) {
585 if (buf
.st_dev
!= original_device
)
588 r
= fd_is_mount_point(dirfd(d
), de
->d_name
, 0);
595 q
= fd_copy_directory(dirfd(d
), de
->d_name
, &buf
, fdt
, de
->d_name
, original_device
, depth_left
-1, override_uid
, override_gid
, copy_flags
, child_display_path
, progress_path
, progress_bytes
, userdata
);
596 } else if (S_ISREG(buf
.st_mode
))
597 q
= fd_copy_regular(dirfd(d
), de
->d_name
, &buf
, fdt
, de
->d_name
, override_uid
, override_gid
, copy_flags
, progress_bytes
, userdata
);
598 else if (S_ISLNK(buf
.st_mode
))
599 q
= fd_copy_symlink(dirfd(d
), de
->d_name
, &buf
, fdt
, de
->d_name
, override_uid
, override_gid
, copy_flags
);
600 else if (S_ISFIFO(buf
.st_mode
))
601 q
= fd_copy_fifo(dirfd(d
), de
->d_name
, &buf
, fdt
, de
->d_name
, override_uid
, override_gid
, copy_flags
);
602 else if (S_ISBLK(buf
.st_mode
) || S_ISCHR(buf
.st_mode
) || S_ISSOCK(buf
.st_mode
))
603 q
= fd_copy_node(dirfd(d
), de
->d_name
, &buf
, fdt
, de
->d_name
, override_uid
, override_gid
, copy_flags
);
607 if (q
== -EEXIST
&& (copy_flags
& COPY_MERGE
))
615 struct timespec ut
[2] = {
621 uid_is_valid(override_uid
) ? override_uid
: st
->st_uid
,
622 gid_is_valid(override_gid
) ? override_gid
: st
->st_gid
) < 0)
625 if (fchmod(fdt
, st
->st_mode
& 07777) < 0)
628 (void) copy_xattr(dirfd(d
), fdt
);
629 (void) futimens(fdt
, ut
);
635 int copy_tree_at_full(
642 CopyFlags copy_flags
,
643 copy_progress_path_t progress_path
,
644 copy_progress_bytes_t progress_bytes
,
652 if (fstatat(fdf
, from
, &st
, AT_SYMLINK_NOFOLLOW
) < 0)
655 if (S_ISREG(st
.st_mode
))
656 return fd_copy_regular(fdf
, from
, &st
, fdt
, to
, override_uid
, override_gid
, copy_flags
, progress_bytes
, userdata
);
657 else if (S_ISDIR(st
.st_mode
))
658 return fd_copy_directory(fdf
, from
, &st
, fdt
, to
, st
.st_dev
, COPY_DEPTH_MAX
, override_uid
, override_gid
, copy_flags
, NULL
, progress_path
, progress_bytes
, userdata
);
659 else if (S_ISLNK(st
.st_mode
))
660 return fd_copy_symlink(fdf
, from
, &st
, fdt
, to
, override_uid
, override_gid
, copy_flags
);
661 else if (S_ISFIFO(st
.st_mode
))
662 return fd_copy_fifo(fdf
, from
, &st
, fdt
, to
, override_uid
, override_gid
, copy_flags
);
663 else if (S_ISBLK(st
.st_mode
) || S_ISCHR(st
.st_mode
) || S_ISSOCK(st
.st_mode
))
664 return fd_copy_node(fdf
, from
, &st
, fdt
, to
, override_uid
, override_gid
, copy_flags
);
669 int copy_directory_fd_full(
672 CopyFlags copy_flags
,
673 copy_progress_path_t progress_path
,
674 copy_progress_bytes_t progress_bytes
,
682 if (fstat(dirfd
, &st
) < 0)
685 if (!S_ISDIR(st
.st_mode
))
688 return fd_copy_directory(dirfd
, NULL
, &st
, AT_FDCWD
, to
, st
.st_dev
, COPY_DEPTH_MAX
, UID_INVALID
, GID_INVALID
, copy_flags
, NULL
, progress_path
, progress_bytes
, userdata
);
691 int copy_directory_full(
694 CopyFlags copy_flags
,
695 copy_progress_path_t progress_path
,
696 copy_progress_bytes_t progress_bytes
,
704 if (lstat(from
, &st
) < 0)
707 if (!S_ISDIR(st
.st_mode
))
710 return fd_copy_directory(AT_FDCWD
, from
, &st
, AT_FDCWD
, to
, st
.st_dev
, COPY_DEPTH_MAX
, UID_INVALID
, GID_INVALID
, copy_flags
, NULL
, progress_path
, progress_bytes
, userdata
);
713 int copy_file_fd_full(
716 CopyFlags copy_flags
,
717 copy_progress_bytes_t progress_bytes
,
720 _cleanup_close_
int fdf
= -1;
726 fdf
= open(from
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
730 r
= copy_bytes_full(fdf
, fdt
, (uint64_t) -1, copy_flags
, NULL
, NULL
, progress_bytes
, userdata
);
732 (void) copy_times(fdf
, fdt
);
733 (void) copy_xattr(fdf
, fdt
);
743 unsigned chattr_flags
,
744 CopyFlags copy_flags
,
745 copy_progress_bytes_t progress_bytes
,
753 RUN_WITH_UMASK(0000) {
754 fdt
= open(to
, flags
|O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
, mode
);
759 if (chattr_flags
!= 0)
760 (void) chattr_fd(fdt
, chattr_flags
, (unsigned) -1, NULL
);
762 r
= copy_file_fd_full(from
, fdt
, copy_flags
, progress_bytes
, userdata
);
769 if (close(fdt
) < 0) {
777 int copy_file_atomic_full(
781 unsigned chattr_flags
,
782 CopyFlags copy_flags
,
783 copy_progress_bytes_t progress_bytes
,
786 _cleanup_(unlink_and_freep
) char *t
= NULL
;
787 _cleanup_close_
int fdt
= -1;
793 /* We try to use O_TMPFILE here to create the file if we can. Note that that only works if COPY_REPLACE is not
794 * set though as we need to use linkat() for linking the O_TMPFILE file into the file system but that system
795 * call can't replace existing files. Hence, if COPY_REPLACE is set we create a temporary name in the file
796 * system right-away and unconditionally which we then can renameat() to the right name after we completed
799 if (copy_flags
& COPY_REPLACE
) {
800 r
= tempfn_random(to
, NULL
, &t
);
804 fdt
= open(t
, O_CREAT
|O_EXCL
|O_NOFOLLOW
|O_NOCTTY
|O_WRONLY
|O_CLOEXEC
, 0600);
810 fdt
= open_tmpfile_linkable(to
, O_WRONLY
|O_CLOEXEC
, &t
);
815 if (chattr_flags
!= 0)
816 (void) chattr_fd(fdt
, chattr_flags
, (unsigned) -1, NULL
);
818 r
= copy_file_fd_full(from
, fdt
, copy_flags
, progress_bytes
, userdata
);
822 if (fchmod(fdt
, mode
) < 0)
825 if (copy_flags
& COPY_REPLACE
) {
826 if (renameat(AT_FDCWD
, t
, AT_FDCWD
, to
) < 0)
829 r
= link_tmpfile(fdt
, t
, to
);
838 int copy_times(int fdf
, int fdt
) {
839 struct timespec ut
[2];
846 if (fstat(fdf
, &st
) < 0)
852 if (futimens(fdt
, ut
) < 0)
855 if (fd_getcrtime(fdf
, &crtime
) >= 0)
856 (void) fd_setcrtime(fdt
, crtime
);
861 int copy_xattr(int fdf
, int fdt
) {
862 _cleanup_free_
char *bufa
= NULL
, *bufb
= NULL
;
863 size_t sza
= 100, szb
= 100;
873 n
= flistxattr(fdf
, bufa
, sza
);
891 assert(l
< (size_t) n
);
893 if (startswith(p
, "user.")) {
902 m
= fgetxattr(fdf
, p
, bufb
, szb
);
904 if (errno
== ERANGE
) {
913 if (fsetxattr(fdt
, p
, bufb
, m
, 0) < 0)