1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 Copyright 2014 Lennart Poettering
13 #include <sys/sendfile.h>
14 //#include <sys/stat.h>
15 #include <sys/xattr.h>
19 //#include "alloc-util.h"
20 //#include "btrfs-util.h"
21 //#include "chattr-util.h"
23 //#include "dirent-util.h"
24 //#include "fd-util.h"
26 //#include "fs-util.h"
30 //#include "mount-util.h"
31 //#include "string-util.h"
33 #include "time-util.h"
34 //#include "umask-util.h"
35 #include "user-util.h"
36 //#include "xattr-util.h"
38 #define COPY_BUFFER_SIZE (16U*1024U)
40 /* A safety net for descending recursively into file system trees to copy. On Linux PATH_MAX is 4096, which means the
41 * deepest valid path one can build is around 2048, which we hence use as a safety net here, to not spin endlessly in
42 * case of bind mount cycles and suchlike. */
43 #define COPY_DEPTH_MAX 2048U
45 static ssize_t try_copy_file_range(
46 int fd_in, loff_t *off_in,
47 int fd_out, loff_t *off_out,
57 r = copy_file_range(fd_in, off_in, fd_out, off_out, len, flags);
59 have = r >= 0 || errno != ENOSYS;
69 FD_IS_NONBLOCKING_PIPE,
72 static int fd_is_nonblock_pipe(int fd) {
76 /* Checks whether the specified file descriptor refers to a pipe, and if so if O_NONBLOCK is set. */
78 if (fstat(fd, &st) < 0)
81 if (!S_ISFIFO(st.st_mode))
84 flags = fcntl(fd, F_GETFL);
88 return FLAGS_SET(flags, O_NONBLOCK) ? FD_IS_NONBLOCKING_PIPE : FD_IS_BLOCKING_PIPE;
96 size_t *ret_remains_size) {
98 bool try_cfr = true, try_sendfile = true, try_splice = true;
99 int r, nonblock_pipe = -1;
100 size_t m = SSIZE_MAX; /* that is the maximum that sendfile and c_f_r accept */
105 /* Tries to copy bytes from the file descriptor 'fdf' to 'fdt' in the smartest possible way. Copies a maximum
106 * of 'max_bytes', which may be specified as UINT64_MAX, in which no maximum is applied. Returns negative on
107 * error, zero if EOF is hit before the bytes limit is hit and positive otherwise. If the copy fails for some
108 * reason but we read but didn't yet write some data an ret_remains/ret_remains_size is not NULL, then it will
109 * be initialized with an allocated buffer containing this "remaining" data. Note that these two parameters are
110 * initialized with a valid buffer only on failure and only if there's actually data already read. Otherwise
111 * these parameters if non-NULL are set to NULL. */
115 if (ret_remains_size)
116 *ret_remains_size = 0;
118 #if 0 /// UNNEEDED by elogind
119 /* Try btrfs reflinks first. This only works on regular, seekable files, hence let's check the file offsets of
120 * source and destination first. */
121 if ((copy_flags & COPY_REFLINK)) {
124 foffset = lseek(fdf, 0, SEEK_CUR);
128 toffset = lseek(fdt, 0, SEEK_CUR);
131 if (foffset == 0 && toffset == 0 && max_bytes == UINT64_MAX)
132 r = btrfs_reflink(fdf, fdt); /* full file reflink */
134 r = btrfs_clone_range(fdf, foffset, fdt, toffset, max_bytes == UINT64_MAX ? 0 : max_bytes); /* partial reflink */
138 /* This worked, yay! Now — to be fully correct — let's adjust the file pointers */
139 if (max_bytes == UINT64_MAX) {
141 /* We cloned to the end of the source file, let's position the read
142 * pointer there, and query it at the same time. */
143 t = lseek(fdf, 0, SEEK_END);
149 /* Let's adjust the destination file write pointer by the same number
151 t = lseek(fdt, toffset + (t - foffset), SEEK_SET);
155 return 0; /* we copied the whole thing, hence hit EOF, return 0 */
157 t = lseek(fdf, foffset + max_bytes, SEEK_SET);
161 t = lseek(fdt, toffset + max_bytes, SEEK_SET);
165 return 1; /* we copied only some number of bytes, which worked, but this means we didn't hit EOF, return 1 */
169 log_debug_errno(r, "Reflinking didn't work, falling back to non-reflink copying: %m");
179 return 1; /* return > 0 if we hit the max_bytes limit */
181 if (max_bytes != UINT64_MAX && m > max_bytes)
184 /* First try copy_file_range(), unless we already tried */
186 n = try_copy_file_range(fdf, NULL, fdt, NULL, m, 0u);
188 if (!IN_SET(n, -EINVAL, -ENOSYS, -EXDEV, -EBADF))
192 /* use fallback below */
193 } else if (n == 0) /* EOF */
200 /* First try sendfile(), unless we already tried */
202 n = sendfile(fdt, fdf, NULL, m);
204 if (!IN_SET(errno, EINVAL, ENOSYS))
207 try_sendfile = false;
208 /* use fallback below */
209 } else if (n == 0) /* EOF */
216 /* Then try splice, unless we already tried. */
219 /* splice()'s asynchronous I/O support is a bit weird. When it encounters a pipe file
220 * descriptor, then it will ignore its O_NONBLOCK flag and instead only honour the
221 * SPLICE_F_NONBLOCK flag specified in its flag parameter. Let's hide this behaviour here, and
222 * check if either of the specified fds are a pipe, and if so, let's pass the flag
223 * automatically, depending on O_NONBLOCK being set.
225 * Here's a twist though: when we use it to move data between two pipes of which one has
226 * O_NONBLOCK set and the other has not, then we have no individual control over O_NONBLOCK
227 * behaviour. Hence in that case we can't use splice() and still guarantee systematic
228 * O_NONBLOCK behaviour, hence don't. */
230 if (nonblock_pipe < 0) {
233 /* Check if either of these fds is a pipe, and if so non-blocking or not */
234 a = fd_is_nonblock_pipe(fdf);
238 b = fd_is_nonblock_pipe(fdt);
242 if ((a == FD_IS_NO_PIPE && b == FD_IS_NO_PIPE) ||
243 (a == FD_IS_BLOCKING_PIPE && b == FD_IS_NONBLOCKING_PIPE) ||
244 (a == FD_IS_NONBLOCKING_PIPE && b == FD_IS_BLOCKING_PIPE))
246 /* splice() only works if one of the fds is a pipe. If neither is, let's skip
247 * this step right-away. As mentioned above, if one of the two fds refers to a
248 * blocking pipe and the other to a non-blocking pipe, we can't use splice()
249 * either, hence don't try either. This hence means we can only use splice() if
250 * either only one of the two fds is a pipe, or if both are pipes with the same
251 * nonblocking flag setting. */
255 nonblock_pipe = a == FD_IS_NONBLOCKING_PIPE || b == FD_IS_NONBLOCKING_PIPE;
260 n = splice(fdf, NULL, fdt, NULL, m, nonblock_pipe ? SPLICE_F_NONBLOCK : 0);
262 if (!IN_SET(errno, EINVAL, ENOSYS))
266 /* use fallback below */
267 } else if (n == 0) /* EOF */
274 /* As a fallback just copy bits by hand */
276 uint8_t buf[MIN(m, COPY_BUFFER_SIZE)], *p = buf;
279 n = read(fdf, buf, sizeof buf);
282 if (n == 0) /* EOF */
289 k = write(fdt, p, z);
303 if (ret_remains_size)
304 *ret_remains_size = z;
316 if (max_bytes != (uint64_t) -1) {
317 assert(max_bytes >= (uint64_t) n);
320 /* sendfile accepts at most SSIZE_MAX-offset bytes to copy,
321 * so reduce our maximum by the amount we already copied,
322 * but don't go below our copy buffer size, unless we are
323 * close the limit of bytes we are allowed to copy. */
324 m = MAX(MIN(COPY_BUFFER_SIZE, max_bytes), m - n);
327 return 0; /* return 0 if we hit EOF earlier than the size limit */
330 #if 0 /// UNNEEDED by elogind
331 static int fd_copy_symlink(
334 const struct stat *st,
339 CopyFlags copy_flags) {
341 _cleanup_free_ char *target = NULL;
348 r = readlinkat_malloc(df, from, &target);
352 if (symlinkat(target, dt, to) < 0)
356 uid_is_valid(override_uid) ? override_uid : st->st_uid,
357 gid_is_valid(override_gid) ? override_gid : st->st_gid,
358 AT_SYMLINK_NOFOLLOW) < 0)
364 static int fd_copy_regular(
367 const struct stat *st,
372 CopyFlags copy_flags) {
374 _cleanup_close_ int fdf = -1, fdt = -1;
375 struct timespec ts[2];
382 fdf = openat(df, from, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
386 fdt = openat(dt, to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, st->st_mode & 07777);
390 r = copy_bytes(fdf, fdt, (uint64_t) -1, copy_flags);
392 (void) unlinkat(dt, to, 0);
397 uid_is_valid(override_uid) ? override_uid : st->st_uid,
398 gid_is_valid(override_gid) ? override_gid : st->st_gid) < 0)
401 if (fchmod(fdt, st->st_mode & 07777) < 0)
406 (void) futimens(fdt, ts);
407 (void) copy_xattr(fdf, fdt);
414 (void) unlinkat(dt, to, 0);
420 static int fd_copy_fifo(
423 const struct stat *st,
428 CopyFlags copy_flags) {
435 r = mkfifoat(dt, to, st->st_mode & 07777);
440 uid_is_valid(override_uid) ? override_uid : st->st_uid,
441 gid_is_valid(override_gid) ? override_gid : st->st_gid,
442 AT_SYMLINK_NOFOLLOW) < 0)
445 if (fchmodat(dt, to, st->st_mode & 07777, 0) < 0)
451 static int fd_copy_node(
454 const struct stat *st,
459 CopyFlags copy_flags) {
466 r = mknodat(dt, to, st->st_mode, st->st_rdev);
471 uid_is_valid(override_uid) ? override_uid : st->st_uid,
472 gid_is_valid(override_gid) ? override_gid : st->st_gid,
473 AT_SYMLINK_NOFOLLOW) < 0)
476 if (fchmodat(dt, to, st->st_mode & 07777, 0) < 0)
482 static int fd_copy_directory(
485 const struct stat *st,
488 dev_t original_device,
492 CopyFlags copy_flags) {
494 _cleanup_close_ int fdf = -1, fdt = -1;
495 _cleanup_closedir_ DIR *d = NULL;
504 return -ENAMETOOLONG;
507 fdf = openat(df, from, O_RDONLY|O_DIRECTORY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
509 fdf = fcntl(df, F_DUPFD_CLOEXEC, 3);
518 r = mkdirat(dt, to, st->st_mode & 07777);
521 else if (errno == EEXIST && (copy_flags & COPY_MERGE))
526 fdt = openat(dt, to, O_RDONLY|O_DIRECTORY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
532 FOREACH_DIRENT_ALL(de, d, return -errno) {
536 if (dot_or_dot_dot(de->d_name))
539 if (fstatat(dirfd(d), de->d_name, &buf, AT_SYMLINK_NOFOLLOW) < 0) {
544 if (S_ISDIR(buf.st_mode)) {
546 * Don't descend into directories on other file systems, if this is requested. We do a simple
547 * .st_dev check here, which basically comes for free. Note that we do this check only on
548 * directories, not other kind of file system objects, for two reason:
550 * • The kernel's overlayfs pseudo file system that overlays multiple real file systems
551 * propagates the .st_dev field of the file system a file originates from all the way up
552 * through the stack to stat(). It doesn't do that for directories however. This means that
553 * comparing .st_dev on non-directories suggests that they all are mount points. To avoid
554 * confusion we hence avoid relying on this check for regular files.
556 * • The main reason we do this check at all is to protect ourselves from bind mount cycles,
557 * where we really want to avoid descending down in all eternity. However the .st_dev check
558 * is usually not sufficient for this protection anyway, as bind mount cycles from the same
559 * file system onto itself can't be detected that way. (Note we also do a recursion depth
560 * check, which is probably the better protection in this regard, which is why
561 * COPY_SAME_MOUNT is optional).
564 if (FLAGS_SET(copy_flags, COPY_SAME_MOUNT)) {
565 if (buf.st_dev != original_device)
568 r = fd_is_mount_point(dirfd(d), de->d_name, 0);
575 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);
576 } else if (S_ISREG(buf.st_mode))
577 q = fd_copy_regular(dirfd(d), de->d_name, &buf, fdt, de->d_name, override_uid, override_gid, copy_flags);
578 else if (S_ISLNK(buf.st_mode))
579 q = fd_copy_symlink(dirfd(d), de->d_name, &buf, fdt, de->d_name, override_uid, override_gid, copy_flags);
580 else if (S_ISFIFO(buf.st_mode))
581 q = fd_copy_fifo(dirfd(d), de->d_name, &buf, fdt, de->d_name, override_uid, override_gid, copy_flags);
582 else if (S_ISBLK(buf.st_mode) || S_ISCHR(buf.st_mode) || S_ISSOCK(buf.st_mode))
583 q = fd_copy_node(dirfd(d), de->d_name, &buf, fdt, de->d_name, override_uid, override_gid, copy_flags);
587 if (q == -EEXIST && (copy_flags & COPY_MERGE))
595 struct timespec ut[2] = {
601 uid_is_valid(override_uid) ? override_uid : st->st_uid,
602 gid_is_valid(override_gid) ? override_gid : st->st_gid) < 0)
605 if (fchmod(fdt, st->st_mode & 07777) < 0)
608 (void) copy_xattr(dirfd(d), fdt);
609 (void) futimens(fdt, ut);
615 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) {
621 if (fstatat(fdf, from, &st, AT_SYMLINK_NOFOLLOW) < 0)
624 if (S_ISREG(st.st_mode))
625 return fd_copy_regular(fdf, from, &st, fdt, to, override_uid, override_gid, copy_flags);
626 else if (S_ISDIR(st.st_mode))
627 return fd_copy_directory(fdf, from, &st, fdt, to, st.st_dev, COPY_DEPTH_MAX, override_uid, override_gid, copy_flags);
628 else if (S_ISLNK(st.st_mode))
629 return fd_copy_symlink(fdf, from, &st, fdt, to, override_uid, override_gid, copy_flags);
630 else if (S_ISFIFO(st.st_mode))
631 return fd_copy_fifo(fdf, from, &st, fdt, to, override_uid, override_gid, copy_flags);
632 else if (S_ISBLK(st.st_mode) || S_ISCHR(st.st_mode) || S_ISSOCK(st.st_mode))
633 return fd_copy_node(fdf, from, &st, fdt, to, override_uid, override_gid, copy_flags);
638 int copy_tree(const char *from, const char *to, uid_t override_uid, gid_t override_gid, CopyFlags copy_flags) {
639 return copy_tree_at(AT_FDCWD, from, AT_FDCWD, to, override_uid, override_gid, copy_flags);
642 int copy_directory_fd(int dirfd, const char *to, CopyFlags copy_flags) {
648 if (fstat(dirfd, &st) < 0)
651 if (!S_ISDIR(st.st_mode))
654 return fd_copy_directory(dirfd, NULL, &st, AT_FDCWD, to, st.st_dev, COPY_DEPTH_MAX, UID_INVALID, GID_INVALID, copy_flags);
657 int copy_directory(const char *from, const char *to, CopyFlags copy_flags) {
663 if (lstat(from, &st) < 0)
666 if (!S_ISDIR(st.st_mode))
669 return fd_copy_directory(AT_FDCWD, from, &st, AT_FDCWD, to, st.st_dev, COPY_DEPTH_MAX, UID_INVALID, GID_INVALID, copy_flags);
672 int copy_file_fd(const char *from, int fdt, CopyFlags copy_flags) {
673 _cleanup_close_ int fdf = -1;
679 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
683 r = copy_bytes(fdf, fdt, (uint64_t) -1, copy_flags);
685 (void) copy_times(fdf, fdt);
686 (void) copy_xattr(fdf, fdt);
691 int copy_file(const char *from, const char *to, int flags, mode_t mode, unsigned chattr_flags, CopyFlags copy_flags) {
697 RUN_WITH_UMASK(0000) {
698 fdt = open(to, flags|O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode);
703 if (chattr_flags != 0)
704 (void) chattr_fd(fdt, chattr_flags, (unsigned) -1);
706 r = copy_file_fd(from, fdt, copy_flags);
713 if (close(fdt) < 0) {
721 int copy_file_atomic(const char *from, const char *to, mode_t mode, unsigned chattr_flags, CopyFlags copy_flags) {
722 _cleanup_free_ char *t = NULL;
728 r = tempfn_random(to, NULL, &t);
732 r = copy_file(from, t, O_NOFOLLOW|O_EXCL, mode, chattr_flags, copy_flags);
736 if (copy_flags & COPY_REPLACE) {
737 r = renameat(AT_FDCWD, t, AT_FDCWD, to);
741 r = rename_noreplace(AT_FDCWD, t, AT_FDCWD, to);
750 int copy_times(int fdf, int fdt) {
751 struct timespec ut[2];
758 if (fstat(fdf, &st) < 0)
764 if (futimens(fdt, ut) < 0)
767 if (fd_getcrtime(fdf, &crtime) >= 0)
768 (void) fd_setcrtime(fdt, crtime);
773 int copy_xattr(int fdf, int fdt) {
774 _cleanup_free_ char *bufa = NULL, *bufb = NULL;
775 size_t sza = 100, szb = 100;
785 n = flistxattr(fdf, bufa, sza);
803 assert(l < (size_t) n);
805 if (startswith(p, "user.")) {
814 m = fgetxattr(fdf, p, bufb, szb);
816 if (errno == ERANGE) {
825 if (fsetxattr(fdt, p, bufb, m, 0) < 0)