chiark / gitweb /
bb17d3ae3cb2569de7f243756a31d416989b6322
[elogind.git] / src / basic / copy.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3   Copyright 2014 Lennart Poettering
4 ***/
5
6 //#include <dirent.h>
7 //#include <errno.h>
8 //#include <fcntl.h>
9 //#include <stddef.h>
10 //#include <stdio.h>
11 //#include <stdlib.h>
12 //#include <string.h>
13 #include <sys/sendfile.h>
14 //#include <sys/stat.h>
15 #include <sys/xattr.h>
16 //#include <time.h>
17 //#include <unistd.h>
18
19 //#include "alloc-util.h"
20 //#include "btrfs-util.h"
21 //#include "chattr-util.h"
22 #include "copy.h"
23 //#include "dirent-util.h"
24 //#include "fd-util.h"
25 //#include "fileio.h"
26 //#include "fs-util.h"
27 #include "io-util.h"
28 //#include "macro.h"
29 #include "missing.h"
30 //#include "mount-util.h"
31 //#include "string-util.h"
32 #include "strv.h"
33 #include "time-util.h"
34 //#include "umask-util.h"
35 #include "user-util.h"
36 //#include "xattr-util.h"
37
38 #define COPY_BUFFER_SIZE (16U*1024U)
39
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
44
45 static ssize_t try_copy_file_range(
46                 int fd_in, loff_t *off_in,
47                 int fd_out, loff_t *off_out,
48                 size_t len,
49                 unsigned int flags) {
50
51         static int have = -1;
52         ssize_t r;
53
54         if (have == 0)
55                 return -ENOSYS;
56
57         r = copy_file_range(fd_in, off_in, fd_out, off_out, len, flags);
58         if (have < 0)
59                 have = r >= 0 || errno != ENOSYS;
60         if (r < 0)
61                 return -errno;
62
63         return r;
64 }
65
66 enum {
67         FD_IS_NO_PIPE,
68         FD_IS_BLOCKING_PIPE,
69         FD_IS_NONBLOCKING_PIPE,
70 };
71
72 static int fd_is_nonblock_pipe(int fd) {
73         struct stat st;
74         int flags;
75
76         /* Checks whether the specified file descriptor refers to a pipe, and if so if O_NONBLOCK is set. */
77
78         if (fstat(fd, &st) < 0)
79                 return -errno;
80
81         if (!S_ISFIFO(st.st_mode))
82                 return FD_IS_NO_PIPE;
83
84         flags = fcntl(fd, F_GETFL);
85         if (flags < 0)
86                 return -errno;
87
88         return FLAGS_SET(flags, O_NONBLOCK) ? FD_IS_NONBLOCKING_PIPE : FD_IS_BLOCKING_PIPE;
89 }
90
91 int copy_bytes_full(
92                 int fdf, int fdt,
93                 uint64_t max_bytes,
94                 CopyFlags copy_flags,
95                 void **ret_remains,
96                 size_t *ret_remains_size) {
97
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 */
101
102         assert(fdf >= 0);
103         assert(fdt >= 0);
104
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. */
112
113         if (ret_remains)
114                 *ret_remains = NULL;
115         if (ret_remains_size)
116                 *ret_remains_size = 0;
117
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)) {
122                 off_t foffset;
123
124                 foffset = lseek(fdf, 0, SEEK_CUR);
125                 if (foffset >= 0) {
126                         off_t toffset;
127
128                         toffset = lseek(fdt, 0, SEEK_CUR);
129                         if (toffset >= 0) {
130
131                                 if (foffset == 0 && toffset == 0 && max_bytes == UINT64_MAX)
132                                         r = btrfs_reflink(fdf, fdt); /* full file reflink */
133                                 else
134                                         r = btrfs_clone_range(fdf, foffset, fdt, toffset, max_bytes == UINT64_MAX ? 0 : max_bytes); /* partial reflink */
135                                 if (r >= 0) {
136                                         off_t t;
137
138                                         /* This worked, yay! Now — to be fully correct — let's adjust the file pointers */
139                                         if (max_bytes == UINT64_MAX) {
140
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);
144                                                 if (t < 0)
145                                                         return -errno;
146                                                 if (t < foffset)
147                                                         return -ESPIPE;
148
149                                                 /* Let's adjust the destination file write pointer by the same number
150                                                  * of bytes. */
151                                                 t = lseek(fdt, toffset + (t - foffset), SEEK_SET);
152                                                 if (t < 0)
153                                                         return -errno;
154
155                                                 return 0; /* we copied the whole thing, hence hit EOF, return 0 */
156                                         } else {
157                                                 t = lseek(fdf, foffset + max_bytes, SEEK_SET);
158                                                 if (t < 0)
159                                                         return -errno;
160
161                                                 t = lseek(fdt, toffset + max_bytes, SEEK_SET);
162                                                 if (t < 0)
163                                                         return -errno;
164
165                                                 return 1; /* we copied only some number of bytes, which worked, but this means we didn't hit EOF, return 1 */
166                                         }
167                                 }
168
169                                 log_debug_errno(r, "Reflinking didn't work, falling back to non-reflink copying: %m");
170                         }
171                 }
172         }
173 #endif // 0
174
175         for (;;) {
176                 ssize_t n;
177
178                 if (max_bytes <= 0)
179                         return 1; /* return > 0 if we hit the max_bytes limit */
180
181                 if (max_bytes != UINT64_MAX && m > max_bytes)
182                         m = max_bytes;
183
184                 /* First try copy_file_range(), unless we already tried */
185                 if (try_cfr) {
186                         n = try_copy_file_range(fdf, NULL, fdt, NULL, m, 0u);
187                         if (n < 0) {
188                                 if (!IN_SET(n, -EINVAL, -ENOSYS, -EXDEV, -EBADF))
189                                         return n;
190
191                                 try_cfr = false;
192                                 /* use fallback below */
193                         } else if (n == 0) /* EOF */
194                                 break;
195                         else
196                                 /* Success! */
197                                 goto next;
198                 }
199
200                 /* First try sendfile(), unless we already tried */
201                 if (try_sendfile) {
202                         n = sendfile(fdt, fdf, NULL, m);
203                         if (n < 0) {
204                                 if (!IN_SET(errno, EINVAL, ENOSYS))
205                                         return -errno;
206
207                                 try_sendfile = false;
208                                 /* use fallback below */
209                         } else if (n == 0) /* EOF */
210                                 break;
211                         else
212                                 /* Success! */
213                                 goto next;
214                 }
215
216                 /* Then try splice, unless we already tried. */
217                 if (try_splice) {
218
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.
224                          *
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. */
229
230                         if (nonblock_pipe < 0) {
231                                 int a, b;
232
233                                 /* Check if either of these fds is a pipe, and if so non-blocking or not */
234                                 a = fd_is_nonblock_pipe(fdf);
235                                 if (a < 0)
236                                         return a;
237
238                                 b = fd_is_nonblock_pipe(fdt);
239                                 if (b < 0)
240                                         return b;
241
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))
245
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. */
252
253                                         try_splice = false;
254                                 else
255                                         nonblock_pipe = a == FD_IS_NONBLOCKING_PIPE || b == FD_IS_NONBLOCKING_PIPE;
256                         }
257                 }
258
259                 if (try_splice) {
260                         n = splice(fdf, NULL, fdt, NULL, m, nonblock_pipe ? SPLICE_F_NONBLOCK : 0);
261                         if (n < 0) {
262                                 if (!IN_SET(errno, EINVAL, ENOSYS))
263                                         return -errno;
264
265                                 try_splice = false;
266                                 /* use fallback below */
267                         } else if (n == 0) /* EOF */
268                                 break;
269                         else
270                                 /* Success! */
271                                 goto next;
272                 }
273
274                 /* As a fallback just copy bits by hand */
275                 {
276                         uint8_t buf[MIN(m, COPY_BUFFER_SIZE)], *p = buf;
277                         ssize_t z;
278
279                         n = read(fdf, buf, sizeof buf);
280                         if (n < 0)
281                                 return -errno;
282                         if (n == 0) /* EOF */
283                                 break;
284
285                         z = (size_t) n;
286                         do {
287                                 ssize_t k;
288
289                                 k = write(fdt, p, z);
290                                 if (k < 0) {
291                                         r = -errno;
292
293                                         if (ret_remains) {
294                                                 void *copy;
295
296                                                 copy = memdup(p, z);
297                                                 if (!copy)
298                                                         return -ENOMEM;
299
300                                                 *ret_remains = copy;
301                                         }
302
303                                         if (ret_remains_size)
304                                                 *ret_remains_size = z;
305
306                                         return r;
307                                 }
308
309                                 assert(k <= z);
310                                 z -= k;
311                                 p += k;
312                         } while (z > 0);
313                 }
314
315         next:
316                 if (max_bytes != (uint64_t) -1) {
317                         assert(max_bytes >= (uint64_t) n);
318                         max_bytes -= n;
319                 }
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);
325         }
326
327         return 0; /* return 0 if we hit EOF earlier than the size limit */
328 }
329
330 #if 0 /// UNNEEDED by elogind
331 static int fd_copy_symlink(
332                 int df,
333                 const char *from,
334                 const struct stat *st,
335                 int dt,
336                 const char *to,
337                 uid_t override_uid,
338                 gid_t override_gid,
339                 CopyFlags copy_flags) {
340
341         _cleanup_free_ char *target = NULL;
342         int r;
343
344         assert(from);
345         assert(st);
346         assert(to);
347
348         r = readlinkat_malloc(df, from, &target);
349         if (r < 0)
350                 return r;
351
352         if (symlinkat(target, dt, to) < 0)
353                 return -errno;
354
355         if (fchownat(dt, to,
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)
359                 return -errno;
360
361         return 0;
362 }
363
364 static int fd_copy_regular(
365                 int df,
366                 const char *from,
367                 const struct stat *st,
368                 int dt,
369                 const char *to,
370                 uid_t override_uid,
371                 gid_t override_gid,
372                 CopyFlags copy_flags) {
373
374         _cleanup_close_ int fdf = -1, fdt = -1;
375         struct timespec ts[2];
376         int r, q;
377
378         assert(from);
379         assert(st);
380         assert(to);
381
382         fdf = openat(df, from, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
383         if (fdf < 0)
384                 return -errno;
385
386         fdt = openat(dt, to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, st->st_mode & 07777);
387         if (fdt < 0)
388                 return -errno;
389
390         r = copy_bytes(fdf, fdt, (uint64_t) -1, copy_flags);
391         if (r < 0) {
392                 (void) unlinkat(dt, to, 0);
393                 return r;
394         }
395
396         if (fchown(fdt,
397                    uid_is_valid(override_uid) ? override_uid : st->st_uid,
398                    gid_is_valid(override_gid) ? override_gid : st->st_gid) < 0)
399                 r = -errno;
400
401         if (fchmod(fdt, st->st_mode & 07777) < 0)
402                 r = -errno;
403
404         ts[0] = st->st_atim;
405         ts[1] = st->st_mtim;
406         (void) futimens(fdt, ts);
407         (void) copy_xattr(fdf, fdt);
408
409         q = close(fdt);
410         fdt = -1;
411
412         if (q < 0) {
413                 r = -errno;
414                 (void) unlinkat(dt, to, 0);
415         }
416
417         return r;
418 }
419
420 static int fd_copy_fifo(
421                 int df,
422                 const char *from,
423                 const struct stat *st,
424                 int dt,
425                 const char *to,
426                 uid_t override_uid,
427                 gid_t override_gid,
428                 CopyFlags copy_flags) {
429         int r;
430
431         assert(from);
432         assert(st);
433         assert(to);
434
435         r = mkfifoat(dt, to, st->st_mode & 07777);
436         if (r < 0)
437                 return -errno;
438
439         if (fchownat(dt, to,
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)
443                 r = -errno;
444
445         if (fchmodat(dt, to, st->st_mode & 07777, 0) < 0)
446                 r = -errno;
447
448         return r;
449 }
450
451 static int fd_copy_node(
452                 int df,
453                 const char *from,
454                 const struct stat *st,
455                 int dt,
456                 const char *to,
457                 uid_t override_uid,
458                 gid_t override_gid,
459                 CopyFlags copy_flags) {
460         int r;
461
462         assert(from);
463         assert(st);
464         assert(to);
465
466         r = mknodat(dt, to, st->st_mode, st->st_rdev);
467         if (r < 0)
468                 return -errno;
469
470         if (fchownat(dt, to,
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)
474                 r = -errno;
475
476         if (fchmodat(dt, to, st->st_mode & 07777, 0) < 0)
477                 r = -errno;
478
479         return r;
480 }
481
482 static int fd_copy_directory(
483                 int df,
484                 const char *from,
485                 const struct stat *st,
486                 int dt,
487                 const char *to,
488                 dev_t original_device,
489                 unsigned depth_left,
490                 uid_t override_uid,
491                 gid_t override_gid,
492                 CopyFlags copy_flags) {
493
494         _cleanup_close_ int fdf = -1, fdt = -1;
495         _cleanup_closedir_ DIR *d = NULL;
496         struct dirent *de;
497         bool created;
498         int r;
499
500         assert(st);
501         assert(to);
502
503         if (depth_left == 0)
504                 return -ENAMETOOLONG;
505
506         if (from)
507                 fdf = openat(df, from, O_RDONLY|O_DIRECTORY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
508         else
509                 fdf = fcntl(df, F_DUPFD_CLOEXEC, 3);
510         if (fdf < 0)
511                 return -errno;
512
513         d = fdopendir(fdf);
514         if (!d)
515                 return -errno;
516         fdf = -1;
517
518         r = mkdirat(dt, to, st->st_mode & 07777);
519         if (r >= 0)
520                 created = true;
521         else if (errno == EEXIST && (copy_flags & COPY_MERGE))
522                 created = false;
523         else
524                 return -errno;
525
526         fdt = openat(dt, to, O_RDONLY|O_DIRECTORY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
527         if (fdt < 0)
528                 return -errno;
529
530         r = 0;
531
532         FOREACH_DIRENT_ALL(de, d, return -errno) {
533                 struct stat buf;
534                 int q;
535
536                 if (dot_or_dot_dot(de->d_name))
537                         continue;
538
539                 if (fstatat(dirfd(d), de->d_name, &buf, AT_SYMLINK_NOFOLLOW) < 0) {
540                         r = -errno;
541                         continue;
542                 }
543
544                 if (S_ISDIR(buf.st_mode)) {
545                         /*
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:
549                          *
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.
555                          *
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).
562                          */
563
564                         if (FLAGS_SET(copy_flags, COPY_SAME_MOUNT)) {
565                                 if (buf.st_dev != original_device)
566                                         continue;
567
568                                 r = fd_is_mount_point(dirfd(d), de->d_name, 0);
569                                 if (r < 0)
570                                         return r;
571                                 if (r > 0)
572                                         continue;
573                         }
574
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);
584                 else
585                         q = -EOPNOTSUPP;
586
587                 if (q == -EEXIST && (copy_flags & COPY_MERGE))
588                         q = 0;
589
590                 if (q < 0)
591                         r = q;
592         }
593
594         if (created) {
595                 struct timespec ut[2] = {
596                         st->st_atim,
597                         st->st_mtim
598                 };
599
600                 if (fchown(fdt,
601                            uid_is_valid(override_uid) ? override_uid : st->st_uid,
602                            gid_is_valid(override_gid) ? override_gid : st->st_gid) < 0)
603                         r = -errno;
604
605                 if (fchmod(fdt, st->st_mode & 07777) < 0)
606                         r = -errno;
607
608                 (void) copy_xattr(dirfd(d), fdt);
609                 (void) futimens(fdt, ut);
610         }
611
612         return r;
613 }
614
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) {
616         struct stat st;
617
618         assert(from);
619         assert(to);
620
621         if (fstatat(fdf, from, &st, AT_SYMLINK_NOFOLLOW) < 0)
622                 return -errno;
623
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);
634         else
635                 return -EOPNOTSUPP;
636 }
637
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);
640 }
641
642 int copy_directory_fd(int dirfd, const char *to, CopyFlags copy_flags) {
643         struct stat st;
644
645         assert(dirfd >= 0);
646         assert(to);
647
648         if (fstat(dirfd, &st) < 0)
649                 return -errno;
650
651         if (!S_ISDIR(st.st_mode))
652                 return -ENOTDIR;
653
654         return fd_copy_directory(dirfd, NULL, &st, AT_FDCWD, to, st.st_dev, COPY_DEPTH_MAX, UID_INVALID, GID_INVALID, copy_flags);
655 }
656
657 int copy_directory(const char *from, const char *to, CopyFlags copy_flags) {
658         struct stat st;
659
660         assert(from);
661         assert(to);
662
663         if (lstat(from, &st) < 0)
664                 return -errno;
665
666         if (!S_ISDIR(st.st_mode))
667                 return -ENOTDIR;
668
669         return fd_copy_directory(AT_FDCWD, from, &st, AT_FDCWD, to, st.st_dev, COPY_DEPTH_MAX, UID_INVALID, GID_INVALID, copy_flags);
670 }
671
672 int copy_file_fd(const char *from, int fdt, CopyFlags copy_flags) {
673         _cleanup_close_ int fdf = -1;
674         int r;
675
676         assert(from);
677         assert(fdt >= 0);
678
679         fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
680         if (fdf < 0)
681                 return -errno;
682
683         r = copy_bytes(fdf, fdt, (uint64_t) -1, copy_flags);
684
685         (void) copy_times(fdf, fdt);
686         (void) copy_xattr(fdf, fdt);
687
688         return r;
689 }
690
691 int copy_file(const char *from, const char *to, int flags, mode_t mode, unsigned chattr_flags, CopyFlags copy_flags) {
692         int fdt = -1, r;
693
694         assert(from);
695         assert(to);
696
697         RUN_WITH_UMASK(0000) {
698                 fdt = open(to, flags|O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode);
699                 if (fdt < 0)
700                         return -errno;
701         }
702
703         if (chattr_flags != 0)
704                 (void) chattr_fd(fdt, chattr_flags, (unsigned) -1);
705
706         r = copy_file_fd(from, fdt, copy_flags);
707         if (r < 0) {
708                 close(fdt);
709                 (void) unlink(to);
710                 return r;
711         }
712
713         if (close(fdt) < 0) {
714                 unlink_noerrno(to);
715                 return -errno;
716         }
717
718         return 0;
719 }
720
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;
723         int r;
724
725         assert(from);
726         assert(to);
727
728         r = tempfn_random(to, NULL, &t);
729         if (r < 0)
730                 return r;
731
732         r = copy_file(from, t, O_NOFOLLOW|O_EXCL, mode, chattr_flags, copy_flags);
733         if (r < 0)
734                 return r;
735
736         if (copy_flags & COPY_REPLACE) {
737                 r = renameat(AT_FDCWD, t, AT_FDCWD, to);
738                 if (r < 0)
739                         r = -errno;
740         } else
741                 r = rename_noreplace(AT_FDCWD, t, AT_FDCWD, to);
742         if (r < 0) {
743                 (void) unlink(t);
744                 return r;
745         }
746
747         return 0;
748 }
749
750 int copy_times(int fdf, int fdt) {
751         struct timespec ut[2];
752         struct stat st;
753         usec_t crtime = 0;
754
755         assert(fdf >= 0);
756         assert(fdt >= 0);
757
758         if (fstat(fdf, &st) < 0)
759                 return -errno;
760
761         ut[0] = st.st_atim;
762         ut[1] = st.st_mtim;
763
764         if (futimens(fdt, ut) < 0)
765                 return -errno;
766
767         if (fd_getcrtime(fdf, &crtime) >= 0)
768                 (void) fd_setcrtime(fdt, crtime);
769
770         return 0;
771 }
772
773 int copy_xattr(int fdf, int fdt) {
774         _cleanup_free_ char *bufa = NULL, *bufb = NULL;
775         size_t sza = 100, szb = 100;
776         ssize_t n;
777         int ret = 0;
778         const char *p;
779
780         for (;;) {
781                 bufa = malloc(sza);
782                 if (!bufa)
783                         return -ENOMEM;
784
785                 n = flistxattr(fdf, bufa, sza);
786                 if (n == 0)
787                         return 0;
788                 if (n > 0)
789                         break;
790                 if (errno != ERANGE)
791                         return -errno;
792
793                 sza *= 2;
794
795                 bufa = mfree(bufa);
796         }
797
798         p = bufa;
799         while (n > 0) {
800                 size_t l;
801
802                 l = strlen(p);
803                 assert(l < (size_t) n);
804
805                 if (startswith(p, "user.")) {
806                         ssize_t m;
807
808                         if (!bufb) {
809                                 bufb = malloc(szb);
810                                 if (!bufb)
811                                         return -ENOMEM;
812                         }
813
814                         m = fgetxattr(fdf, p, bufb, szb);
815                         if (m < 0) {
816                                 if (errno == ERANGE) {
817                                         szb *= 2;
818                                         bufb = mfree(bufb);
819                                         continue;
820                                 }
821
822                                 return -errno;
823                         }
824
825                         if (fsetxattr(fdt, p, bufb, m, 0) < 0)
826                                 ret = -errno;
827                 }
828
829                 p += l + 1;
830                 n -= l + 1;
831         }
832
833         return ret;
834 }
835 #endif // 0