chiark / gitweb /
964613f8c74867ea0293bed989b29b60695be107
[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 "mount-util.h"
33 //#include "string-util.h"
34 #include "strv.h"
35 #include "time-util.h"
36 //#include "umask-util.h"
37 #include "user-util.h"
38 //#include "xattr-util.h"
39
40 #define COPY_BUFFER_SIZE (16U*1024U)
41
42 /* A safety net for descending recursively into file system trees to copy. On Linux PATH_MAX is 4096, which means the
43  * deepest valid path one can build is around 2048, which we hence use as a safety net here, to not spin endlessly in
44  * case of bind mount cycles and suchlike. */
45 #define COPY_DEPTH_MAX 2048U
46
47 static ssize_t try_copy_file_range(
48                 int fd_in, loff_t *off_in,
49                 int fd_out, loff_t *off_out,
50                 size_t len,
51                 unsigned int flags) {
52
53         static int have = -1;
54         ssize_t r;
55
56         if (have == 0)
57                 return -ENOSYS;
58
59         r = copy_file_range(fd_in, off_in, fd_out, off_out, len, flags);
60         if (have < 0)
61                 have = r >= 0 || errno != ENOSYS;
62         if (r < 0)
63                 return -errno;
64
65         return r;
66 }
67
68 enum {
69         FD_IS_NO_PIPE,
70         FD_IS_BLOCKING_PIPE,
71         FD_IS_NONBLOCKING_PIPE,
72 };
73
74 static int fd_is_nonblock_pipe(int fd) {
75         struct stat st;
76         int flags;
77
78         /* Checks whether the specified file descriptor refers to a pipe, and if so if O_NONBLOCK is set. */
79
80         if (fstat(fd, &st) < 0)
81                 return -errno;
82
83         if (!S_ISFIFO(st.st_mode))
84                 return FD_IS_NO_PIPE;
85
86         flags = fcntl(fd, F_GETFL);
87         if (flags < 0)
88                 return -errno;
89
90         return FLAGS_SET(flags, O_NONBLOCK) ? FD_IS_NONBLOCKING_PIPE : FD_IS_BLOCKING_PIPE;
91 }
92
93 int copy_bytes_full(
94                 int fdf, int fdt,
95                 uint64_t max_bytes,
96                 CopyFlags copy_flags,
97                 void **ret_remains,
98                 size_t *ret_remains_size) {
99
100         bool try_cfr = true, try_sendfile = true, try_splice = true;
101         int r, nonblock_pipe = -1;
102         size_t m = SSIZE_MAX; /* that is the maximum that sendfile and c_f_r accept */
103
104         assert(fdf >= 0);
105         assert(fdt >= 0);
106
107         /* Tries to copy bytes from the file descriptor 'fdf' to 'fdt' in the smartest possible way. Copies a maximum
108          * of 'max_bytes', which may be specified as UINT64_MAX, in which no maximum is applied. Returns negative on
109          * error, zero if EOF is hit before the bytes limit is hit and positive otherwise. If the copy fails for some
110          * reason but we read but didn't yet write some data an ret_remains/ret_remains_size is not NULL, then it will
111          * be initialized with an allocated buffer containing this "remaining" data. Note that these two parameters are
112          * initialized with a valid buffer only on failure and only if there's actually data already read. Otherwise
113          * these parameters if non-NULL are set to NULL. */
114
115         if (ret_remains)
116                 *ret_remains = NULL;
117         if (ret_remains_size)
118                 *ret_remains_size = 0;
119
120 #if 0 /// UNNEEDED by elogind
121         /* Try btrfs reflinks first. This only works on regular, seekable files, hence let's check the file offsets of
122          * source and destination first. */
123         if ((copy_flags & COPY_REFLINK)) {
124                 off_t foffset;
125
126                 foffset = lseek(fdf, 0, SEEK_CUR);
127                 if (foffset >= 0) {
128                         off_t toffset;
129
130                         toffset = lseek(fdt, 0, SEEK_CUR);
131                         if (toffset >= 0) {
132
133                                 if (foffset == 0 && toffset == 0 && max_bytes == UINT64_MAX)
134                                         r = btrfs_reflink(fdf, fdt); /* full file reflink */
135                                 else
136                                         r = btrfs_clone_range(fdf, foffset, fdt, toffset, max_bytes == UINT64_MAX ? 0 : max_bytes); /* partial reflink */
137                                 if (r >= 0) {
138                                         off_t t;
139
140                                         /* This worked, yay! Now — to be fully correct — let's adjust the file pointers */
141                                         if (max_bytes == UINT64_MAX) {
142
143                                                 /* We cloned to the end of the source file, let's position the read
144                                                  * pointer there, and query it at the same time. */
145                                                 t = lseek(fdf, 0, SEEK_END);
146                                                 if (t < 0)
147                                                         return -errno;
148                                                 if (t < foffset)
149                                                         return -ESPIPE;
150
151                                                 /* Let's adjust the destination file write pointer by the same number
152                                                  * of bytes. */
153                                                 t = lseek(fdt, toffset + (t - foffset), SEEK_SET);
154                                                 if (t < 0)
155                                                         return -errno;
156
157                                                 return 0; /* we copied the whole thing, hence hit EOF, return 0 */
158                                         } else {
159                                                 t = lseek(fdf, foffset + max_bytes, SEEK_SET);
160                                                 if (t < 0)
161                                                         return -errno;
162
163                                                 t = lseek(fdt, toffset + max_bytes, SEEK_SET);
164                                                 if (t < 0)
165                                                         return -errno;
166
167                                                 return 1; /* we copied only some number of bytes, which worked, but this means we didn't hit EOF, return 1 */
168                                         }
169                                 }
170
171                                 log_debug_errno(r, "Reflinking didn't work, falling back to non-reflink copying: %m");
172                         }
173                 }
174         }
175 #endif // 0
176
177         for (;;) {
178                 ssize_t n;
179
180                 if (max_bytes <= 0)
181                         return 1; /* return > 0 if we hit the max_bytes limit */
182
183                 if (max_bytes != UINT64_MAX && m > max_bytes)
184                         m = max_bytes;
185
186                 /* First try copy_file_range(), unless we already tried */
187                 if (try_cfr) {
188                         n = try_copy_file_range(fdf, NULL, fdt, NULL, m, 0u);
189                         if (n < 0) {
190                                 if (!IN_SET(n, -EINVAL, -ENOSYS, -EXDEV, -EBADF))
191                                         return n;
192
193                                 try_cfr = false;
194                                 /* use fallback below */
195                         } else if (n == 0) /* EOF */
196                                 break;
197                         else
198                                 /* Success! */
199                                 goto next;
200                 }
201
202                 /* First try sendfile(), unless we already tried */
203                 if (try_sendfile) {
204                         n = sendfile(fdt, fdf, NULL, m);
205                         if (n < 0) {
206                                 if (!IN_SET(errno, EINVAL, ENOSYS))
207                                         return -errno;
208
209                                 try_sendfile = false;
210                                 /* use fallback below */
211                         } else if (n == 0) /* EOF */
212                                 break;
213                         else
214                                 /* Success! */
215                                 goto next;
216                 }
217
218                 /* Then try splice, unless we already tried. */
219                 if (try_splice) {
220
221                         /* splice()'s asynchronous I/O support is a bit weird. When it encounters a pipe file
222                          * descriptor, then it will ignore its O_NONBLOCK flag and instead only honour the
223                          * SPLICE_F_NONBLOCK flag specified in its flag parameter. Let's hide this behaviour here, and
224                          * check if either of the specified fds are a pipe, and if so, let's pass the flag
225                          * automatically, depending on O_NONBLOCK being set.
226                          *
227                          * Here's a twist though: when we use it to move data between two pipes of which one has
228                          * O_NONBLOCK set and the other has not, then we have no individual control over O_NONBLOCK
229                          * behaviour. Hence in that case we can't use splice() and still guarantee systematic
230                          * O_NONBLOCK behaviour, hence don't. */
231
232                         if (nonblock_pipe < 0) {
233                                 int a, b;
234
235                                 /* Check if either of these fds is a pipe, and if so non-blocking or not */
236                                 a = fd_is_nonblock_pipe(fdf);
237                                 if (a < 0)
238                                         return a;
239
240                                 b = fd_is_nonblock_pipe(fdt);
241                                 if (b < 0)
242                                         return b;
243
244                                 if ((a == FD_IS_NO_PIPE && b == FD_IS_NO_PIPE) ||
245                                     (a == FD_IS_BLOCKING_PIPE && b == FD_IS_NONBLOCKING_PIPE) ||
246                                     (a == FD_IS_NONBLOCKING_PIPE && b == FD_IS_BLOCKING_PIPE))
247
248                                         /* splice() only works if one of the fds is a pipe. If neither is, let's skip
249                                          * this step right-away. As mentioned above, if one of the two fds refers to a
250                                          * blocking pipe and the other to a non-blocking pipe, we can't use splice()
251                                          * either, hence don't try either. This hence means we can only use splice() if
252                                          * either only one of the two fds is a pipe, or if both are pipes with the same
253                                          * nonblocking flag setting. */
254
255                                         try_splice = false;
256                                 else
257                                         nonblock_pipe = a == FD_IS_NONBLOCKING_PIPE || b == FD_IS_NONBLOCKING_PIPE;
258                         }
259                 }
260
261                 if (try_splice) {
262                         n = splice(fdf, NULL, fdt, NULL, m, nonblock_pipe ? SPLICE_F_NONBLOCK : 0);
263                         if (n < 0) {
264                                 if (!IN_SET(errno, EINVAL, ENOSYS))
265                                         return -errno;
266
267                                 try_splice = false;
268                                 /* use fallback below */
269                         } else if (n == 0) /* EOF */
270                                 break;
271                         else
272                                 /* Success! */
273                                 goto next;
274                 }
275
276                 /* As a fallback just copy bits by hand */
277                 {
278                         uint8_t buf[MIN(m, COPY_BUFFER_SIZE)], *p = buf;
279                         ssize_t z;
280
281                         n = read(fdf, buf, sizeof buf);
282                         if (n < 0)
283                                 return -errno;
284                         if (n == 0) /* EOF */
285                                 break;
286
287                         z = (size_t) n;
288                         do {
289                                 ssize_t k;
290
291                                 k = write(fdt, p, z);
292                                 if (k < 0) {
293                                         r = -errno;
294
295                                         if (ret_remains) {
296                                                 void *copy;
297
298                                                 copy = memdup(p, z);
299                                                 if (!copy)
300                                                         return -ENOMEM;
301
302                                                 *ret_remains = copy;
303                                         }
304
305                                         if (ret_remains_size)
306                                                 *ret_remains_size = z;
307
308                                         return r;
309                                 }
310
311                                 assert(k <= z);
312                                 z -= k;
313                                 p += k;
314                         } while (z > 0);
315                 }
316
317         next:
318                 if (max_bytes != (uint64_t) -1) {
319                         assert(max_bytes >= (uint64_t) n);
320                         max_bytes -= n;
321                 }
322                 /* sendfile accepts at most SSIZE_MAX-offset bytes to copy,
323                  * so reduce our maximum by the amount we already copied,
324                  * but don't go below our copy buffer size, unless we are
325                  * close the limit of bytes we are allowed to copy. */
326                 m = MAX(MIN(COPY_BUFFER_SIZE, max_bytes), m - n);
327         }
328
329         return 0; /* return 0 if we hit EOF earlier than the size limit */
330 }
331
332 #if 0 /// UNNEEDED by elogind
333 static int fd_copy_symlink(
334                 int df,
335                 const char *from,
336                 const struct stat *st,
337                 int dt,
338                 const char *to,
339                 uid_t override_uid,
340                 gid_t override_gid,
341                 CopyFlags copy_flags) {
342
343         _cleanup_free_ char *target = NULL;
344         int r;
345
346         assert(from);
347         assert(st);
348         assert(to);
349
350         r = readlinkat_malloc(df, from, &target);
351         if (r < 0)
352                 return r;
353
354         if (symlinkat(target, dt, to) < 0)
355                 return -errno;
356
357         if (fchownat(dt, to,
358                      uid_is_valid(override_uid) ? override_uid : st->st_uid,
359                      gid_is_valid(override_gid) ? override_gid : st->st_gid,
360                      AT_SYMLINK_NOFOLLOW) < 0)
361                 return -errno;
362
363         return 0;
364 }
365
366 static int fd_copy_regular(
367                 int df,
368                 const char *from,
369                 const struct stat *st,
370                 int dt,
371                 const char *to,
372                 uid_t override_uid,
373                 gid_t override_gid,
374                 CopyFlags copy_flags) {
375
376         _cleanup_close_ int fdf = -1, fdt = -1;
377         struct timespec ts[2];
378         int r, q;
379
380         assert(from);
381         assert(st);
382         assert(to);
383
384         fdf = openat(df, from, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
385         if (fdf < 0)
386                 return -errno;
387
388         fdt = openat(dt, to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, st->st_mode & 07777);
389         if (fdt < 0)
390                 return -errno;
391
392         r = copy_bytes(fdf, fdt, (uint64_t) -1, copy_flags);
393         if (r < 0) {
394                 (void) unlinkat(dt, to, 0);
395                 return r;
396         }
397
398         if (fchown(fdt,
399                    uid_is_valid(override_uid) ? override_uid : st->st_uid,
400                    gid_is_valid(override_gid) ? override_gid : st->st_gid) < 0)
401                 r = -errno;
402
403         if (fchmod(fdt, st->st_mode & 07777) < 0)
404                 r = -errno;
405
406         ts[0] = st->st_atim;
407         ts[1] = st->st_mtim;
408         (void) futimens(fdt, ts);
409         (void) copy_xattr(fdf, fdt);
410
411         q = close(fdt);
412         fdt = -1;
413
414         if (q < 0) {
415                 r = -errno;
416                 (void) unlinkat(dt, to, 0);
417         }
418
419         return r;
420 }
421
422 static int fd_copy_fifo(
423                 int df,
424                 const char *from,
425                 const struct stat *st,
426                 int dt,
427                 const char *to,
428                 uid_t override_uid,
429                 gid_t override_gid,
430                 CopyFlags copy_flags) {
431         int r;
432
433         assert(from);
434         assert(st);
435         assert(to);
436
437         r = mkfifoat(dt, to, st->st_mode & 07777);
438         if (r < 0)
439                 return -errno;
440
441         if (fchownat(dt, to,
442                      uid_is_valid(override_uid) ? override_uid : st->st_uid,
443                      gid_is_valid(override_gid) ? override_gid : st->st_gid,
444                      AT_SYMLINK_NOFOLLOW) < 0)
445                 r = -errno;
446
447         if (fchmodat(dt, to, st->st_mode & 07777, 0) < 0)
448                 r = -errno;
449
450         return r;
451 }
452
453 static int fd_copy_node(
454                 int df,
455                 const char *from,
456                 const struct stat *st,
457                 int dt,
458                 const char *to,
459                 uid_t override_uid,
460                 gid_t override_gid,
461                 CopyFlags copy_flags) {
462         int r;
463
464         assert(from);
465         assert(st);
466         assert(to);
467
468         r = mknodat(dt, to, st->st_mode, st->st_rdev);
469         if (r < 0)
470                 return -errno;
471
472         if (fchownat(dt, to,
473                      uid_is_valid(override_uid) ? override_uid : st->st_uid,
474                      gid_is_valid(override_gid) ? override_gid : st->st_gid,
475                      AT_SYMLINK_NOFOLLOW) < 0)
476                 r = -errno;
477
478         if (fchmodat(dt, to, st->st_mode & 07777, 0) < 0)
479                 r = -errno;
480
481         return r;
482 }
483
484 static int fd_copy_directory(
485                 int df,
486                 const char *from,
487                 const struct stat *st,
488                 int dt,
489                 const char *to,
490                 dev_t original_device,
491                 unsigned depth_left,
492                 uid_t override_uid,
493                 gid_t override_gid,
494                 CopyFlags copy_flags) {
495
496         _cleanup_close_ int fdf = -1, fdt = -1;
497         _cleanup_closedir_ DIR *d = NULL;
498         struct dirent *de;
499         bool created;
500         int r;
501
502         assert(st);
503         assert(to);
504
505         if (depth_left == 0)
506                 return -ENAMETOOLONG;
507
508         if (from)
509                 fdf = openat(df, from, O_RDONLY|O_DIRECTORY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
510         else
511                 fdf = fcntl(df, F_DUPFD_CLOEXEC, 3);
512         if (fdf < 0)
513                 return -errno;
514
515         d = fdopendir(fdf);
516         if (!d)
517                 return -errno;
518         fdf = -1;
519
520         r = mkdirat(dt, to, st->st_mode & 07777);
521         if (r >= 0)
522                 created = true;
523         else if (errno == EEXIST && (copy_flags & COPY_MERGE))
524                 created = false;
525         else
526                 return -errno;
527
528         fdt = openat(dt, to, O_RDONLY|O_DIRECTORY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
529         if (fdt < 0)
530                 return -errno;
531
532         r = 0;
533
534         FOREACH_DIRENT_ALL(de, d, return -errno) {
535                 struct stat buf;
536                 int q;
537
538                 if (dot_or_dot_dot(de->d_name))
539                         continue;
540
541                 if (fstatat(dirfd(d), de->d_name, &buf, AT_SYMLINK_NOFOLLOW) < 0) {
542                         r = -errno;
543                         continue;
544                 }
545
546                 if (S_ISDIR(buf.st_mode)) {
547                         /*
548                          * Don't descend into directories on other file systems, if this is requested. We do a simple
549                          * .st_dev check here, which basically comes for free. Note that we do this check only on
550                          * directories, not other kind of file system objects, for two reason:
551                          *
552                          * • The kernel's overlayfs pseudo file system that overlays multiple real file systems
553                          *   propagates the .st_dev field of the file system a file originates from all the way up
554                          *   through the stack to stat(). It doesn't do that for directories however. This means that
555                          *   comparing .st_dev on non-directories suggests that they all are mount points. To avoid
556                          *   confusion we hence avoid relying on this check for regular files.
557                          *
558                          * • The main reason we do this check at all is to protect ourselves from bind mount cycles,
559                          *   where we really want to avoid descending down in all eternity. However the .st_dev check
560                          *   is usually not sufficient for this protection anyway, as bind mount cycles from the same
561                          *   file system onto itself can't be detected that way. (Note we also do a recursion depth
562                          *   check, which is probably the better protection in this regard, which is why
563                          *   COPY_SAME_MOUNT is optional).
564                          */
565
566                         if (FLAGS_SET(copy_flags, COPY_SAME_MOUNT)) {
567                                 if (buf.st_dev != original_device)
568                                         continue;
569
570                                 r = fd_is_mount_point(dirfd(d), de->d_name, 0);
571                                 if (r < 0)
572                                         return r;
573                                 if (r > 0)
574                                         continue;
575                         }
576
577                         q = fd_copy_directory(dirfd(d), de->d_name, &buf, fdt, de->d_name, original_device, depth_left-1, override_uid, override_gid, copy_flags);
578                 } else if (S_ISREG(buf.st_mode))
579                         q = fd_copy_regular(dirfd(d), de->d_name, &buf, fdt, de->d_name, override_uid, override_gid, copy_flags);
580                 else if (S_ISLNK(buf.st_mode))
581                         q = fd_copy_symlink(dirfd(d), de->d_name, &buf, fdt, de->d_name, override_uid, override_gid, copy_flags);
582                 else if (S_ISFIFO(buf.st_mode))
583                         q = fd_copy_fifo(dirfd(d), de->d_name, &buf, fdt, de->d_name, override_uid, override_gid, copy_flags);
584                 else if (S_ISBLK(buf.st_mode) || S_ISCHR(buf.st_mode) || S_ISSOCK(buf.st_mode))
585                         q = fd_copy_node(dirfd(d), de->d_name, &buf, fdt, de->d_name, override_uid, override_gid, copy_flags);
586                 else
587                         q = -EOPNOTSUPP;
588
589                 if (q == -EEXIST && (copy_flags & COPY_MERGE))
590                         q = 0;
591
592                 if (q < 0)
593                         r = q;
594         }
595
596         if (created) {
597                 struct timespec ut[2] = {
598                         st->st_atim,
599                         st->st_mtim
600                 };
601
602                 if (fchown(fdt,
603                            uid_is_valid(override_uid) ? override_uid : st->st_uid,
604                            gid_is_valid(override_gid) ? override_gid : st->st_gid) < 0)
605                         r = -errno;
606
607                 if (fchmod(fdt, st->st_mode & 07777) < 0)
608                         r = -errno;
609
610                 (void) copy_xattr(dirfd(d), fdt);
611                 (void) futimens(fdt, ut);
612         }
613
614         return r;
615 }
616
617 int copy_tree_at(int fdf, const char *from, int fdt, const char *to, uid_t override_uid, gid_t override_gid, CopyFlags copy_flags) {
618         struct stat st;
619
620         assert(from);
621         assert(to);
622
623         if (fstatat(fdf, from, &st, AT_SYMLINK_NOFOLLOW) < 0)
624                 return -errno;
625
626         if (S_ISREG(st.st_mode))
627                 return fd_copy_regular(fdf, from, &st, fdt, to, override_uid, override_gid, copy_flags);
628         else if (S_ISDIR(st.st_mode))
629                 return fd_copy_directory(fdf, from, &st, fdt, to, st.st_dev, COPY_DEPTH_MAX, override_uid, override_gid, copy_flags);
630         else if (S_ISLNK(st.st_mode))
631                 return fd_copy_symlink(fdf, from, &st, fdt, to, override_uid, override_gid, copy_flags);
632         else if (S_ISFIFO(st.st_mode))
633                 return fd_copy_fifo(fdf, from, &st, fdt, to, override_uid, override_gid, copy_flags);
634         else if (S_ISBLK(st.st_mode) || S_ISCHR(st.st_mode) || S_ISSOCK(st.st_mode))
635                 return fd_copy_node(fdf, from, &st, fdt, to, override_uid, override_gid, copy_flags);
636         else
637                 return -EOPNOTSUPP;
638 }
639
640 int copy_tree(const char *from, const char *to, uid_t override_uid, gid_t override_gid, CopyFlags copy_flags) {
641         return copy_tree_at(AT_FDCWD, from, AT_FDCWD, to, override_uid, override_gid, copy_flags);
642 }
643
644 int copy_directory_fd(int dirfd, const char *to, CopyFlags copy_flags) {
645         struct stat st;
646
647         assert(dirfd >= 0);
648         assert(to);
649
650         if (fstat(dirfd, &st) < 0)
651                 return -errno;
652
653         if (!S_ISDIR(st.st_mode))
654                 return -ENOTDIR;
655
656         return fd_copy_directory(dirfd, NULL, &st, AT_FDCWD, to, st.st_dev, COPY_DEPTH_MAX, UID_INVALID, GID_INVALID, copy_flags);
657 }
658
659 int copy_directory(const char *from, const char *to, CopyFlags copy_flags) {
660         struct stat st;
661
662         assert(from);
663         assert(to);
664
665         if (lstat(from, &st) < 0)
666                 return -errno;
667
668         if (!S_ISDIR(st.st_mode))
669                 return -ENOTDIR;
670
671         return fd_copy_directory(AT_FDCWD, from, &st, AT_FDCWD, to, st.st_dev, COPY_DEPTH_MAX, UID_INVALID, GID_INVALID, copy_flags);
672 }
673
674 int copy_file_fd(const char *from, int fdt, CopyFlags copy_flags) {
675         _cleanup_close_ int fdf = -1;
676         int r;
677
678         assert(from);
679         assert(fdt >= 0);
680
681         fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
682         if (fdf < 0)
683                 return -errno;
684
685         r = copy_bytes(fdf, fdt, (uint64_t) -1, copy_flags);
686
687         (void) copy_times(fdf, fdt);
688         (void) copy_xattr(fdf, fdt);
689
690         return r;
691 }
692
693 int copy_file(const char *from, const char *to, int flags, mode_t mode, unsigned chattr_flags, CopyFlags copy_flags) {
694         int fdt = -1, r;
695
696         assert(from);
697         assert(to);
698
699         RUN_WITH_UMASK(0000) {
700                 fdt = open(to, flags|O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode);
701                 if (fdt < 0)
702                         return -errno;
703         }
704
705         if (chattr_flags != 0)
706                 (void) chattr_fd(fdt, chattr_flags, (unsigned) -1);
707
708         r = copy_file_fd(from, fdt, copy_flags);
709         if (r < 0) {
710                 close(fdt);
711                 (void) unlink(to);
712                 return r;
713         }
714
715         if (close(fdt) < 0) {
716                 unlink_noerrno(to);
717                 return -errno;
718         }
719
720         return 0;
721 }
722
723 int copy_file_atomic(const char *from, const char *to, mode_t mode, unsigned chattr_flags, CopyFlags copy_flags) {
724         _cleanup_free_ char *t = NULL;
725         int r;
726
727         assert(from);
728         assert(to);
729
730         r = tempfn_random(to, NULL, &t);
731         if (r < 0)
732                 return r;
733
734         r = copy_file(from, t, O_NOFOLLOW|O_EXCL, mode, chattr_flags, copy_flags);
735         if (r < 0)
736                 return r;
737
738         if (copy_flags & COPY_REPLACE) {
739                 r = renameat(AT_FDCWD, t, AT_FDCWD, to);
740                 if (r < 0)
741                         r = -errno;
742         } else
743                 r = rename_noreplace(AT_FDCWD, t, AT_FDCWD, to);
744         if (r < 0) {
745                 (void) unlink(t);
746                 return r;
747         }
748
749         return 0;
750 }
751
752 int copy_times(int fdf, int fdt) {
753         struct timespec ut[2];
754         struct stat st;
755         usec_t crtime = 0;
756
757         assert(fdf >= 0);
758         assert(fdt >= 0);
759
760         if (fstat(fdf, &st) < 0)
761                 return -errno;
762
763         ut[0] = st.st_atim;
764         ut[1] = st.st_mtim;
765
766         if (futimens(fdt, ut) < 0)
767                 return -errno;
768
769         if (fd_getcrtime(fdf, &crtime) >= 0)
770                 (void) fd_setcrtime(fdt, crtime);
771
772         return 0;
773 }
774
775 int copy_xattr(int fdf, int fdt) {
776         _cleanup_free_ char *bufa = NULL, *bufb = NULL;
777         size_t sza = 100, szb = 100;
778         ssize_t n;
779         int ret = 0;
780         const char *p;
781
782         for (;;) {
783                 bufa = malloc(sza);
784                 if (!bufa)
785                         return -ENOMEM;
786
787                 n = flistxattr(fdf, bufa, sza);
788                 if (n == 0)
789                         return 0;
790                 if (n > 0)
791                         break;
792                 if (errno != ERANGE)
793                         return -errno;
794
795                 sza *= 2;
796
797                 bufa = mfree(bufa);
798         }
799
800         p = bufa;
801         while (n > 0) {
802                 size_t l;
803
804                 l = strlen(p);
805                 assert(l < (size_t) n);
806
807                 if (startswith(p, "user.")) {
808                         ssize_t m;
809
810                         if (!bufb) {
811                                 bufb = malloc(szb);
812                                 if (!bufb)
813                                         return -ENOMEM;
814                         }
815
816                         m = fgetxattr(fdf, p, bufb, szb);
817                         if (m < 0) {
818                                 if (errno == ERANGE) {
819                                         szb *= 2;
820                                         bufb = mfree(bufb);
821                                         continue;
822                                 }
823
824                                 return -errno;
825                         }
826
827                         if (fsetxattr(fdt, p, bufb, m, 0) < 0)
828                                 ret = -errno;
829                 }
830
831                 p += l + 1;
832                 n -= l + 1;
833         }
834
835         return ret;
836 }
837 #endif // 0