1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2014 Lennart Poettering
15 #include <sys/sendfile.h>
16 //#include <sys/stat.h>
17 #include <sys/xattr.h>
21 //#include "alloc-util.h"
22 //#include "btrfs-util.h"
23 //#include "chattr-util.h"
25 //#include "dirent-util.h"
26 //#include "fd-util.h"
28 //#include "fs-util.h"
32 //#include "mount-util.h"
33 //#include "string-util.h"
35 #include "time-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;
98 size_t *ret_remains_size) {
100 bool try_cfr = true, try_sendfile = true, try_splice = true;
101 int r, nonblock_pipe = -1;
102 size_t m = SSIZE_MAX; /* that is the maximum that sendfile and c_f_r accept */
107 /* Tries to copy bytes from the file descriptor 'fdf' to 'fdt' in the smartest possible way. Copies a maximum
108 * of 'max_bytes', which may be specified as UINT64_MAX, in which no maximum is applied. Returns negative on
109 * error, zero if EOF is hit before the bytes limit is hit and positive otherwise. If the copy fails for some
110 * reason but we read but didn't yet write some data an ret_remains/ret_remains_size is not NULL, then it will
111 * be initialized with an allocated buffer containing this "remaining" data. Note that these two parameters are
112 * initialized with a valid buffer only on failure and only if there's actually data already read. Otherwise
113 * these parameters if non-NULL are set to NULL. */
117 if (ret_remains_size)
118 *ret_remains_size = 0;
120 #if 0 /// UNNEEDED by elogind
121 /* Try btrfs reflinks first. This only works on regular, seekable files, hence let's check the file offsets of
122 * source and destination first. */
123 if ((copy_flags & COPY_REFLINK)) {
126 foffset = lseek(fdf, 0, SEEK_CUR);
130 toffset = lseek(fdt, 0, SEEK_CUR);
133 if (foffset == 0 && toffset == 0 && max_bytes == UINT64_MAX)
134 r = btrfs_reflink(fdf, fdt); /* full file reflink */
136 r = btrfs_clone_range(fdf, foffset, fdt, toffset, max_bytes == UINT64_MAX ? 0 : max_bytes); /* partial reflink */
140 /* This worked, yay! Now — to be fully correct — let's adjust the file pointers */
141 if (max_bytes == UINT64_MAX) {
143 /* We cloned to the end of the source file, let's position the read
144 * pointer there, and query it at the same time. */
145 t = lseek(fdf, 0, SEEK_END);
151 /* Let's adjust the destination file write pointer by the same number
153 t = lseek(fdt, toffset + (t - foffset), SEEK_SET);
157 return 0; /* we copied the whole thing, hence hit EOF, return 0 */
159 t = lseek(fdf, foffset + max_bytes, SEEK_SET);
163 t = lseek(fdt, toffset + max_bytes, SEEK_SET);
167 return 1; /* we copied only some number of bytes, which worked, but this means we didn't hit EOF, return 1 */
171 log_debug_errno(r, "Reflinking didn't work, falling back to non-reflink copying: %m");
181 return 1; /* return > 0 if we hit the max_bytes limit */
183 if (max_bytes != UINT64_MAX && m > max_bytes)
186 /* First try copy_file_range(), unless we already tried */
188 n = try_copy_file_range(fdf, NULL, fdt, NULL, m, 0u);
190 if (!IN_SET(n, -EINVAL, -ENOSYS, -EXDEV, -EBADF))
194 /* use fallback below */
195 } else if (n == 0) /* EOF */
202 /* First try sendfile(), unless we already tried */
204 n = sendfile(fdt, fdf, NULL, m);
206 if (!IN_SET(errno, EINVAL, ENOSYS))
209 try_sendfile = false;
210 /* use fallback below */
211 } else if (n == 0) /* EOF */
218 /* Then try splice, unless we already tried. */
221 /* splice()'s asynchronous I/O support is a bit weird. When it encounters a pipe file
222 * descriptor, then it will ignore its O_NONBLOCK flag and instead only honour the
223 * SPLICE_F_NONBLOCK flag specified in its flag parameter. Let's hide this behaviour here, and
224 * check if either of the specified fds are a pipe, and if so, let's pass the flag
225 * automatically, depending on O_NONBLOCK being set.
227 * Here's a twist though: when we use it to move data between two pipes of which one has
228 * O_NONBLOCK set and the other has not, then we have no individual control over O_NONBLOCK
229 * behaviour. Hence in that case we can't use splice() and still guarantee systematic
230 * O_NONBLOCK behaviour, hence don't. */
232 if (nonblock_pipe < 0) {
235 /* Check if either of these fds is a pipe, and if so non-blocking or not */
236 a = fd_is_nonblock_pipe(fdf);
240 b = fd_is_nonblock_pipe(fdt);
244 if ((a == FD_IS_NO_PIPE && b == FD_IS_NO_PIPE) ||
245 (a == FD_IS_BLOCKING_PIPE && b == FD_IS_NONBLOCKING_PIPE) ||
246 (a == FD_IS_NONBLOCKING_PIPE && b == FD_IS_BLOCKING_PIPE))
248 /* splice() only works if one of the fds is a pipe. If neither is, let's skip
249 * this step right-away. As mentioned above, if one of the two fds refers to a
250 * blocking pipe and the other to a non-blocking pipe, we can't use splice()
251 * either, hence don't try either. This hence means we can only use splice() if
252 * either only one of the two fds is a pipe, or if both are pipes with the same
253 * nonblocking flag setting. */
257 nonblock_pipe = a == FD_IS_NONBLOCKING_PIPE || b == FD_IS_NONBLOCKING_PIPE;
262 n = splice(fdf, NULL, fdt, NULL, m, nonblock_pipe ? SPLICE_F_NONBLOCK : 0);
264 if (!IN_SET(errno, EINVAL, ENOSYS))
268 /* use fallback below */
269 } else if (n == 0) /* EOF */
276 /* As a fallback just copy bits by hand */
278 uint8_t buf[MIN(m, COPY_BUFFER_SIZE)], *p = buf;
281 n = read(fdf, buf, sizeof buf);
284 if (n == 0) /* EOF */
291 k = write(fdt, p, z);
305 if (ret_remains_size)
306 *ret_remains_size = z;
318 if (max_bytes != (uint64_t) -1) {
319 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 #if 0 /// UNNEEDED by elogind
333 static int fd_copy_symlink(
336 const struct stat *st,
341 CopyFlags copy_flags) {
343 _cleanup_free_ char *target = NULL;
350 r = readlinkat_malloc(df, from, &target);
354 if (symlinkat(target, dt, to) < 0)
358 uid_is_valid(override_uid) ? override_uid : st->st_uid,
359 gid_is_valid(override_gid) ? override_gid : st->st_gid,
360 AT_SYMLINK_NOFOLLOW) < 0)
366 static int fd_copy_regular(
369 const struct stat *st,
374 CopyFlags copy_flags) {
376 _cleanup_close_ int fdf = -1, fdt = -1;
377 struct timespec ts[2];
384 fdf = openat(df, from, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
388 fdt = openat(dt, to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, st->st_mode & 07777);
392 r = copy_bytes(fdf, fdt, (uint64_t) -1, copy_flags);
394 (void) unlinkat(dt, to, 0);
399 uid_is_valid(override_uid) ? override_uid : st->st_uid,
400 gid_is_valid(override_gid) ? override_gid : st->st_gid) < 0)
403 if (fchmod(fdt, st->st_mode & 07777) < 0)
408 (void) futimens(fdt, ts);
409 (void) copy_xattr(fdf, fdt);
416 (void) unlinkat(dt, to, 0);
422 static int fd_copy_fifo(
425 const struct stat *st,
430 CopyFlags copy_flags) {
437 r = mkfifoat(dt, to, st->st_mode & 07777);
442 uid_is_valid(override_uid) ? override_uid : st->st_uid,
443 gid_is_valid(override_gid) ? override_gid : st->st_gid,
444 AT_SYMLINK_NOFOLLOW) < 0)
447 if (fchmodat(dt, to, st->st_mode & 07777, 0) < 0)
453 static int fd_copy_node(
456 const struct stat *st,
461 CopyFlags copy_flags) {
468 r = mknodat(dt, to, st->st_mode, st->st_rdev);
473 uid_is_valid(override_uid) ? override_uid : st->st_uid,
474 gid_is_valid(override_gid) ? override_gid : st->st_gid,
475 AT_SYMLINK_NOFOLLOW) < 0)
478 if (fchmodat(dt, to, st->st_mode & 07777, 0) < 0)
484 static int fd_copy_directory(
487 const struct stat *st,
490 dev_t original_device,
494 CopyFlags copy_flags) {
496 _cleanup_close_ int fdf = -1, fdt = -1;
497 _cleanup_closedir_ DIR *d = NULL;
506 return -ENAMETOOLONG;
509 fdf = openat(df, from, O_RDONLY|O_DIRECTORY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
511 fdf = fcntl(df, F_DUPFD_CLOEXEC, 3);
520 r = mkdirat(dt, to, st->st_mode & 07777);
523 else if (errno == EEXIST && (copy_flags & COPY_MERGE))
528 fdt = openat(dt, to, O_RDONLY|O_DIRECTORY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
534 FOREACH_DIRENT_ALL(de, d, return -errno) {
538 if (dot_or_dot_dot(de->d_name))
541 if (fstatat(dirfd(d), de->d_name, &buf, AT_SYMLINK_NOFOLLOW) < 0) {
546 if (S_ISDIR(buf.st_mode)) {
548 * Don't descend into directories on other file systems, if this is requested. We do a simple
549 * .st_dev check here, which basically comes for free. Note that we do this check only on
550 * directories, not other kind of file system objects, for two reason:
552 * • The kernel's overlayfs pseudo file system that overlays multiple real file systems
553 * propagates the .st_dev field of the file system a file originates from all the way up
554 * through the stack to stat(). It doesn't do that for directories however. This means that
555 * comparing .st_dev on non-directories suggests that they all are mount points. To avoid
556 * confusion we hence avoid relying on this check for regular files.
558 * • The main reason we do this check at all is to protect ourselves from bind mount cycles,
559 * where we really want to avoid descending down in all eternity. However the .st_dev check
560 * is usually not sufficient for this protection anyway, as bind mount cycles from the same
561 * file system onto itself can't be detected that way. (Note we also do a recursion depth
562 * check, which is probably the better protection in this regard, which is why
563 * COPY_SAME_MOUNT is optional).
566 if (FLAGS_SET(copy_flags, COPY_SAME_MOUNT)) {
567 if (buf.st_dev != original_device)
570 r = fd_is_mount_point(dirfd(d), de->d_name, 0);
577 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);
578 } else if (S_ISREG(buf.st_mode))
579 q = fd_copy_regular(dirfd(d), de->d_name, &buf, fdt, de->d_name, override_uid, override_gid, copy_flags);
580 else if (S_ISLNK(buf.st_mode))
581 q = fd_copy_symlink(dirfd(d), de->d_name, &buf, fdt, de->d_name, override_uid, override_gid, copy_flags);
582 else if (S_ISFIFO(buf.st_mode))
583 q = fd_copy_fifo(dirfd(d), de->d_name, &buf, fdt, de->d_name, override_uid, override_gid, copy_flags);
584 else if (S_ISBLK(buf.st_mode) || S_ISCHR(buf.st_mode) || S_ISSOCK(buf.st_mode))
585 q = fd_copy_node(dirfd(d), de->d_name, &buf, fdt, de->d_name, override_uid, override_gid, copy_flags);
589 if (q == -EEXIST && (copy_flags & COPY_MERGE))
597 struct timespec ut[2] = {
603 uid_is_valid(override_uid) ? override_uid : st->st_uid,
604 gid_is_valid(override_gid) ? override_gid : st->st_gid) < 0)
607 if (fchmod(fdt, st->st_mode & 07777) < 0)
610 (void) copy_xattr(dirfd(d), fdt);
611 (void) futimens(fdt, ut);
617 int copy_tree_at(int fdf, const char *from, int fdt, const char *to, uid_t override_uid, gid_t override_gid, CopyFlags copy_flags) {
623 if (fstatat(fdf, from, &st, AT_SYMLINK_NOFOLLOW) < 0)
626 if (S_ISREG(st.st_mode))
627 return fd_copy_regular(fdf, from, &st, fdt, to, override_uid, override_gid, copy_flags);
628 else if (S_ISDIR(st.st_mode))
629 return fd_copy_directory(fdf, from, &st, fdt, to, st.st_dev, COPY_DEPTH_MAX, override_uid, override_gid, copy_flags);
630 else if (S_ISLNK(st.st_mode))
631 return fd_copy_symlink(fdf, from, &st, fdt, to, override_uid, override_gid, copy_flags);
632 else if (S_ISFIFO(st.st_mode))
633 return fd_copy_fifo(fdf, from, &st, fdt, to, override_uid, override_gid, copy_flags);
634 else if (S_ISBLK(st.st_mode) || S_ISCHR(st.st_mode) || S_ISSOCK(st.st_mode))
635 return fd_copy_node(fdf, from, &st, fdt, to, override_uid, override_gid, copy_flags);
640 int copy_tree(const char *from, const char *to, uid_t override_uid, gid_t override_gid, CopyFlags copy_flags) {
641 return copy_tree_at(AT_FDCWD, from, AT_FDCWD, to, override_uid, override_gid, copy_flags);
644 int copy_directory_fd(int dirfd, const char *to, CopyFlags copy_flags) {
650 if (fstat(dirfd, &st) < 0)
653 if (!S_ISDIR(st.st_mode))
656 return fd_copy_directory(dirfd, NULL, &st, AT_FDCWD, to, st.st_dev, COPY_DEPTH_MAX, UID_INVALID, GID_INVALID, copy_flags);
659 int copy_directory(const char *from, const char *to, CopyFlags copy_flags) {
665 if (lstat(from, &st) < 0)
668 if (!S_ISDIR(st.st_mode))
671 return fd_copy_directory(AT_FDCWD, from, &st, AT_FDCWD, to, st.st_dev, COPY_DEPTH_MAX, UID_INVALID, GID_INVALID, copy_flags);
674 int copy_file_fd(const char *from, int fdt, CopyFlags copy_flags) {
675 _cleanup_close_ int fdf = -1;
681 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
685 r = copy_bytes(fdf, fdt, (uint64_t) -1, copy_flags);
687 (void) copy_times(fdf, fdt);
688 (void) copy_xattr(fdf, fdt);
693 int copy_file(const char *from, const char *to, int flags, mode_t mode, unsigned chattr_flags, CopyFlags copy_flags) {
699 RUN_WITH_UMASK(0000) {
700 fdt = open(to, flags|O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode);
705 if (chattr_flags != 0)
706 (void) chattr_fd(fdt, chattr_flags, (unsigned) -1);
708 r = copy_file_fd(from, fdt, copy_flags);
715 if (close(fdt) < 0) {
723 int copy_file_atomic(const char *from, const char *to, mode_t mode, unsigned chattr_flags, CopyFlags copy_flags) {
724 _cleanup_free_ char *t = NULL;
730 r = tempfn_random(to, NULL, &t);
734 r = copy_file(from, t, O_NOFOLLOW|O_EXCL, mode, chattr_flags, copy_flags);
738 if (copy_flags & COPY_REPLACE) {
739 r = renameat(AT_FDCWD, t, AT_FDCWD, to);
743 r = rename_noreplace(AT_FDCWD, t, AT_FDCWD, to);
752 int copy_times(int fdf, int fdt) {
753 struct timespec ut[2];
760 if (fstat(fdf, &st) < 0)
766 if (futimens(fdt, ut) < 0)
769 if (fd_getcrtime(fdf, &crtime) >= 0)
770 (void) fd_setcrtime(fdt, crtime);
775 int copy_xattr(int fdf, int fdt) {
776 _cleanup_free_ char *bufa = NULL, *bufb = NULL;
777 size_t sza = 100, szb = 100;
787 n = flistxattr(fdf, bufa, sza);
805 assert(l < (size_t) n);
807 if (startswith(p, "user.")) {
816 m = fgetxattr(fdf, p, bufb, szb);
818 if (errno == ERANGE) {
827 if (fsetxattr(fdt, p, bufb, m, 0) < 0)