]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/copy.c
copy: extend copy_bytes() a bit
[thirdparty/systemd.git] / src / basic / copy.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3 This file is part of systemd.
4
5 Copyright 2014 Lennart Poettering
6 ***/
7
8 #include <dirent.h>
9 #include <errno.h>
10 #include <fcntl.h>
11 #include <stddef.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <sys/sendfile.h>
16 #include <sys/stat.h>
17 #include <sys/xattr.h>
18 #include <time.h>
19 #include <unistd.h>
20
21 #include "alloc-util.h"
22 #include "btrfs-util.h"
23 #include "chattr-util.h"
24 #include "copy.h"
25 #include "dirent-util.h"
26 #include "fd-util.h"
27 #include "fileio.h"
28 #include "fs-util.h"
29 #include "io-util.h"
30 #include "macro.h"
31 #include "missing.h"
32 #include "string-util.h"
33 #include "strv.h"
34 #include "time-util.h"
35 #include "umask-util.h"
36 #include "user-util.h"
37 #include "xattr-util.h"
38
39 #define COPY_BUFFER_SIZE (16*1024u)
40
41 static ssize_t try_copy_file_range(int fd_in, loff_t *off_in,
42 int fd_out, loff_t *off_out,
43 size_t len,
44 unsigned int flags) {
45 static int have = -1;
46 ssize_t r;
47
48 if (have == false)
49 return -ENOSYS;
50
51 r = copy_file_range(fd_in, off_in, fd_out, off_out, len, flags);
52 if (_unlikely_(have < 0))
53 have = r >= 0 || errno != ENOSYS;
54 if (r >= 0)
55 return r;
56 else
57 return -errno;
58 }
59
60 int copy_bytes_full(
61 int fdf, int fdt,
62 uint64_t max_bytes,
63 CopyFlags copy_flags,
64 void **ret_remains,
65 size_t *ret_remains_size) {
66
67 bool try_cfr = true, try_sendfile = true, try_splice = true;
68 int r;
69 size_t m = SSIZE_MAX; /* that is the maximum that sendfile and c_f_r accept */
70
71 assert(fdf >= 0);
72 assert(fdt >= 0);
73
74 /* Tries to copy bytes from the file descriptor 'fdf' to 'fdt' in the smartest possible way. Copies a maximum
75 * of 'max_bytes', which may be specified as UINT64_MAX, in which no maximum is applied. Returns negative on
76 * error, zero if EOF is hit before the bytes limit is hit and positive otherwise. If the copy fails for some
77 * reason but we read but didn't yet write some data an ret_remains/ret_remains_size is not NULL, then it will
78 * be initialized with an allocated buffer containing this "remaining" data. Note that these two parameters are
79 * initialized with a valid buffer only on failure and only if there's actually data already read. Otherwise
80 * these parameters if non-NULL are set to NULL. */
81
82 if (ret_remains)
83 *ret_remains = NULL;
84 if (ret_remains_size)
85 *ret_remains_size = 0;
86
87 /* Try btrfs reflinks first. This only works on regular, seekable files, hence let's check the file offsets of
88 * source and destination first. */
89 if ((copy_flags & COPY_REFLINK)) {
90 off_t foffset;
91
92 foffset = lseek(fdf, 0, SEEK_CUR);
93 if (foffset >= 0) {
94 off_t toffset;
95
96 toffset = lseek(fdt, 0, SEEK_CUR);
97 if (toffset >= 0) {
98
99 if (foffset == 0 && toffset == 0 && max_bytes == UINT64_MAX)
100 r = btrfs_reflink(fdf, fdt); /* full file reflink */
101 else
102 r = btrfs_clone_range(fdf, foffset, fdt, toffset, max_bytes == UINT64_MAX ? 0 : max_bytes); /* partial reflink */
103 if (r >= 0) {
104 off_t t;
105
106 /* This worked, yay! Now — to be fully correct — let's adjust the file pointers */
107 if (max_bytes == UINT64_MAX) {
108
109 /* We cloned to the end of the source file, let's position the read
110 * pointer there, and query it at the same time. */
111 t = lseek(fdf, 0, SEEK_END);
112 if (t < 0)
113 return -errno;
114 if (t < foffset)
115 return -ESPIPE;
116
117 /* Let's adjust the destination file write pointer by the same number
118 * of bytes. */
119 t = lseek(fdt, toffset + (t - foffset), SEEK_SET);
120 if (t < 0)
121 return -errno;
122
123 return 0; /* we copied the whole thing, hence hit EOF, return 0 */
124 } else {
125 t = lseek(fdf, foffset + max_bytes, SEEK_SET);
126 if (t < 0)
127 return -errno;
128
129 t = lseek(fdt, toffset + max_bytes, SEEK_SET);
130 if (t < 0)
131 return -errno;
132
133 return 1; /* we copied only some number of bytes, which worked, but this means we didn't hit EOF, return 1 */
134 }
135 }
136
137 log_debug_errno(r, "Reflinking didn't work, falling back to non-reflink copying: %m");
138 }
139 }
140 }
141
142 for (;;) {
143 ssize_t n;
144
145 if (max_bytes != (uint64_t) -1) {
146 if (max_bytes <= 0)
147 return 1; /* return > 0 if we hit the max_bytes limit */
148
149 if (m > max_bytes)
150 m = max_bytes;
151 }
152
153 /* First try copy_file_range(), unless we already tried */
154 if (try_cfr) {
155 n = try_copy_file_range(fdf, NULL, fdt, NULL, m, 0u);
156 if (n < 0) {
157 if (!IN_SET(n, -EINVAL, -ENOSYS, -EXDEV, -EBADF))
158 return n;
159
160 try_cfr = false;
161 /* use fallback below */
162 } else if (n == 0) /* EOF */
163 break;
164 else
165 /* Success! */
166 goto next;
167 }
168
169 /* First try sendfile(), unless we already tried */
170 if (try_sendfile) {
171 n = sendfile(fdt, fdf, NULL, m);
172 if (n < 0) {
173 if (!IN_SET(errno, EINVAL, ENOSYS))
174 return -errno;
175
176 try_sendfile = false;
177 /* use fallback below */
178 } else if (n == 0) /* EOF */
179 break;
180 else
181 /* Success! */
182 goto next;
183 }
184
185 /* Then try splice, unless we already tried */
186 if (try_splice) {
187 n = splice(fdf, NULL, fdt, NULL, m, 0);
188 if (n < 0) {
189 if (!IN_SET(errno, EINVAL, ENOSYS))
190 return -errno;
191
192 try_splice = false;
193 /* use fallback below */
194 } else if (n == 0) /* EOF */
195 break;
196 else
197 /* Success! */
198 goto next;
199 }
200
201 /* As a fallback just copy bits by hand */
202 {
203 uint8_t buf[MIN(m, COPY_BUFFER_SIZE)], *p = buf;
204 ssize_t z;
205
206 n = read(fdf, buf, sizeof buf);
207 if (n < 0)
208 return -errno;
209 if (n == 0) /* EOF */
210 break;
211
212 z = (size_t) n;
213 do {
214 ssize_t k;
215
216 k = write(fdt, p, z);
217 if (k < 0) {
218 r = -errno;
219
220 if (ret_remains) {
221 void *copy;
222
223 copy = memdup(p, z);
224 if (!copy)
225 return -ENOMEM;
226
227 *ret_remains = copy;
228 }
229
230 if (ret_remains_size)
231 *ret_remains_size = z;
232
233 return r;
234 }
235
236 assert(k <= z);
237 z -= k;
238 p += k;
239 } while (z > 0);
240 }
241
242 next:
243 if (max_bytes != (uint64_t) -1) {
244 assert(max_bytes >= (uint64_t) n);
245 max_bytes -= n;
246 }
247 /* sendfile accepts at most SSIZE_MAX-offset bytes to copy,
248 * so reduce our maximum by the amount we already copied,
249 * but don't go below our copy buffer size, unless we are
250 * close the limit of bytes we are allowed to copy. */
251 m = MAX(MIN(COPY_BUFFER_SIZE, max_bytes), m - n);
252 }
253
254 return 0; /* return 0 if we hit EOF earlier than the size limit */
255 }
256
257 static int fd_copy_symlink(
258 int df,
259 const char *from,
260 const struct stat *st,
261 int dt,
262 const char *to,
263 uid_t override_uid,
264 gid_t override_gid,
265 CopyFlags copy_flags) {
266
267 _cleanup_free_ char *target = NULL;
268 int r;
269
270 assert(from);
271 assert(st);
272 assert(to);
273
274 r = readlinkat_malloc(df, from, &target);
275 if (r < 0)
276 return r;
277
278 if (symlinkat(target, dt, to) < 0)
279 return -errno;
280
281 if (fchownat(dt, to,
282 uid_is_valid(override_uid) ? override_uid : st->st_uid,
283 gid_is_valid(override_gid) ? override_gid : st->st_gid,
284 AT_SYMLINK_NOFOLLOW) < 0)
285 return -errno;
286
287 return 0;
288 }
289
290 static int fd_copy_regular(
291 int df,
292 const char *from,
293 const struct stat *st,
294 int dt,
295 const char *to,
296 uid_t override_uid,
297 gid_t override_gid,
298 CopyFlags copy_flags) {
299
300 _cleanup_close_ int fdf = -1, fdt = -1;
301 struct timespec ts[2];
302 int r, q;
303
304 assert(from);
305 assert(st);
306 assert(to);
307
308 fdf = openat(df, from, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
309 if (fdf < 0)
310 return -errno;
311
312 fdt = openat(dt, to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, st->st_mode & 07777);
313 if (fdt < 0)
314 return -errno;
315
316 r = copy_bytes(fdf, fdt, (uint64_t) -1, copy_flags);
317 if (r < 0) {
318 (void) unlinkat(dt, to, 0);
319 return r;
320 }
321
322 if (fchown(fdt,
323 uid_is_valid(override_uid) ? override_uid : st->st_uid,
324 gid_is_valid(override_gid) ? override_gid : st->st_gid) < 0)
325 r = -errno;
326
327 if (fchmod(fdt, st->st_mode & 07777) < 0)
328 r = -errno;
329
330 ts[0] = st->st_atim;
331 ts[1] = st->st_mtim;
332 (void) futimens(fdt, ts);
333 (void) copy_xattr(fdf, fdt);
334
335 q = close(fdt);
336 fdt = -1;
337
338 if (q < 0) {
339 r = -errno;
340 (void) unlinkat(dt, to, 0);
341 }
342
343 return r;
344 }
345
346 static int fd_copy_fifo(
347 int df,
348 const char *from,
349 const struct stat *st,
350 int dt,
351 const char *to,
352 uid_t override_uid,
353 gid_t override_gid,
354 CopyFlags copy_flags) {
355 int r;
356
357 assert(from);
358 assert(st);
359 assert(to);
360
361 r = mkfifoat(dt, to, st->st_mode & 07777);
362 if (r < 0)
363 return -errno;
364
365 if (fchownat(dt, to,
366 uid_is_valid(override_uid) ? override_uid : st->st_uid,
367 gid_is_valid(override_gid) ? override_gid : st->st_gid,
368 AT_SYMLINK_NOFOLLOW) < 0)
369 r = -errno;
370
371 if (fchmodat(dt, to, st->st_mode & 07777, 0) < 0)
372 r = -errno;
373
374 return r;
375 }
376
377 static int fd_copy_node(
378 int df,
379 const char *from,
380 const struct stat *st,
381 int dt,
382 const char *to,
383 uid_t override_uid,
384 gid_t override_gid,
385 CopyFlags copy_flags) {
386 int r;
387
388 assert(from);
389 assert(st);
390 assert(to);
391
392 r = mknodat(dt, to, st->st_mode, st->st_rdev);
393 if (r < 0)
394 return -errno;
395
396 if (fchownat(dt, to,
397 uid_is_valid(override_uid) ? override_uid : st->st_uid,
398 gid_is_valid(override_gid) ? override_gid : st->st_gid,
399 AT_SYMLINK_NOFOLLOW) < 0)
400 r = -errno;
401
402 if (fchmodat(dt, to, st->st_mode & 07777, 0) < 0)
403 r = -errno;
404
405 return r;
406 }
407
408 static int fd_copy_directory(
409 int df,
410 const char *from,
411 const struct stat *st,
412 int dt,
413 const char *to,
414 dev_t original_device,
415 uid_t override_uid,
416 gid_t override_gid,
417 CopyFlags copy_flags) {
418
419 _cleanup_close_ int fdf = -1, fdt = -1;
420 _cleanup_closedir_ DIR *d = NULL;
421 struct dirent *de;
422 bool created;
423 int r;
424
425 assert(st);
426 assert(to);
427
428 if (from)
429 fdf = openat(df, from, O_RDONLY|O_DIRECTORY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
430 else
431 fdf = fcntl(df, F_DUPFD_CLOEXEC, 3);
432 if (fdf < 0)
433 return -errno;
434
435 d = fdopendir(fdf);
436 if (!d)
437 return -errno;
438 fdf = -1;
439
440 r = mkdirat(dt, to, st->st_mode & 07777);
441 if (r >= 0)
442 created = true;
443 else if (errno == EEXIST && (copy_flags & COPY_MERGE))
444 created = false;
445 else
446 return -errno;
447
448 fdt = openat(dt, to, O_RDONLY|O_DIRECTORY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
449 if (fdt < 0)
450 return -errno;
451
452 r = 0;
453
454 FOREACH_DIRENT_ALL(de, d, return -errno) {
455 struct stat buf;
456 int q;
457
458 if (dot_or_dot_dot(de->d_name))
459 continue;
460
461 if (fstatat(dirfd(d), de->d_name, &buf, AT_SYMLINK_NOFOLLOW) < 0) {
462 r = -errno;
463 continue;
464 }
465
466 if (buf.st_dev != original_device)
467 continue;
468
469 if (S_ISREG(buf.st_mode))
470 q = fd_copy_regular(dirfd(d), de->d_name, &buf, fdt, de->d_name, override_uid, override_gid, copy_flags);
471 else if (S_ISDIR(buf.st_mode))
472 q = fd_copy_directory(dirfd(d), de->d_name, &buf, fdt, de->d_name, original_device, override_uid, override_gid, copy_flags);
473 else if (S_ISLNK(buf.st_mode))
474 q = fd_copy_symlink(dirfd(d), de->d_name, &buf, fdt, de->d_name, override_uid, override_gid, copy_flags);
475 else if (S_ISFIFO(buf.st_mode))
476 q = fd_copy_fifo(dirfd(d), de->d_name, &buf, fdt, de->d_name, override_uid, override_gid, copy_flags);
477 else if (S_ISBLK(buf.st_mode) || S_ISCHR(buf.st_mode) || S_ISSOCK(buf.st_mode))
478 q = fd_copy_node(dirfd(d), de->d_name, &buf, fdt, de->d_name, override_uid, override_gid, copy_flags);
479 else
480 q = -EOPNOTSUPP;
481
482 if (q == -EEXIST && (copy_flags & COPY_MERGE))
483 q = 0;
484
485 if (q < 0)
486 r = q;
487 }
488
489 if (created) {
490 struct timespec ut[2] = {
491 st->st_atim,
492 st->st_mtim
493 };
494
495 if (fchown(fdt,
496 uid_is_valid(override_uid) ? override_uid : st->st_uid,
497 gid_is_valid(override_gid) ? override_gid : st->st_gid) < 0)
498 r = -errno;
499
500 if (fchmod(fdt, st->st_mode & 07777) < 0)
501 r = -errno;
502
503 (void) copy_xattr(dirfd(d), fdt);
504 (void) futimens(fdt, ut);
505 }
506
507 return r;
508 }
509
510 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) {
511 struct stat st;
512
513 assert(from);
514 assert(to);
515
516 if (fstatat(fdf, from, &st, AT_SYMLINK_NOFOLLOW) < 0)
517 return -errno;
518
519 if (S_ISREG(st.st_mode))
520 return fd_copy_regular(fdf, from, &st, fdt, to, override_uid, override_gid, copy_flags);
521 else if (S_ISDIR(st.st_mode))
522 return fd_copy_directory(fdf, from, &st, fdt, to, st.st_dev, override_uid, override_gid, copy_flags);
523 else if (S_ISLNK(st.st_mode))
524 return fd_copy_symlink(fdf, from, &st, fdt, to, override_uid, override_gid, copy_flags);
525 else if (S_ISFIFO(st.st_mode))
526 return fd_copy_fifo(fdf, from, &st, fdt, to, override_uid, override_gid, copy_flags);
527 else if (S_ISBLK(st.st_mode) || S_ISCHR(st.st_mode) || S_ISSOCK(st.st_mode))
528 return fd_copy_node(fdf, from, &st, fdt, to, override_uid, override_gid, copy_flags);
529 else
530 return -EOPNOTSUPP;
531 }
532
533 int copy_tree(const char *from, const char *to, uid_t override_uid, gid_t override_gid, CopyFlags copy_flags) {
534 return copy_tree_at(AT_FDCWD, from, AT_FDCWD, to, override_uid, override_gid, copy_flags);
535 }
536
537 int copy_directory_fd(int dirfd, const char *to, CopyFlags copy_flags) {
538 struct stat st;
539
540 assert(dirfd >= 0);
541 assert(to);
542
543 if (fstat(dirfd, &st) < 0)
544 return -errno;
545
546 if (!S_ISDIR(st.st_mode))
547 return -ENOTDIR;
548
549 return fd_copy_directory(dirfd, NULL, &st, AT_FDCWD, to, st.st_dev, UID_INVALID, GID_INVALID, copy_flags);
550 }
551
552 int copy_directory(const char *from, const char *to, CopyFlags copy_flags) {
553 struct stat st;
554
555 assert(from);
556 assert(to);
557
558 if (lstat(from, &st) < 0)
559 return -errno;
560
561 if (!S_ISDIR(st.st_mode))
562 return -ENOTDIR;
563
564 return fd_copy_directory(AT_FDCWD, from, &st, AT_FDCWD, to, st.st_dev, UID_INVALID, GID_INVALID, copy_flags);
565 }
566
567 int copy_file_fd(const char *from, int fdt, CopyFlags copy_flags) {
568 _cleanup_close_ int fdf = -1;
569 int r;
570
571 assert(from);
572 assert(fdt >= 0);
573
574 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
575 if (fdf < 0)
576 return -errno;
577
578 r = copy_bytes(fdf, fdt, (uint64_t) -1, copy_flags);
579
580 (void) copy_times(fdf, fdt);
581 (void) copy_xattr(fdf, fdt);
582
583 return r;
584 }
585
586 int copy_file(const char *from, const char *to, int flags, mode_t mode, unsigned chattr_flags, CopyFlags copy_flags) {
587 int fdt = -1, r;
588
589 assert(from);
590 assert(to);
591
592 RUN_WITH_UMASK(0000) {
593 fdt = open(to, flags|O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode);
594 if (fdt < 0)
595 return -errno;
596 }
597
598 if (chattr_flags != 0)
599 (void) chattr_fd(fdt, chattr_flags, (unsigned) -1);
600
601 r = copy_file_fd(from, fdt, copy_flags);
602 if (r < 0) {
603 close(fdt);
604 (void) unlink(to);
605 return r;
606 }
607
608 if (close(fdt) < 0) {
609 unlink_noerrno(to);
610 return -errno;
611 }
612
613 return 0;
614 }
615
616 int copy_file_atomic(const char *from, const char *to, mode_t mode, unsigned chattr_flags, CopyFlags copy_flags) {
617 _cleanup_free_ char *t = NULL;
618 int r;
619
620 assert(from);
621 assert(to);
622
623 r = tempfn_random(to, NULL, &t);
624 if (r < 0)
625 return r;
626
627 r = copy_file(from, t, O_NOFOLLOW|O_EXCL, mode, chattr_flags, copy_flags);
628 if (r < 0)
629 return r;
630
631 if (copy_flags & COPY_REPLACE) {
632 r = renameat(AT_FDCWD, t, AT_FDCWD, to);
633 if (r < 0)
634 r = -errno;
635 } else
636 r = rename_noreplace(AT_FDCWD, t, AT_FDCWD, to);
637 if (r < 0) {
638 (void) unlink(t);
639 return r;
640 }
641
642 return 0;
643 }
644
645 int copy_times(int fdf, int fdt) {
646 struct timespec ut[2];
647 struct stat st;
648 usec_t crtime = 0;
649
650 assert(fdf >= 0);
651 assert(fdt >= 0);
652
653 if (fstat(fdf, &st) < 0)
654 return -errno;
655
656 ut[0] = st.st_atim;
657 ut[1] = st.st_mtim;
658
659 if (futimens(fdt, ut) < 0)
660 return -errno;
661
662 if (fd_getcrtime(fdf, &crtime) >= 0)
663 (void) fd_setcrtime(fdt, crtime);
664
665 return 0;
666 }
667
668 int copy_xattr(int fdf, int fdt) {
669 _cleanup_free_ char *bufa = NULL, *bufb = NULL;
670 size_t sza = 100, szb = 100;
671 ssize_t n;
672 int ret = 0;
673 const char *p;
674
675 for (;;) {
676 bufa = malloc(sza);
677 if (!bufa)
678 return -ENOMEM;
679
680 n = flistxattr(fdf, bufa, sza);
681 if (n == 0)
682 return 0;
683 if (n > 0)
684 break;
685 if (errno != ERANGE)
686 return -errno;
687
688 sza *= 2;
689
690 bufa = mfree(bufa);
691 }
692
693 p = bufa;
694 while (n > 0) {
695 size_t l;
696
697 l = strlen(p);
698 assert(l < (size_t) n);
699
700 if (startswith(p, "user.")) {
701 ssize_t m;
702
703 if (!bufb) {
704 bufb = malloc(szb);
705 if (!bufb)
706 return -ENOMEM;
707 }
708
709 m = fgetxattr(fdf, p, bufb, szb);
710 if (m < 0) {
711 if (errno == ERANGE) {
712 szb *= 2;
713 bufb = mfree(bufb);
714 continue;
715 }
716
717 return -errno;
718 }
719
720 if (fsetxattr(fdt, p, bufb, m, 0) < 0)
721 ret = -errno;
722 }
723
724 p += l + 1;
725 n -= l + 1;
726 }
727
728 return ret;
729 }