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