maint: update GCC version comment
[coreutils.git] / src / copy.c
blob12845eefd6b144bd5177289ef038ecaa31799eef
1 /* copy.c -- core functions for copying files and directories
2 Copyright (C) 1989-2024 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
17 /* Extracted from cp.c and librarified by Jim Meyering. */
19 #include <config.h>
20 #include <stdio.h>
21 #include <sys/ioctl.h>
22 #include <sys/types.h>
23 #include <selinux/selinux.h>
25 #if HAVE_HURD_H
26 # include <hurd.h>
27 #endif
28 #if HAVE_PRIV_H
29 # include <priv.h>
30 #endif
32 #include "system.h"
33 #include "acl.h"
34 #include "alignalloc.h"
35 #include "assure.h"
36 #include "backupfile.h"
37 #include "buffer-lcm.h"
38 #include "canonicalize.h"
39 #include "copy.h"
40 #include "cp-hash.h"
41 #include "fadvise.h"
42 #include "fcntl--.h"
43 #include "file-set.h"
44 #include "filemode.h"
45 #include "filenamecat.h"
46 #include "force-link.h"
47 #include "full-write.h"
48 #include "hash.h"
49 #include "hash-triple.h"
50 #include "ignore-value.h"
51 #include "ioblksize.h"
52 #include "quote.h"
53 #include "renameatu.h"
54 #include "root-uid.h"
55 #include "same.h"
56 #include "savedir.h"
57 #include "stat-size.h"
58 #include "stat-time.h"
59 #include "utimecmp.h"
60 #include "utimens.h"
61 #include "write-any-file.h"
62 #include "areadlink.h"
63 #include "yesno.h"
64 #include "selinux.h"
66 #ifndef USE_XATTR
67 # define USE_XATTR false
68 #endif
70 #if USE_XATTR
71 # include <attr/error_context.h>
72 # include <attr/libattr.h>
73 # include <stdarg.h>
74 # include "verror.h"
75 #endif
77 #if HAVE_LINUX_FALLOC_H
78 # include <linux/falloc.h>
79 #endif
81 /* See HAVE_FALLOCATE workaround when including this file. */
82 #ifdef HAVE_LINUX_FS_H
83 # include <linux/fs.h>
84 #endif
86 #if !defined FICLONE && defined __linux__
87 # define FICLONE _IOW (0x94, 9, int)
88 #endif
90 #if HAVE_FCLONEFILEAT && !USE_XATTR
91 # include <sys/clonefile.h>
92 #endif
94 #ifndef USE_ACL
95 # define USE_ACL 0
96 #endif
98 #define SAME_OWNER(A, B) ((A).st_uid == (B).st_uid)
99 #define SAME_GROUP(A, B) ((A).st_gid == (B).st_gid)
100 #define SAME_OWNER_AND_GROUP(A, B) (SAME_OWNER (A, B) && SAME_GROUP (A, B))
102 /* LINK_FOLLOWS_SYMLINKS is tri-state; if it is -1, we don't know
103 how link() behaves, so assume we can't hardlink symlinks in that case. */
104 #if (defined HAVE_LINKAT && ! LINKAT_SYMLINK_NOTSUP) || ! LINK_FOLLOWS_SYMLINKS
105 # define CAN_HARDLINK_SYMLINKS 1
106 #else
107 # define CAN_HARDLINK_SYMLINKS 0
108 #endif
110 struct dir_list
112 struct dir_list *parent;
113 ino_t ino;
114 dev_t dev;
117 /* Initial size of the cp.dest_info hash table. */
118 #define DEST_INFO_INITIAL_CAPACITY 61
120 static bool copy_internal (char const *src_name, char const *dst_name,
121 int dst_dirfd, char const *dst_relname,
122 int nonexistent_dst, struct stat const *parent,
123 struct dir_list *ancestors,
124 const struct cp_options *x,
125 bool command_line_arg,
126 bool *first_dir_created_per_command_line_arg,
127 bool *copy_into_self,
128 bool *rename_succeeded);
129 static bool owner_failure_ok (struct cp_options const *x);
131 /* Pointers to the file names: they're used in the diagnostic that is issued
132 when we detect the user is trying to copy a directory into itself. */
133 static char const *top_level_src_name;
134 static char const *top_level_dst_name;
136 enum copy_debug_val
138 COPY_DEBUG_UNKNOWN,
139 COPY_DEBUG_NO,
140 COPY_DEBUG_YES,
141 COPY_DEBUG_EXTERNAL,
142 COPY_DEBUG_EXTERNAL_INTERNAL,
143 COPY_DEBUG_AVOIDED,
144 COPY_DEBUG_UNSUPPORTED,
147 /* debug info about the last file copy. */
148 static struct copy_debug
150 enum copy_debug_val offload;
151 enum copy_debug_val reflink;
152 enum copy_debug_val sparse_detection;
153 } copy_debug;
155 static const char*
156 copy_debug_string (enum copy_debug_val debug_val)
158 switch (debug_val)
160 case COPY_DEBUG_NO: return "no";
161 case COPY_DEBUG_YES: return "yes";
162 case COPY_DEBUG_AVOIDED: return "avoided";
163 case COPY_DEBUG_UNSUPPORTED: return "unsupported";
164 default: return "unknown";
168 static const char*
169 copy_debug_sparse_string (enum copy_debug_val debug_val)
171 switch (debug_val)
173 case COPY_DEBUG_NO: return "no";
174 case COPY_DEBUG_YES: return "zeros";
175 case COPY_DEBUG_EXTERNAL: return "SEEK_HOLE";
176 case COPY_DEBUG_EXTERNAL_INTERNAL: return "SEEK_HOLE + zeros";
177 default: return "unknown";
181 /* Print --debug output on standard output. */
182 static void
183 emit_debug (const struct cp_options *x)
185 if (! x->hard_link && ! x->symbolic_link && x->data_copy_required)
186 printf ("copy offload: %s, reflink: %s, sparse detection: %s\n",
187 copy_debug_string (copy_debug.offload),
188 copy_debug_string (copy_debug.reflink),
189 copy_debug_sparse_string (copy_debug.sparse_detection));
192 #ifndef DEV_FD_MIGHT_BE_CHR
193 # define DEV_FD_MIGHT_BE_CHR false
194 #endif
196 /* Act like fstat (DIRFD, FILENAME, ST, FLAGS), except when following
197 symbolic links on Solaris-like systems, treat any character-special
198 device like /dev/fd/0 as if it were the file it is open on. */
199 static int
200 follow_fstatat (int dirfd, char const *filename, struct stat *st, int flags)
202 int result = fstatat (dirfd, filename, st, flags);
204 if (DEV_FD_MIGHT_BE_CHR && result == 0 && !(flags & AT_SYMLINK_NOFOLLOW)
205 && S_ISCHR (st->st_mode))
207 static dev_t stdin_rdev;
208 static signed char stdin_rdev_status;
209 if (stdin_rdev_status == 0)
211 struct stat stdin_st;
212 if (stat ("/dev/stdin", &stdin_st) == 0 && S_ISCHR (stdin_st.st_mode)
213 && minor (stdin_st.st_rdev) == STDIN_FILENO)
215 stdin_rdev = stdin_st.st_rdev;
216 stdin_rdev_status = 1;
218 else
219 stdin_rdev_status = -1;
221 if (0 < stdin_rdev_status && major (stdin_rdev) == major (st->st_rdev))
222 result = fstat (minor (st->st_rdev), st);
225 return result;
228 /* Attempt to punch a hole to avoid any permanent
229 speculative preallocation on file systems such as XFS.
230 Return values as per fallocate(2) except ENOSYS etc. are ignored. */
232 static int
233 punch_hole (int fd, off_t offset, off_t length)
235 int ret = 0;
236 /* +0 is to work around older <linux/fs.h> defining HAVE_FALLOCATE to empty. */
237 #if HAVE_FALLOCATE + 0
238 # if defined FALLOC_FL_PUNCH_HOLE && defined FALLOC_FL_KEEP_SIZE
239 ret = fallocate (fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
240 offset, length);
241 if (ret < 0 && (is_ENOTSUP (errno) || errno == ENOSYS))
242 ret = 0;
243 # endif
244 #endif
245 return ret;
248 /* Create a hole at the end of a file,
249 avoiding preallocation if requested. */
251 static bool
252 create_hole (int fd, char const *name, bool punch_holes, off_t size)
254 off_t file_end = lseek (fd, size, SEEK_CUR);
256 if (file_end < 0)
258 error (0, errno, _("cannot lseek %s"), quoteaf (name));
259 return false;
262 /* Some file systems (like XFS) preallocate when write extending a file.
263 I.e., a previous write() may have preallocated extra space
264 that the seek above will not discard. A subsequent write() could
265 then make this allocation permanent. */
266 if (punch_holes && punch_hole (fd, file_end - size, size) < 0)
268 error (0, errno, _("error deallocating %s"), quoteaf (name));
269 return false;
272 return true;
276 /* Whether an errno value ERR, set by FICLONE or copy_file_range,
277 indicates that the copying operation has terminally failed, even
278 though it was invoked correctly (so that, e.g, EBADF cannot occur)
279 and even though !is_CLONENOTSUP (ERR). */
281 static bool
282 is_terminal_error (int err)
284 return err == EIO || err == ENOMEM || err == ENOSPC || err == EDQUOT;
287 /* Similarly, whether ERR indicates that the copying operation is not
288 supported or allowed for this file or process, even though the
289 operation was invoked correctly. */
291 static bool
292 is_CLONENOTSUP (int err)
294 return err == ENOSYS || err == ENOTTY || is_ENOTSUP (err)
295 || err == EINVAL || err == EBADF
296 || err == EXDEV || err == ETXTBSY
297 || err == EPERM || err == EACCES;
301 /* Copy the regular file open on SRC_FD/SRC_NAME to DST_FD/DST_NAME,
302 honoring the MAKE_HOLES setting and using the BUF_SIZE-byte buffer
303 *ABUF for temporary storage, allocating it lazily if *ABUF is null.
304 Copy no more than MAX_N_READ bytes.
305 Return true upon successful completion;
306 print a diagnostic and return false upon error.
307 Note that for best results, BUF should be "well"-aligned.
308 Set *LAST_WRITE_MADE_HOLE to true if the final operation on
309 DEST_FD introduced a hole. Set *TOTAL_N_READ to the number of
310 bytes read. */
311 static bool
312 sparse_copy (int src_fd, int dest_fd, char **abuf, size_t buf_size,
313 size_t hole_size, bool punch_holes, bool allow_reflink,
314 char const *src_name, char const *dst_name,
315 uintmax_t max_n_read, off_t *total_n_read,
316 bool *last_write_made_hole)
318 *last_write_made_hole = false;
319 *total_n_read = 0;
321 if (copy_debug.sparse_detection == COPY_DEBUG_UNKNOWN)
322 copy_debug.sparse_detection = hole_size ? COPY_DEBUG_YES : COPY_DEBUG_NO;
323 else if (hole_size && copy_debug.sparse_detection == COPY_DEBUG_EXTERNAL)
324 copy_debug.sparse_detection = COPY_DEBUG_EXTERNAL_INTERNAL;
326 /* If not looking for holes, use copy_file_range if functional,
327 but don't use if reflink disallowed as that may be implicit. */
328 if (!hole_size && allow_reflink)
329 while (max_n_read)
331 /* Copy at most COPY_MAX bytes at a time; this is min
332 (SSIZE_MAX, SIZE_MAX) truncated to a value that is
333 surely aligned well. */
334 ssize_t copy_max = MIN (SSIZE_MAX, SIZE_MAX) >> 30 << 30;
335 ssize_t n_copied = copy_file_range (src_fd, nullptr, dest_fd, nullptr,
336 MIN (max_n_read, copy_max), 0);
337 if (n_copied == 0)
339 /* copy_file_range incorrectly returns 0 when reading from
340 the proc file system on the Linux kernel through at
341 least 5.6.19 (2020), so fall back on 'read' if the
342 input file seems empty. */
343 if (*total_n_read == 0)
344 break;
345 copy_debug.offload = COPY_DEBUG_YES;
346 return true;
348 if (n_copied < 0)
350 copy_debug.offload = COPY_DEBUG_UNSUPPORTED;
352 /* Consider operation unsupported only if no data copied.
353 For example, EPERM could occur if copy_file_range not enabled
354 in seccomp filters, so retry with a standard copy. EPERM can
355 also occur for immutable files, but that would only be in the
356 edge case where the file is made immutable after creating,
357 in which case the (more accurate) error is still shown. */
358 if (*total_n_read == 0 && is_CLONENOTSUP (errno))
359 break;
361 /* ENOENT was seen sometimes across CIFS shares, resulting in
362 no data being copied, but subsequent standard copies succeed. */
363 if (*total_n_read == 0 && errno == ENOENT)
364 break;
366 if (errno == EINTR)
367 n_copied = 0;
368 else
370 error (0, errno, _("error copying %s to %s"),
371 quoteaf_n (0, src_name), quoteaf_n (1, dst_name));
372 return false;
375 copy_debug.offload = COPY_DEBUG_YES;
376 max_n_read -= n_copied;
377 *total_n_read += n_copied;
379 else
380 copy_debug.offload = COPY_DEBUG_AVOIDED;
383 bool make_hole = false;
384 off_t psize = 0;
386 while (max_n_read)
388 if (!*abuf)
389 *abuf = xalignalloc (getpagesize (), buf_size);
390 char *buf = *abuf;
391 ssize_t n_read = read (src_fd, buf, MIN (max_n_read, buf_size));
392 if (n_read < 0)
394 if (errno == EINTR)
395 continue;
396 error (0, errno, _("error reading %s"), quoteaf (src_name));
397 return false;
399 if (n_read == 0)
400 break;
401 max_n_read -= n_read;
402 *total_n_read += n_read;
404 /* Loop over the input buffer in chunks of hole_size. */
405 size_t csize = hole_size ? hole_size : buf_size;
406 char *cbuf = buf;
407 char *pbuf = buf;
409 while (n_read)
411 bool prev_hole = make_hole;
412 csize = MIN (csize, n_read);
414 if (hole_size && csize)
415 make_hole = is_nul (cbuf, csize);
417 bool transition = (make_hole != prev_hole) && psize;
418 bool last_chunk = (n_read == csize && ! make_hole) || ! csize;
420 if (transition || last_chunk)
422 if (! transition)
423 psize += csize;
425 if (! prev_hole)
427 if (full_write (dest_fd, pbuf, psize) != psize)
429 error (0, errno, _("error writing %s"),
430 quoteaf (dst_name));
431 return false;
434 else
436 if (! create_hole (dest_fd, dst_name, punch_holes, psize))
437 return false;
440 pbuf = cbuf;
441 psize = csize;
443 if (last_chunk)
445 if (! csize)
446 n_read = 0; /* Finished processing buffer. */
448 if (transition)
449 csize = 0; /* Loop again to deal with last chunk. */
450 else
451 psize = 0; /* Reset for next read loop. */
454 else /* Coalesce writes/seeks. */
456 if (ckd_add (&psize, psize, csize))
458 error (0, 0, _("overflow reading %s"), quoteaf (src_name));
459 return false;
463 n_read -= csize;
464 cbuf += csize;
467 *last_write_made_hole = make_hole;
469 /* It's tempting to break early here upon a short read from
470 a regular file. That would save the final read syscall
471 for each file. Unfortunately that doesn't work for
472 certain files in /proc or /sys with linux kernels. */
475 /* Ensure a trailing hole is created, so that subsequent
476 calls of sparse_copy() start at the correct offset. */
477 if (make_hole && ! create_hole (dest_fd, dst_name, punch_holes, psize))
478 return false;
479 else
480 return true;
483 /* Perform the O(1) btrfs clone operation, if possible.
484 Upon success, return 0. Otherwise, return -1 and set errno. */
485 static inline int
486 clone_file (int dest_fd, int src_fd)
488 #ifdef FICLONE
489 return ioctl (dest_fd, FICLONE, src_fd);
490 #else
491 (void) dest_fd;
492 (void) src_fd;
493 errno = ENOTSUP;
494 return -1;
495 #endif
498 /* Write N_BYTES zero bytes to file descriptor FD. Return true if successful.
499 Upon write failure, set errno and return false. */
500 static bool
501 write_zeros (int fd, off_t n_bytes)
503 static char *zeros;
504 static size_t nz = IO_BUFSIZE;
506 /* Attempt to use a relatively large calloc'd source buffer for
507 efficiency, but if that allocation fails, resort to a smaller
508 statically allocated one. */
509 if (zeros == nullptr)
511 static char fallback[1024];
512 zeros = calloc (nz, 1);
513 if (zeros == nullptr)
515 zeros = fallback;
516 nz = sizeof fallback;
520 while (n_bytes)
522 size_t n = MIN (nz, n_bytes);
523 if ((full_write (fd, zeros, n)) != n)
524 return false;
525 n_bytes -= n;
528 return true;
531 #ifdef SEEK_HOLE
532 /* Perform an efficient extent copy, if possible. This avoids
533 the overhead of detecting holes in hole-introducing/preserving
534 copy, and thus makes copying sparse files much more efficient.
535 Copy from SRC_FD to DEST_FD, using *ABUF (of size BUF_SIZE) for a buffer.
536 Allocate *ABUF lazily if *ABUF is null.
537 Look for holes of size HOLE_SIZE in the input.
538 The input file is of size SRC_TOTAL_SIZE.
539 Use SPARSE_MODE to determine whether to create holes in the output.
540 SRC_NAME and DST_NAME are the input and output file names.
541 Return true if successful, false (with a diagnostic) otherwise. */
543 static bool
544 lseek_copy (int src_fd, int dest_fd, char **abuf, size_t buf_size,
545 size_t hole_size, off_t ext_start, off_t src_total_size,
546 enum Sparse_type sparse_mode,
547 bool allow_reflink,
548 char const *src_name, char const *dst_name)
550 off_t last_ext_start = 0;
551 off_t last_ext_len = 0;
552 off_t dest_pos = 0;
553 bool wrote_hole_at_eof = true;
555 copy_debug.sparse_detection = COPY_DEBUG_EXTERNAL;
557 while (0 <= ext_start)
559 off_t ext_end = lseek (src_fd, ext_start, SEEK_HOLE);
560 if (ext_end < 0)
562 if (errno != ENXIO)
563 goto cannot_lseek;
564 ext_end = src_total_size;
565 if (ext_end <= ext_start)
567 /* The input file grew; get its current size. */
568 src_total_size = lseek (src_fd, 0, SEEK_END);
569 if (src_total_size < 0)
570 goto cannot_lseek;
572 /* If the input file shrank after growing, stop copying. */
573 if (src_total_size <= ext_start)
574 break;
576 ext_end = src_total_size;
579 /* If the input file must have grown, increase its measured size. */
580 if (src_total_size < ext_end)
581 src_total_size = ext_end;
583 if (lseek (src_fd, ext_start, SEEK_SET) < 0)
584 goto cannot_lseek;
586 wrote_hole_at_eof = false;
587 off_t ext_hole_size = ext_start - last_ext_start - last_ext_len;
589 if (ext_hole_size)
591 if (sparse_mode != SPARSE_NEVER)
593 if (! create_hole (dest_fd, dst_name,
594 sparse_mode == SPARSE_ALWAYS,
595 ext_hole_size))
596 return false;
597 wrote_hole_at_eof = true;
599 else
601 /* When not inducing holes and when there is a hole between
602 the end of the previous extent and the beginning of the
603 current one, write zeros to the destination file. */
604 if (! write_zeros (dest_fd, ext_hole_size))
606 error (0, errno, _("%s: write failed"),
607 quotef (dst_name));
608 return false;
613 off_t ext_len = ext_end - ext_start;
614 last_ext_start = ext_start;
615 last_ext_len = ext_len;
617 /* Copy this extent, looking for further opportunities to not
618 bother to write zeros if --sparse=always, since SEEK_HOLE
619 is conservative and may miss some holes. */
620 off_t n_read;
621 bool read_hole;
622 if ( ! sparse_copy (src_fd, dest_fd, abuf, buf_size,
623 sparse_mode != SPARSE_ALWAYS ? 0 : hole_size,
624 true, allow_reflink, src_name, dst_name,
625 ext_len, &n_read, &read_hole))
626 return false;
628 dest_pos = ext_start + n_read;
629 if (n_read)
630 wrote_hole_at_eof = read_hole;
631 if (n_read < ext_len)
633 /* The input file shrank. */
634 src_total_size = dest_pos;
635 break;
638 ext_start = lseek (src_fd, dest_pos, SEEK_DATA);
639 if (ext_start < 0 && errno != ENXIO)
640 goto cannot_lseek;
643 /* When the source file ends with a hole, we have to do a little more work,
644 since the above copied only up to and including the final extent.
645 In order to complete the copy, we may have to insert a hole or write
646 zeros in the destination corresponding to the source file's hole-at-EOF.
648 In addition, if the final extent was a block of zeros at EOF and we've
649 just converted them to a hole in the destination, we must call ftruncate
650 here in order to record the proper length in the destination. */
651 if ((dest_pos < src_total_size || wrote_hole_at_eof)
652 && ! (sparse_mode == SPARSE_NEVER
653 ? write_zeros (dest_fd, src_total_size - dest_pos)
654 : ftruncate (dest_fd, src_total_size) == 0))
656 error (0, errno, _("failed to extend %s"), quoteaf (dst_name));
657 return false;
660 if (sparse_mode == SPARSE_ALWAYS && dest_pos < src_total_size
661 && punch_hole (dest_fd, dest_pos, src_total_size - dest_pos) < 0)
663 error (0, errno, _("error deallocating %s"), quoteaf (dst_name));
664 return false;
667 return true;
669 cannot_lseek:
670 error (0, errno, _("cannot lseek %s"), quoteaf (src_name));
671 return false;
673 #endif
675 /* FIXME: describe */
676 /* FIXME: rewrite this to use a hash table so we avoid the quadratic
677 performance hit that's probably noticeable only on trees deeper
678 than a few hundred levels. See use of active_dir_map in remove.c */
680 ATTRIBUTE_PURE
681 static bool
682 is_ancestor (const struct stat *sb, const struct dir_list *ancestors)
684 while (ancestors != 0)
686 if (ancestors->ino == sb->st_ino && ancestors->dev == sb->st_dev)
687 return true;
688 ancestors = ancestors->parent;
690 return false;
693 static bool
694 errno_unsupported (int err)
696 return err == ENOTSUP || err == ENODATA;
699 #if USE_XATTR
700 ATTRIBUTE_FORMAT ((printf, 2, 3))
701 static void
702 copy_attr_error (MAYBE_UNUSED struct error_context *ctx,
703 char const *fmt, ...)
705 if (!errno_unsupported (errno))
707 int err = errno;
708 va_list ap;
710 /* use verror module to print error message */
711 va_start (ap, fmt);
712 verror (0, err, fmt, ap);
713 va_end (ap);
717 ATTRIBUTE_FORMAT ((printf, 2, 3))
718 static void
719 copy_attr_allerror (MAYBE_UNUSED struct error_context *ctx,
720 char const *fmt, ...)
722 int err = errno;
723 va_list ap;
725 /* use verror module to print error message */
726 va_start (ap, fmt);
727 verror (0, err, fmt, ap);
728 va_end (ap);
731 static char const *
732 copy_attr_quote (MAYBE_UNUSED struct error_context *ctx, char const *str)
734 return quoteaf (str);
737 static void
738 copy_attr_free (MAYBE_UNUSED struct error_context *ctx,
739 MAYBE_UNUSED char const *str)
743 /* Exclude SELinux extended attributes that are otherwise handled,
744 and are problematic to copy again. Also honor attributes
745 configured for exclusion in /etc/xattr.conf.
746 FIXME: Should we handle POSIX ACLs similarly?
747 Return zero to skip. */
748 static int
749 check_selinux_attr (char const *name, struct error_context *ctx)
751 return STRNCMP_LIT (name, "security.selinux")
752 && attr_copy_check_permissions (name, ctx);
755 /* If positive SRC_FD and DST_FD descriptors are passed,
756 then copy by fd, otherwise copy by name. */
758 static bool
759 copy_attr (char const *src_path, int src_fd,
760 char const *dst_path, int dst_fd, struct cp_options const *x)
762 bool all_errors = (!x->data_copy_required || x->require_preserve_xattr);
763 bool some_errors = (!all_errors && !x->reduce_diagnostics);
764 int (*check) (char const *, struct error_context *)
765 = (x->preserve_security_context || x->set_security_context
766 ? check_selinux_attr : nullptr);
768 # if 4 < __GNUC__ + (8 <= __GNUC_MINOR__)
769 /* Pacify gcc -Wsuggest-attribute=format through at least GCC 13.2.1. */
770 # pragma GCC diagnostic push
771 # pragma GCC diagnostic ignored "-Wsuggest-attribute=format"
772 # endif
773 struct error_context *ctx
774 = (all_errors || some_errors
775 ? (&(struct error_context) {
776 .error = all_errors ? copy_attr_allerror : copy_attr_error,
777 .quote = copy_attr_quote,
778 .quote_free = copy_attr_free
780 : nullptr);
781 # if 4 < __GNUC__ + (8 <= __GNUC_MINOR__)
782 # pragma GCC diagnostic pop
783 # endif
785 return ! (0 <= src_fd && 0 <= dst_fd
786 ? attr_copy_fd (src_path, src_fd, dst_path, dst_fd, check, ctx)
787 : attr_copy_file (src_path, dst_path, check, ctx));
789 #else /* USE_XATTR */
791 static bool
792 copy_attr (MAYBE_UNUSED char const *src_path,
793 MAYBE_UNUSED int src_fd,
794 MAYBE_UNUSED char const *dst_path,
795 MAYBE_UNUSED int dst_fd,
796 MAYBE_UNUSED struct cp_options const *x)
798 return true;
800 #endif /* USE_XATTR */
802 /* Read the contents of the directory SRC_NAME_IN, and recursively
803 copy the contents to DST_NAME_IN aka DST_DIRFD+DST_RELNAME_IN.
804 NEW_DST is true if DST_NAME_IN is a directory
805 that was created previously in the recursion.
806 SRC_SB and ANCESTORS describe SRC_NAME_IN.
807 Set *COPY_INTO_SELF if SRC_NAME_IN is a parent of
808 (or the same as) DST_NAME_IN; otherwise, clear it.
809 Propagate *FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG from
810 caller to each invocation of copy_internal. Be careful to
811 pass the address of a temporary, and to update
812 *FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG only upon completion.
813 Return true if successful. */
815 static bool
816 copy_dir (char const *src_name_in, char const *dst_name_in,
817 int dst_dirfd, char const *dst_relname_in, bool new_dst,
818 const struct stat *src_sb, struct dir_list *ancestors,
819 const struct cp_options *x,
820 bool *first_dir_created_per_command_line_arg,
821 bool *copy_into_self)
823 char *name_space;
824 char *namep;
825 struct cp_options non_command_line_options = *x;
826 bool ok = true;
828 name_space = savedir (src_name_in, SAVEDIR_SORT_FASTREAD);
829 if (name_space == nullptr)
831 /* This diagnostic is a bit vague because savedir can fail in
832 several different ways. */
833 error (0, errno, _("cannot access %s"), quoteaf (src_name_in));
834 return false;
837 /* For cp's -H option, dereference command line arguments, but do not
838 dereference symlinks that are found via recursive traversal. */
839 if (x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
840 non_command_line_options.dereference = DEREF_NEVER;
842 bool new_first_dir_created = false;
843 namep = name_space;
844 while (*namep != '\0')
846 bool local_copy_into_self;
847 char *src_name = file_name_concat (src_name_in, namep, nullptr);
848 char *dst_name = file_name_concat (dst_name_in, namep, nullptr);
849 bool first_dir_created = *first_dir_created_per_command_line_arg;
850 bool rename_succeeded;
852 ok &= copy_internal (src_name, dst_name, dst_dirfd,
853 dst_name + (dst_relname_in - dst_name_in),
854 new_dst, src_sb,
855 ancestors, &non_command_line_options, false,
856 &first_dir_created,
857 &local_copy_into_self, &rename_succeeded);
858 *copy_into_self |= local_copy_into_self;
860 free (dst_name);
861 free (src_name);
863 /* If we're copying into self, there's no point in continuing,
864 and in fact, that would even infloop, now that we record only
865 the first created directory per command line argument. */
866 if (local_copy_into_self)
867 break;
869 new_first_dir_created |= first_dir_created;
870 namep += strlen (namep) + 1;
872 free (name_space);
873 *first_dir_created_per_command_line_arg = new_first_dir_created;
875 return ok;
878 /* Change the file mode bits of the file identified by DESC or
879 DIRFD+NAME to MODE. Use DESC if DESC is valid and fchmod is
880 available, DIRFD+NAME otherwise. */
882 static int
883 fchmod_or_lchmod (int desc, int dirfd, char const *name, mode_t mode)
885 #if HAVE_FCHMOD
886 if (0 <= desc)
887 return fchmod (desc, mode);
888 #endif
889 return lchmodat (dirfd, name, mode);
892 /* Change the ownership of the file identified by DESC or
893 DIRFD+NAME to UID+GID. Use DESC if DESC is valid and fchown is
894 available, DIRFD+NAME otherwise. */
896 static int
897 fchown_or_lchown (int desc, int dirfd, char const *name, uid_t uid, gid_t gid)
899 #if HAVE_FCHOWN
900 if (0 <= desc)
901 return fchown (desc, uid, gid);
902 #endif
903 return lchownat (dirfd, name, uid, gid);
906 /* Set the owner and owning group of DEST_DESC to the st_uid and
907 st_gid fields of SRC_SB. If DEST_DESC is undefined (-1), set
908 the owner and owning group of DST_NAME aka DST_DIRFD+DST_RELNAME
909 instead; for safety prefer lchownat since no
910 symbolic links should be involved. DEST_DESC must
911 refer to the same file as DST_NAME if defined.
912 Upon failure to set both UID and GID, try to set only the GID.
913 NEW_DST is true if the file was newly created; otherwise,
914 DST_SB is the status of the destination.
915 Return 1 if the initial syscall succeeds, 0 if it fails but it's OK
916 not to preserve ownership, -1 otherwise. */
918 static int
919 set_owner (const struct cp_options *x, char const *dst_name,
920 int dst_dirfd, char const *dst_relname, int dest_desc,
921 struct stat const *src_sb, bool new_dst,
922 struct stat const *dst_sb)
924 uid_t uid = src_sb->st_uid;
925 gid_t gid = src_sb->st_gid;
927 /* Naively changing the ownership of an already-existing file before
928 changing its permissions would create a window of vulnerability if
929 the file's old permissions are too generous for the new owner and
930 group. Avoid the window by first changing to a restrictive
931 temporary mode if necessary. */
933 if (!new_dst && (x->preserve_mode || x->move_mode || x->set_mode))
935 mode_t old_mode = dst_sb->st_mode;
936 mode_t new_mode =
937 (x->preserve_mode || x->move_mode ? src_sb->st_mode : x->mode);
938 mode_t restrictive_temp_mode = old_mode & new_mode & S_IRWXU;
940 if ((USE_ACL
941 || (old_mode & CHMOD_MODE_BITS
942 & (~new_mode | S_ISUID | S_ISGID | S_ISVTX)))
943 && qset_acl (dst_name, dest_desc, restrictive_temp_mode) != 0)
945 if (! owner_failure_ok (x))
946 error (0, errno, _("clearing permissions for %s"),
947 quoteaf (dst_name));
948 return -x->require_preserve;
952 if (fchown_or_lchown (dest_desc, dst_dirfd, dst_relname, uid, gid) == 0)
953 return 1;
955 /* The ownership change failed. If the failure merely means we lack
956 privileges to change owner+group, try to change just the group
957 and ignore any failure of this. Otherwise, report an error. */
958 if (chown_failure_ok (x))
959 ignore_value (fchown_or_lchown (dest_desc, dst_dirfd, dst_relname,
960 -1, gid));
961 else
963 error (0, errno, _("failed to preserve ownership for %s"),
964 quoteaf (dst_name));
965 if (x->require_preserve)
966 return -1;
969 return 0;
972 /* Set the st_author field of DEST_DESC to the st_author field of
973 SRC_SB. If DEST_DESC is undefined (-1), set the st_author field
974 of DST_NAME instead. DEST_DESC must refer to the same file as
975 DST_NAME if defined. */
977 static void
978 set_author (char const *dst_name, int dest_desc, const struct stat *src_sb)
980 #if HAVE_STRUCT_STAT_ST_AUTHOR
981 /* FIXME: Modify the following code so that it does not
982 follow symbolic links. */
984 /* Preserve the st_author field. */
985 file_t file = (dest_desc < 0
986 ? file_name_lookup (dst_name, 0, 0)
987 : getdport (dest_desc));
988 if (file == MACH_PORT_NULL)
989 error (0, errno, _("failed to lookup file %s"), quoteaf (dst_name));
990 else
992 error_t err = file_chauthor (file, src_sb->st_author);
993 if (err)
994 error (0, err, _("failed to preserve authorship for %s"),
995 quoteaf (dst_name));
996 mach_port_deallocate (mach_task_self (), file);
998 #else
999 (void) dst_name;
1000 (void) dest_desc;
1001 (void) src_sb;
1002 #endif
1005 /* Set the default security context for the process. New files will
1006 have this security context set. Also existing files can have their
1007 context adjusted based on this process context, by
1008 set_file_security_ctx() called with PROCESS_LOCAL=true.
1009 This should be called before files are created so there is no race
1010 where a file may be present without an appropriate security context.
1011 Based on CP_OPTIONS, diagnose warnings and fail when appropriate.
1012 Return FALSE on failure, TRUE on success. */
1014 bool
1015 set_process_security_ctx (char const *src_name, char const *dst_name,
1016 mode_t mode, bool new_dst, const struct cp_options *x)
1018 if (x->preserve_security_context)
1020 /* Set the default context for the process to match the source. */
1021 bool all_errors = !x->data_copy_required || x->require_preserve_context;
1022 bool some_errors = !all_errors && !x->reduce_diagnostics;
1023 char *con_raw;
1025 if (0 <= lgetfilecon_raw (src_name, &con_raw))
1027 if (setfscreatecon_raw (con_raw) < 0)
1029 if (all_errors || (some_errors && !errno_unsupported (errno)))
1030 error (0, errno,
1031 _("failed to set default file creation context to %s"),
1032 quote (con_raw));
1033 if (x->require_preserve_context)
1035 freecon (con_raw);
1036 return false;
1039 freecon (con_raw);
1041 else
1043 if (all_errors || (some_errors && !errno_unsupported (errno)))
1045 error (0, errno,
1046 _("failed to get security context of %s"),
1047 quoteaf (src_name));
1049 if (x->require_preserve_context)
1050 return false;
1053 else if (x->set_security_context)
1055 /* With -Z, adjust the default context for the process
1056 to have the type component adjusted as per the destination path. */
1057 if (new_dst && defaultcon (x->set_security_context, dst_name, mode) < 0
1058 && ! ignorable_ctx_err (errno))
1060 error (0, errno,
1061 _("failed to set default file creation context for %s"),
1062 quoteaf (dst_name));
1066 return true;
1069 /* Reset the security context of DST_NAME, to that already set
1070 as the process default if !X->set_security_context. Otherwise
1071 adjust the type component of DST_NAME's security context as
1072 per the system default for that path. Issue warnings upon
1073 failure, when allowed by various settings in X.
1074 Return false on failure, true on success. */
1076 bool
1077 set_file_security_ctx (char const *dst_name,
1078 bool recurse, const struct cp_options *x)
1080 bool all_errors = (!x->data_copy_required
1081 || x->require_preserve_context);
1082 bool some_errors = !all_errors && !x->reduce_diagnostics;
1084 if (! restorecon (x->set_security_context, dst_name, recurse))
1086 if (all_errors || (some_errors && !errno_unsupported (errno)))
1087 error (0, errno, _("failed to set the security context of %s"),
1088 quoteaf_n (0, dst_name));
1089 return false;
1092 return true;
1095 #ifndef HAVE_STRUCT_STAT_ST_BLOCKS
1096 # define HAVE_STRUCT_STAT_ST_BLOCKS 0
1097 #endif
1099 /* Type of scan being done on the input when looking for sparseness. */
1100 enum scantype
1102 /* An error was found when determining scantype. */
1103 ERROR_SCANTYPE,
1105 /* No fancy scanning; just read and write. */
1106 PLAIN_SCANTYPE,
1108 /* Read and examine data looking for zero blocks; useful when
1109 attempting to create sparse output. */
1110 ZERO_SCANTYPE,
1112 /* lseek information is available. */
1113 LSEEK_SCANTYPE,
1116 /* Result of infer_scantype. */
1117 union scan_inference
1119 /* Used if infer_scantype returns LSEEK_SCANTYPE. This is the
1120 offset of the first data block, or -1 if the file has no data. */
1121 off_t ext_start;
1124 /* Return how to scan a file with descriptor FD and stat buffer SB.
1125 *SCAN_INFERENCE is set to a valid value if returning LSEEK_SCANTYPE. */
1126 static enum scantype
1127 infer_scantype (int fd, struct stat const *sb,
1128 union scan_inference *scan_inference)
1130 scan_inference->ext_start = -1; /* avoid -Wmaybe-uninitialized */
1132 /* Only attempt SEEK_HOLE if this heuristic
1133 suggests the file is sparse. */
1134 if (! (HAVE_STRUCT_STAT_ST_BLOCKS
1135 && S_ISREG (sb->st_mode)
1136 && STP_NBLOCKS (sb) < sb->st_size / ST_NBLOCKSIZE))
1137 return PLAIN_SCANTYPE;
1139 #ifdef SEEK_HOLE
1140 off_t ext_start = lseek (fd, 0, SEEK_DATA);
1141 if (0 <= ext_start || errno == ENXIO)
1143 scan_inference->ext_start = ext_start;
1144 return LSEEK_SCANTYPE;
1146 else if (errno != EINVAL && !is_ENOTSUP (errno))
1147 return ERROR_SCANTYPE;
1148 #endif
1150 return ZERO_SCANTYPE;
1153 #if HAVE_FCLONEFILEAT && !USE_XATTR
1154 # include <sys/acl.h>
1155 /* Return true if FD has a nontrivial ACL. */
1156 static bool
1157 fd_has_acl (int fd)
1159 /* Every platform with fclonefileat (macOS 10.12 or later) also has
1160 acl_get_fd_np. */
1161 bool has_acl = false;
1162 acl_t acl = acl_get_fd_np (fd, ACL_TYPE_EXTENDED);
1163 if (acl)
1165 acl_entry_t ace;
1166 has_acl = 0 <= acl_get_entry (acl, ACL_FIRST_ENTRY, &ace);
1167 acl_free (acl);
1169 return has_acl;
1171 #endif
1173 /* Handle failure from FICLONE or fclonefileat.
1174 Return FALSE if it's a terminal failure for this file. */
1176 static bool
1177 handle_clone_fail (int dst_dirfd, char const *dst_relname,
1178 char const *src_name, char const *dst_name,
1179 int dest_desc, bool new_dst, enum Reflink_type reflink_mode)
1181 /* When the clone operation fails, report failure only with errno values
1182 known to mean trouble when the clone is supported and called properly.
1183 Do not report failure merely because !is_CLONENOTSUP (errno),
1184 as systems may yield oddball errno values here with FICLONE,
1185 and is_CLONENOTSUP is not appropriate for fclonefileat. */
1186 bool report_failure = is_terminal_error (errno);
1188 if (reflink_mode == REFLINK_ALWAYS || report_failure)
1189 error (0, errno, _("failed to clone %s from %s"),
1190 quoteaf_n (0, dst_name), quoteaf_n (1, src_name));
1192 /* Remove the destination if cp --reflink=always created it
1193 but cloned no data. */
1194 if (new_dst /* currently not for fclonefileat(). */
1195 && reflink_mode == REFLINK_ALWAYS
1196 && ((! report_failure) || lseek (dest_desc, 0, SEEK_END) == 0)
1197 && unlinkat (dst_dirfd, dst_relname, 0) != 0 && errno != ENOENT)
1198 error (0, errno, _("cannot remove %s"), quoteaf (dst_name));
1200 if (! report_failure)
1201 copy_debug.reflink = COPY_DEBUG_UNSUPPORTED;
1203 if (reflink_mode == REFLINK_ALWAYS || report_failure)
1204 return false;
1206 return true;
1210 /* Copy a regular file from SRC_NAME to DST_NAME aka DST_DIRFD+DST_RELNAME.
1211 If the source file contains holes, copies holes and blocks of zeros
1212 in the source file as holes in the destination file.
1213 (Holes are read as zeroes by the 'read' system call.)
1214 When creating the destination, use DST_MODE & ~OMITTED_PERMISSIONS
1215 as the third argument in the call to open, adding
1216 OMITTED_PERMISSIONS after copying as needed.
1217 X provides many option settings.
1218 Return true if successful.
1219 *NEW_DST is initially as in copy_internal.
1220 If successful, set *NEW_DST to true if the destination file was created and
1221 to false otherwise; if unsuccessful, perhaps set *NEW_DST to some value.
1222 SRC_SB is the result of calling follow_fstatat on SRC_NAME;
1223 it might be updated by calling fstat again on the same file,
1224 to give it slightly more up-to-date contents. */
1226 static bool
1227 copy_reg (char const *src_name, char const *dst_name,
1228 int dst_dirfd, char const *dst_relname,
1229 const struct cp_options *x,
1230 mode_t dst_mode, mode_t omitted_permissions, bool *new_dst,
1231 struct stat *src_sb)
1233 char *buf = nullptr;
1234 int dest_desc;
1235 int dest_errno;
1236 int source_desc;
1237 mode_t extra_permissions;
1238 struct stat sb;
1239 struct stat src_open_sb;
1240 union scan_inference scan_inference;
1241 bool return_val = true;
1242 bool data_copy_required = x->data_copy_required;
1243 bool preserve_xattr = USE_XATTR & x->preserve_xattr;
1245 copy_debug.offload = COPY_DEBUG_UNKNOWN;
1246 copy_debug.reflink = x->reflink_mode ? COPY_DEBUG_UNKNOWN : COPY_DEBUG_NO;
1247 copy_debug.sparse_detection = COPY_DEBUG_UNKNOWN;
1249 source_desc = open (src_name,
1250 (O_RDONLY | O_BINARY
1251 | (x->dereference == DEREF_NEVER ? O_NOFOLLOW : 0)));
1252 if (source_desc < 0)
1254 error (0, errno, _("cannot open %s for reading"), quoteaf (src_name));
1255 return false;
1258 if (fstat (source_desc, &src_open_sb) != 0)
1260 error (0, errno, _("cannot fstat %s"), quoteaf (src_name));
1261 return_val = false;
1262 goto close_src_desc;
1265 /* Compare the source dev/ino from the open file to the incoming,
1266 saved ones obtained via a previous call to stat. */
1267 if (! psame_inode (src_sb, &src_open_sb))
1269 error (0, 0,
1270 _("skipping file %s, as it was replaced while being copied"),
1271 quoteaf (src_name));
1272 return_val = false;
1273 goto close_src_desc;
1276 /* Might as well tell the caller about the latest version of the
1277 source file status, since we have it already. */
1278 *src_sb = src_open_sb;
1279 mode_t src_mode = src_sb->st_mode;
1281 /* The semantics of the following open calls are mandated
1282 by the specs for both cp and mv. */
1283 if (! *new_dst)
1285 int open_flags =
1286 O_WRONLY | O_BINARY | (data_copy_required ? O_TRUNC : 0);
1287 dest_desc = openat (dst_dirfd, dst_relname, open_flags);
1288 dest_errno = errno;
1290 /* When using cp --preserve=context to copy to an existing destination,
1291 reset the context as per the default context, which has already been
1292 set according to the src.
1293 When using the mutually exclusive -Z option, then adjust the type of
1294 the existing context according to the system default for the dest.
1295 Note we set the context here, _after_ the file is opened, lest the
1296 new context disallow that. */
1297 if (0 <= dest_desc
1298 && (x->set_security_context || x->preserve_security_context))
1300 if (! set_file_security_ctx (dst_name, false, x))
1302 if (x->require_preserve_context)
1304 return_val = false;
1305 goto close_src_and_dst_desc;
1310 if (dest_desc < 0 && dest_errno != ENOENT
1311 && x->unlink_dest_after_failed_open)
1313 if (unlinkat (dst_dirfd, dst_relname, 0) == 0)
1315 if (x->verbose)
1316 printf (_("removed %s\n"), quoteaf (dst_name));
1318 else if (errno != ENOENT)
1320 error (0, errno, _("cannot remove %s"), quoteaf (dst_name));
1321 return_val = false;
1322 goto close_src_desc;
1325 dest_errno = ENOENT;
1328 if (dest_desc < 0 && dest_errno == ENOENT)
1330 /* Ensure there is no race where a file may be left without
1331 an appropriate security context. */
1332 if (x->set_security_context)
1334 if (! set_process_security_ctx (src_name, dst_name, dst_mode,
1335 true, x))
1337 return_val = false;
1338 goto close_src_desc;
1342 /* Tell caller that the destination file is created. */
1343 *new_dst = true;
1347 if (*new_dst)
1349 #if HAVE_FCLONEFILEAT && !USE_XATTR
1350 # ifndef CLONE_ACL
1351 # define CLONE_ACL 0 /* Added in macOS 12.6. */
1352 # endif
1353 # ifndef CLONE_NOOWNERCOPY
1354 # define CLONE_NOOWNERCOPY 0 /* Added in macOS 10.13. */
1355 # endif
1356 /* Try fclonefileat if copying data in reflink mode.
1357 Use CLONE_NOFOLLOW to avoid security issues that could occur
1358 if writing through dangling symlinks. Although the circa
1359 2023 macOS documentation doesn't say so, CLONE_NOFOLLOW
1360 affects the destination file too. */
1361 if (data_copy_required && x->reflink_mode
1362 && (CLONE_NOOWNERCOPY || x->preserve_ownership))
1364 /* Try fclonefileat so long as it won't create the
1365 destination with unwanted permissions, which could lead
1366 to a security race. */
1367 mode_t cloned_mode_bits = S_ISVTX | S_IRWXUGO;
1368 mode_t cloned_mode = src_mode & cloned_mode_bits;
1369 mode_t desired_mode
1370 = (x->preserve_mode ? src_mode & CHMOD_MODE_BITS
1371 : x->set_mode ? x->mode
1372 : ((x->explicit_no_preserve_mode ? MODE_RW_UGO : dst_mode)
1373 & ~ cached_umask ()));
1374 if (! (cloned_mode & ~desired_mode))
1376 int fc_flags
1377 = (CLONE_NOFOLLOW
1378 | (x->preserve_mode ? CLONE_ACL : 0)
1379 | (x->preserve_ownership ? 0 : CLONE_NOOWNERCOPY));
1380 int s = fclonefileat (source_desc, dst_dirfd, dst_relname,
1381 fc_flags);
1382 if (s != 0 && (fc_flags & CLONE_ACL) && errno == EINVAL)
1384 fc_flags &= ~CLONE_ACL;
1385 s = fclonefileat (source_desc, dst_dirfd, dst_relname,
1386 fc_flags);
1388 if (s == 0)
1390 copy_debug.reflink = COPY_DEBUG_YES;
1392 /* Update the clone's timestamps and permissions
1393 as needed. */
1395 if (!x->preserve_timestamps)
1397 struct timespec timespec[2];
1398 timespec[0].tv_nsec = timespec[1].tv_nsec = UTIME_NOW;
1399 if (utimensat (dst_dirfd, dst_relname, timespec,
1400 AT_SYMLINK_NOFOLLOW)
1401 != 0)
1403 error (0, errno, _("updating times for %s"),
1404 quoteaf (dst_name));
1405 return_val = false;
1406 goto close_src_desc;
1410 extra_permissions = desired_mode & ~cloned_mode;
1411 if (!extra_permissions
1412 && (!x->preserve_mode || (fc_flags & CLONE_ACL)
1413 || !fd_has_acl (source_desc)))
1415 goto close_src_desc;
1418 /* Either some desired permissions were not cloned,
1419 or ACLs were not cloned despite that being requested. */
1420 omitted_permissions = 0;
1421 dest_desc = -1;
1422 goto set_dest_mode;
1424 if (! handle_clone_fail (dst_dirfd, dst_relname, src_name,
1425 dst_name,
1426 -1, false /* We didn't create dst */,
1427 x->reflink_mode))
1429 return_val = false;
1430 goto close_src_desc;
1433 else
1434 copy_debug.reflink = COPY_DEBUG_AVOIDED;
1436 else if (data_copy_required && x->reflink_mode)
1438 if (! CLONE_NOOWNERCOPY)
1439 copy_debug.reflink = COPY_DEBUG_AVOIDED;
1441 #endif
1443 /* To allow copying xattrs on read-only files, create with u+w.
1444 This satisfies an inode permission check done by
1445 xattr_permission in fs/xattr.c of the GNU/Linux kernel. */
1446 mode_t open_mode =
1447 ((dst_mode & ~omitted_permissions)
1448 | (preserve_xattr && !x->owner_privileges ? S_IWUSR : 0));
1449 extra_permissions = open_mode & ~dst_mode; /* either 0 or S_IWUSR */
1451 int open_flags = O_WRONLY | O_CREAT | O_BINARY;
1452 dest_desc = openat (dst_dirfd, dst_relname, open_flags | O_EXCL,
1453 open_mode);
1454 dest_errno = errno;
1456 /* When trying to copy through a dangling destination symlink,
1457 the above open fails with EEXIST. If that happens, and
1458 readlinkat shows that it is a symlink, then we
1459 have a problem: trying to resolve this dangling symlink to
1460 a directory/destination-entry pair is fundamentally racy,
1461 so punt. If x->open_dangling_dest_symlink is set (cp sets
1462 that when POSIXLY_CORRECT is set in the environment), simply
1463 call open again, but without O_EXCL (potentially dangerous).
1464 If not, fail with a diagnostic. These shenanigans are necessary
1465 only when copying, i.e., not in move_mode. */
1466 if (dest_desc < 0 && dest_errno == EEXIST && ! x->move_mode)
1468 char dummy[1];
1469 if (0 <= readlinkat (dst_dirfd, dst_relname, dummy, sizeof dummy))
1471 if (x->open_dangling_dest_symlink)
1473 dest_desc = openat (dst_dirfd, dst_relname,
1474 open_flags, open_mode);
1475 dest_errno = errno;
1477 else
1479 error (0, 0, _("not writing through dangling symlink %s"),
1480 quoteaf (dst_name));
1481 return_val = false;
1482 goto close_src_desc;
1487 /* Improve quality of diagnostic when a nonexistent dst_name
1488 ends in a slash and open fails with errno == EISDIR. */
1489 if (dest_desc < 0 && dest_errno == EISDIR
1490 && *dst_name && dst_name[strlen (dst_name) - 1] == '/')
1491 dest_errno = ENOTDIR;
1493 else
1495 omitted_permissions = extra_permissions = 0;
1498 if (dest_desc < 0)
1500 error (0, dest_errno, _("cannot create regular file %s"),
1501 quoteaf (dst_name));
1502 return_val = false;
1503 goto close_src_desc;
1506 /* --attributes-only overrides --reflink. */
1507 if (data_copy_required && x->reflink_mode)
1509 if (clone_file (dest_desc, source_desc) == 0)
1511 data_copy_required = false;
1512 copy_debug.reflink = COPY_DEBUG_YES;
1514 else
1516 if (! handle_clone_fail (dst_dirfd, dst_relname, src_name, dst_name,
1517 dest_desc, *new_dst, x->reflink_mode))
1519 return_val = false;
1520 goto close_src_and_dst_desc;
1525 if (! (data_copy_required | x->preserve_ownership | extra_permissions))
1526 sb.st_mode = 0;
1527 else if (fstat (dest_desc, &sb) != 0)
1529 error (0, errno, _("cannot fstat %s"), quoteaf (dst_name));
1530 return_val = false;
1531 goto close_src_and_dst_desc;
1534 /* If extra permissions needed for copy_xattr didn't happen (e.g.,
1535 due to umask) chmod to add them temporarily; if that fails give
1536 up with extra permissions, letting copy_attr fail later. */
1537 mode_t temporary_mode = sb.st_mode | extra_permissions;
1538 if (temporary_mode != sb.st_mode
1539 && (fchmod_or_lchmod (dest_desc, dst_dirfd, dst_relname, temporary_mode)
1540 != 0))
1541 extra_permissions = 0;
1543 if (data_copy_required)
1545 /* Choose a suitable buffer size; it may be adjusted later. */
1546 size_t buf_size = io_blksize (&sb);
1547 size_t hole_size = STP_BLKSIZE (&sb);
1549 /* Deal with sparse files. */
1550 enum scantype scantype = infer_scantype (source_desc, &src_open_sb,
1551 &scan_inference);
1552 if (scantype == ERROR_SCANTYPE)
1554 error (0, errno, _("cannot lseek %s"), quoteaf (src_name));
1555 return_val = false;
1556 goto close_src_and_dst_desc;
1558 bool make_holes
1559 = (S_ISREG (sb.st_mode)
1560 && (x->sparse_mode == SPARSE_ALWAYS
1561 || (x->sparse_mode == SPARSE_AUTO
1562 && scantype != PLAIN_SCANTYPE)));
1564 fdadvise (source_desc, 0, 0, FADVISE_SEQUENTIAL);
1566 /* If not making a sparse file, try to use a more-efficient
1567 buffer size. */
1568 if (! make_holes)
1570 /* Compute the least common multiple of the input and output
1571 buffer sizes, adjusting for outlandish values.
1572 Note we read in multiples of the reported block size
1573 to support (unusual) devices that have this constraint. */
1574 size_t blcm_max = MIN (SIZE_MAX, SSIZE_MAX);
1575 size_t blcm = buffer_lcm (io_blksize (&src_open_sb), buf_size,
1576 blcm_max);
1578 /* Do not bother with a buffer larger than the input file, plus one
1579 byte to make sure the file has not grown while reading it. */
1580 if (S_ISREG (src_open_sb.st_mode) && src_open_sb.st_size < buf_size)
1581 buf_size = src_open_sb.st_size + 1;
1583 /* However, stick with a block size that is a positive multiple of
1584 blcm, overriding the above adjustments. Watch out for
1585 overflow. */
1586 buf_size += blcm - 1;
1587 buf_size -= buf_size % blcm;
1588 if (buf_size == 0 || blcm_max < buf_size)
1589 buf_size = blcm;
1592 off_t n_read;
1593 bool wrote_hole_at_eof = false;
1594 if (! (
1595 #ifdef SEEK_HOLE
1596 scantype == LSEEK_SCANTYPE
1597 ? lseek_copy (source_desc, dest_desc, &buf, buf_size, hole_size,
1598 scan_inference.ext_start, src_open_sb.st_size,
1599 make_holes ? x->sparse_mode : SPARSE_NEVER,
1600 x->reflink_mode != REFLINK_NEVER,
1601 src_name, dst_name)
1603 #endif
1604 sparse_copy (source_desc, dest_desc, &buf, buf_size,
1605 make_holes ? hole_size : 0,
1606 x->sparse_mode == SPARSE_ALWAYS,
1607 x->reflink_mode != REFLINK_NEVER,
1608 src_name, dst_name, UINTMAX_MAX, &n_read,
1609 &wrote_hole_at_eof)))
1611 return_val = false;
1612 goto close_src_and_dst_desc;
1614 else if (wrote_hole_at_eof && ftruncate (dest_desc, n_read) < 0)
1616 error (0, errno, _("failed to extend %s"), quoteaf (dst_name));
1617 return_val = false;
1618 goto close_src_and_dst_desc;
1622 if (x->preserve_timestamps)
1624 struct timespec timespec[2];
1625 timespec[0] = get_stat_atime (src_sb);
1626 timespec[1] = get_stat_mtime (src_sb);
1628 if (fdutimensat (dest_desc, dst_dirfd, dst_relname, timespec, 0) != 0)
1630 error (0, errno, _("preserving times for %s"), quoteaf (dst_name));
1631 if (x->require_preserve)
1633 return_val = false;
1634 goto close_src_and_dst_desc;
1639 /* Set ownership before xattrs as changing owners will
1640 clear capabilities. */
1641 if (x->preserve_ownership && ! SAME_OWNER_AND_GROUP (*src_sb, sb))
1643 switch (set_owner (x, dst_name, dst_dirfd, dst_relname, dest_desc,
1644 src_sb, *new_dst, &sb))
1646 case -1:
1647 return_val = false;
1648 goto close_src_and_dst_desc;
1650 case 0:
1651 src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX);
1652 break;
1656 if (preserve_xattr)
1658 if (!copy_attr (src_name, source_desc, dst_name, dest_desc, x)
1659 && x->require_preserve_xattr)
1660 return_val = false;
1663 set_author (dst_name, dest_desc, src_sb);
1665 #if HAVE_FCLONEFILEAT && !USE_XATTR
1666 set_dest_mode:
1667 #endif
1668 if (x->preserve_mode || x->move_mode)
1670 if (copy_acl (src_name, source_desc, dst_name, dest_desc, src_mode) != 0
1671 && x->require_preserve)
1672 return_val = false;
1674 else if (x->set_mode)
1676 if (set_acl (dst_name, dest_desc, x->mode) != 0)
1677 return_val = false;
1679 else if (x->explicit_no_preserve_mode && *new_dst)
1681 if (set_acl (dst_name, dest_desc, MODE_RW_UGO & ~cached_umask ()) != 0)
1682 return_val = false;
1684 else if (omitted_permissions | extra_permissions)
1686 omitted_permissions &= ~ cached_umask ();
1687 if ((omitted_permissions | extra_permissions)
1688 && (fchmod_or_lchmod (dest_desc, dst_dirfd, dst_relname,
1689 dst_mode & ~ cached_umask ())
1690 != 0))
1692 error (0, errno, _("preserving permissions for %s"),
1693 quoteaf (dst_name));
1694 if (x->require_preserve)
1695 return_val = false;
1699 if (dest_desc < 0)
1700 goto close_src_desc;
1702 close_src_and_dst_desc:
1703 if (close (dest_desc) < 0)
1705 error (0, errno, _("failed to close %s"), quoteaf (dst_name));
1706 return_val = false;
1708 close_src_desc:
1709 if (close (source_desc) < 0)
1711 error (0, errno, _("failed to close %s"), quoteaf (src_name));
1712 return_val = false;
1715 /* Output debug info for data copying operations. */
1716 if (x->debug)
1717 emit_debug (x);
1719 alignfree (buf);
1720 return return_val;
1723 /* Return whether it's OK that two files are the "same" by some measure.
1724 The first file is SRC_NAME and has status SRC_SB.
1725 The second is DST_DIRFD+DST_RELNAME and has status DST_SB.
1726 The copying options are X. The goal is to avoid
1727 making the 'copy' operation remove both copies of the file
1728 in that case, while still allowing the user to e.g., move or
1729 copy a regular file onto a symlink that points to it.
1730 Try to minimize the cost of this function in the common case.
1731 Set *RETURN_NOW if we've determined that the caller has no more
1732 work to do and should return successfully, right away. */
1734 static bool
1735 same_file_ok (char const *src_name, struct stat const *src_sb,
1736 int dst_dirfd, char const *dst_relname, struct stat const *dst_sb,
1737 const struct cp_options *x, bool *return_now)
1739 const struct stat *src_sb_link;
1740 const struct stat *dst_sb_link;
1741 struct stat tmp_dst_sb;
1742 struct stat tmp_src_sb;
1744 bool same_link;
1745 bool same = psame_inode (src_sb, dst_sb);
1747 *return_now = false;
1749 /* FIXME: this should (at the very least) be moved into the following
1750 if-block. More likely, it should be removed, because it inhibits
1751 making backups. But removing it will result in a change in behavior
1752 that will probably have to be documented -- and tests will have to
1753 be updated. */
1754 if (same && x->hard_link)
1756 *return_now = true;
1757 return true;
1760 if (x->dereference == DEREF_NEVER)
1762 same_link = same;
1764 /* If both the source and destination files are symlinks (and we'll
1765 know this here IFF preserving symlinks), then it's usually ok
1766 when they are distinct. */
1767 if (S_ISLNK (src_sb->st_mode) && S_ISLNK (dst_sb->st_mode))
1769 bool sn = same_nameat (AT_FDCWD, src_name, dst_dirfd, dst_relname);
1770 if ( ! sn)
1772 /* It's fine when we're making any type of backup. */
1773 if (x->backup_type != no_backups)
1774 return true;
1776 /* Here we have two symlinks that are hard-linked together,
1777 and we're not making backups. In this unusual case, simply
1778 returning true would lead to mv calling "rename(A,B)",
1779 which would do nothing and return 0. */
1780 if (same_link)
1782 *return_now = true;
1783 return ! x->move_mode;
1787 return ! sn;
1790 src_sb_link = src_sb;
1791 dst_sb_link = dst_sb;
1793 else
1795 if (!same)
1796 return true;
1798 if (fstatat (dst_dirfd, dst_relname, &tmp_dst_sb,
1799 AT_SYMLINK_NOFOLLOW) != 0
1800 || lstat (src_name, &tmp_src_sb) != 0)
1801 return true;
1803 src_sb_link = &tmp_src_sb;
1804 dst_sb_link = &tmp_dst_sb;
1806 same_link = psame_inode (src_sb_link, dst_sb_link);
1808 /* If both are symlinks, then it's ok, but only if the destination
1809 will be unlinked before being opened. This is like the test
1810 above, but with the addition of the unlink_dest_before_opening
1811 conjunct because otherwise, with two symlinks to the same target,
1812 we'd end up truncating the source file. */
1813 if (S_ISLNK (src_sb_link->st_mode) && S_ISLNK (dst_sb_link->st_mode)
1814 && x->unlink_dest_before_opening)
1815 return true;
1818 /* The backup code ensures there's a copy, so it's usually ok to
1819 remove any destination file. One exception is when both
1820 source and destination are the same directory entry. In that
1821 case, moving the destination file aside (in making the backup)
1822 would also rename the source file and result in an error. */
1823 if (x->backup_type != no_backups)
1825 if (!same_link)
1827 /* In copy mode when dereferencing symlinks, if the source is a
1828 symlink and the dest is not, then backing up the destination
1829 (moving it aside) would make it a dangling symlink, and the
1830 subsequent attempt to open it in copy_reg would fail with
1831 a misleading diagnostic. Avoid that by returning zero in
1832 that case so the caller can make cp (or mv when it has to
1833 resort to reading the source file) fail now. */
1835 /* FIXME-note: even with the following kludge, we can still provoke
1836 the offending diagnostic. It's just a little harder to do :-)
1837 $ rm -f a b c; touch c; ln -s c b; ln -s b a; cp -b a b
1838 cp: cannot open 'a' for reading: No such file or directory
1839 That's misleading, since a subsequent 'ls' shows that 'a'
1840 is still there.
1841 One solution would be to open the source file *before* moving
1842 aside the destination, but that'd involve a big rewrite. */
1843 if ( ! x->move_mode
1844 && x->dereference != DEREF_NEVER
1845 && S_ISLNK (src_sb_link->st_mode)
1846 && ! S_ISLNK (dst_sb_link->st_mode))
1847 return false;
1849 return true;
1852 /* FIXME: What about case insensitive file systems ? */
1853 return ! same_nameat (AT_FDCWD, src_name, dst_dirfd, dst_relname);
1856 #if 0
1857 /* FIXME: use or remove */
1859 /* If we're making a backup, we'll detect the problem case in
1860 copy_reg because SRC_NAME will no longer exist. Allowing
1861 the test to be deferred lets cp do some useful things.
1862 But when creating hardlinks and SRC_NAME is a symlink
1863 but DST_RELNAME is not we must test anyway. */
1864 if (x->hard_link
1865 || !S_ISLNK (src_sb_link->st_mode)
1866 || S_ISLNK (dst_sb_link->st_mode))
1867 return true;
1869 if (x->dereference != DEREF_NEVER)
1870 return true;
1871 #endif
1873 if (x->move_mode || x->unlink_dest_before_opening)
1875 /* They may refer to the same file if we're in move mode and the
1876 target is a symlink. That is ok, since we remove any existing
1877 destination file before opening it -- via 'rename' if they're on
1878 the same file system, via unlinkat otherwise. */
1879 if (S_ISLNK (dst_sb_link->st_mode))
1880 return true;
1882 /* It's not ok if they're distinct hard links to the same file as
1883 this causes a race condition and we may lose data in this case. */
1884 if (same_link
1885 && 1 < dst_sb_link->st_nlink
1886 && ! same_nameat (AT_FDCWD, src_name, dst_dirfd, dst_relname))
1887 return ! x->move_mode;
1890 /* If neither is a symlink, then it's ok as long as they aren't
1891 hard links to the same file. */
1892 if (!S_ISLNK (src_sb_link->st_mode) && !S_ISLNK (dst_sb_link->st_mode))
1894 if (!psame_inode (src_sb_link, dst_sb_link))
1895 return true;
1897 /* If they are the same file, it's ok if we're making hard links. */
1898 if (x->hard_link)
1900 *return_now = true;
1901 return true;
1905 /* At this point, it is normally an error (data loss) to move a symlink
1906 onto its referent, but in at least one narrow case, it is not:
1907 In move mode, when
1908 1) src is a symlink,
1909 2) dest has a link count of 2 or more and
1910 3) dest and the referent of src are not the same directory entry,
1911 then it's ok, since while we'll lose one of those hard links,
1912 src will still point to a remaining link.
1913 Note that technically, condition #3 obviates condition #2, but we
1914 retain the 1 < st_nlink condition because that means fewer invocations
1915 of the more expensive #3.
1917 Given this,
1918 $ touch f && ln f l && ln -s f s
1919 $ ls -og f l s
1920 -rw-------. 2 0 Jan 4 22:46 f
1921 -rw-------. 2 0 Jan 4 22:46 l
1922 lrwxrwxrwx. 1 1 Jan 4 22:46 s -> f
1923 this must fail: mv s f
1924 this must succeed: mv s l */
1925 if (x->move_mode
1926 && S_ISLNK (src_sb->st_mode)
1927 && 1 < dst_sb_link->st_nlink)
1929 char *abs_src = canonicalize_file_name (src_name);
1930 if (abs_src)
1932 bool result = ! same_nameat (AT_FDCWD, abs_src,
1933 dst_dirfd, dst_relname);
1934 free (abs_src);
1935 return result;
1939 /* It's ok to recreate a destination symlink. */
1940 if (x->symbolic_link && S_ISLNK (dst_sb_link->st_mode))
1941 return true;
1943 if (x->dereference == DEREF_NEVER)
1945 if ( ! S_ISLNK (src_sb_link->st_mode))
1946 tmp_src_sb = *src_sb_link;
1947 else if (stat (src_name, &tmp_src_sb) != 0)
1948 return true;
1950 if ( ! S_ISLNK (dst_sb_link->st_mode))
1951 tmp_dst_sb = *dst_sb_link;
1952 else if (fstatat (dst_dirfd, dst_relname, &tmp_dst_sb, 0) != 0)
1953 return true;
1955 if (!psame_inode (&tmp_src_sb, &tmp_dst_sb))
1956 return true;
1958 if (x->hard_link)
1960 /* It's ok to attempt to hardlink the same file,
1961 and return early if not replacing a symlink.
1962 Note we need to return early to avoid a later
1963 unlink() of DST (when SRC is a symlink). */
1964 *return_now = ! S_ISLNK (dst_sb_link->st_mode);
1965 return true;
1969 return false;
1972 /* Return whether DST_DIRFD+DST_RELNAME, with mode MODE,
1973 is writable in the sense of 'mv'.
1974 Always consider a symbolic link to be writable. */
1975 static bool
1976 writable_destination (int dst_dirfd, char const *dst_relname, mode_t mode)
1978 return (S_ISLNK (mode)
1979 || can_write_any_file ()
1980 || faccessat (dst_dirfd, dst_relname, W_OK, AT_EACCESS) == 0);
1983 static bool
1984 overwrite_ok (struct cp_options const *x, char const *dst_name,
1985 int dst_dirfd, char const *dst_relname,
1986 struct stat const *dst_sb)
1988 if (! writable_destination (dst_dirfd, dst_relname, dst_sb->st_mode))
1990 char perms[12]; /* "-rwxrwxrwx " ls-style modes. */
1991 strmode (dst_sb->st_mode, perms);
1992 perms[10] = '\0';
1993 fprintf (stderr,
1994 (x->move_mode || x->unlink_dest_before_opening
1995 || x->unlink_dest_after_failed_open)
1996 ? _("%s: replace %s, overriding mode %04lo (%s)? ")
1997 : _("%s: unwritable %s (mode %04lo, %s); try anyway? "),
1998 program_name, quoteaf (dst_name),
1999 (unsigned long int) (dst_sb->st_mode & CHMOD_MODE_BITS),
2000 &perms[1]);
2002 else
2004 fprintf (stderr, _("%s: overwrite %s? "),
2005 program_name, quoteaf (dst_name));
2008 return yesno ();
2011 /* Initialize the hash table implementing a set of F_triple entries
2012 corresponding to destination files. */
2013 extern void
2014 dest_info_init (struct cp_options *x)
2016 x->dest_info
2017 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
2018 nullptr,
2019 triple_hash,
2020 triple_compare,
2021 triple_free);
2022 if (! x->dest_info)
2023 xalloc_die ();
2026 /* Initialize the hash table implementing a set of F_triple entries
2027 corresponding to source files listed on the command line. */
2028 extern void
2029 src_info_init (struct cp_options *x)
2032 /* Note that we use triple_hash_no_name here.
2033 Contrast with the use of triple_hash above.
2034 That is necessary because a source file may be specified
2035 in many different ways. We want to warn about this
2036 cp a a d/
2037 as well as this:
2038 cp a ./a d/
2040 x->src_info
2041 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
2042 nullptr,
2043 triple_hash_no_name,
2044 triple_compare,
2045 triple_free);
2046 if (! x->src_info)
2047 xalloc_die ();
2050 /* When effecting a move (e.g., for mv(1)), and given the name DST_NAME
2051 aka DST_DIRFD+DST_RELNAME
2052 of the destination and a corresponding stat buffer, DST_SB, return
2053 true if the logical 'move' operation should _not_ proceed.
2054 Otherwise, return false.
2055 Depending on options specified in X, this code may issue an
2056 interactive prompt asking whether it's ok to overwrite DST_NAME. */
2057 static bool
2058 abandon_move (const struct cp_options *x,
2059 char const *dst_name,
2060 int dst_dirfd, char const *dst_relname,
2061 struct stat const *dst_sb)
2063 affirm (x->move_mode);
2064 return (x->interactive == I_ALWAYS_NO
2065 || x->interactive == I_ALWAYS_SKIP
2066 || ((x->interactive == I_ASK_USER
2067 || (x->interactive == I_UNSPECIFIED
2068 && x->stdin_tty
2069 && ! writable_destination (dst_dirfd, dst_relname,
2070 dst_sb->st_mode)))
2071 && ! overwrite_ok (x, dst_name, dst_dirfd, dst_relname, dst_sb)));
2074 /* Print --verbose output on standard output, e.g. 'new' -> 'old'.
2075 If BACKUP_DST_NAME is non-null, then also indicate that it is
2076 the name of a backup file. */
2077 static void
2078 emit_verbose (char const *src, char const *dst, char const *backup_dst_name)
2080 printf ("%s -> %s", quoteaf_n (0, src), quoteaf_n (1, dst));
2081 if (backup_dst_name)
2082 printf (_(" (backup: %s)"), quoteaf (backup_dst_name));
2083 putchar ('\n');
2086 /* A wrapper around "setfscreatecon (nullptr)" that exits upon failure. */
2087 static void
2088 restore_default_fscreatecon_or_die (void)
2090 if (setfscreatecon (nullptr) != 0)
2091 error (EXIT_FAILURE, errno,
2092 _("failed to restore the default file creation context"));
2095 /* Return a newly-allocated string that is like STR
2096 except replace its suffix SUFFIX with NEWSUFFIX. */
2097 static char *
2098 subst_suffix (char const *str, char const *suffix, char const *newsuffix)
2100 idx_t prefixlen = suffix - str;
2101 idx_t newsuffixsize = strlen (newsuffix) + 1;
2102 char *r = ximalloc (prefixlen + newsuffixsize);
2103 memcpy (r + prefixlen, newsuffix, newsuffixsize);
2104 return memcpy (r, str, prefixlen);
2107 /* Create a hard link to SRC_NAME aka SRC_DIRFD+SRC_RELNAME;
2108 the new link is at DST_NAME aka DST_DIRFD+DST_RELNAME.
2109 A null SRC_NAME stands for the file whose name is like DST_NAME
2110 except with DST_RELNAME replaced with SRC_RELNAME.
2111 Honor the REPLACE, VERBOSE and DEREFERENCE settings.
2112 Return true upon success. Otherwise, diagnose the
2113 failure and return false. If SRC_NAME is a symbolic link, then it will not
2114 be followed unless DEREFERENCE is true.
2115 If the system doesn't support hard links to symbolic links, then DST_NAME
2116 will be created as a symbolic link to SRC_NAME. */
2117 static bool
2118 create_hard_link (char const *src_name, int src_dirfd, char const *src_relname,
2119 char const *dst_name, int dst_dirfd, char const *dst_relname,
2120 bool replace, bool verbose, bool dereference)
2122 int err = force_linkat (src_dirfd, src_relname, dst_dirfd, dst_relname,
2123 dereference ? AT_SYMLINK_FOLLOW : 0,
2124 replace, -1);
2125 if (0 < err)
2128 char *a_src_name = nullptr;
2129 if (!src_name)
2130 src_name = a_src_name = subst_suffix (dst_name, dst_relname,
2131 src_relname);
2132 error (0, err, _("cannot create hard link %s to %s"),
2133 quoteaf_n (0, dst_name), quoteaf_n (1, src_name));
2134 free (a_src_name);
2135 return false;
2137 if (err < 0 && verbose)
2138 printf (_("removed %s\n"), quoteaf (dst_name));
2139 return true;
2142 /* Return true if the current file should be (tried to be) dereferenced:
2143 either for DEREF_ALWAYS or for DEREF_COMMAND_LINE_ARGUMENTS in the case
2144 where the current file is a COMMAND_LINE_ARG; otherwise return false. */
2145 ATTRIBUTE_PURE
2146 static inline bool
2147 should_dereference (const struct cp_options *x, bool command_line_arg)
2149 return x->dereference == DEREF_ALWAYS
2150 || (x->dereference == DEREF_COMMAND_LINE_ARGUMENTS
2151 && command_line_arg);
2154 /* Return true if the source file with basename SRCBASE and status SRC_ST
2155 is likely to be the simple backup file for DST_DIRFD+DST_RELNAME. */
2156 static bool
2157 source_is_dst_backup (char const *srcbase, struct stat const *src_st,
2158 int dst_dirfd, char const *dst_relname)
2160 size_t srcbaselen = strlen (srcbase);
2161 char const *dstbase = last_component (dst_relname);
2162 size_t dstbaselen = strlen (dstbase);
2163 size_t suffixlen = strlen (simple_backup_suffix);
2164 if (! (srcbaselen == dstbaselen + suffixlen
2165 && memcmp (srcbase, dstbase, dstbaselen) == 0
2166 && STREQ (srcbase + dstbaselen, simple_backup_suffix)))
2167 return false;
2168 char *dst_back = subst_suffix (dst_relname,
2169 dst_relname + strlen (dst_relname),
2170 simple_backup_suffix);
2171 struct stat dst_back_sb;
2172 int dst_back_status = fstatat (dst_dirfd, dst_back, &dst_back_sb, 0);
2173 free (dst_back);
2174 return dst_back_status == 0 && psame_inode (src_st, &dst_back_sb);
2177 /* Copy the file SRC_NAME to the file DST_NAME aka DST_DIRFD+DST_RELNAME.
2178 If NONEXISTENT_DST is positive, DST_NAME does not exist even as a
2179 dangling symlink; if negative, it does not exist except possibly
2180 as a dangling symlink; if zero, its existence status is unknown.
2181 A non-null PARENT describes the parent directory.
2182 ANCESTORS points to a linked, null terminated list of
2183 devices and inodes of parent directories of SRC_NAME.
2184 X summarizes the command-line options.
2185 COMMAND_LINE_ARG means SRC_NAME was specified on the command line.
2186 FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG is both input and output.
2187 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
2188 same as) DST_NAME; otherwise, clear it.
2189 If X->move_mode, set *RENAME_SUCCEEDED according to whether
2190 the source was simply renamed to the destination.
2191 Return true if successful. */
2192 static bool
2193 copy_internal (char const *src_name, char const *dst_name,
2194 int dst_dirfd, char const *dst_relname,
2195 int nonexistent_dst,
2196 struct stat const *parent,
2197 struct dir_list *ancestors,
2198 const struct cp_options *x,
2199 bool command_line_arg,
2200 bool *first_dir_created_per_command_line_arg,
2201 bool *copy_into_self,
2202 bool *rename_succeeded)
2204 struct stat src_sb;
2205 struct stat dst_sb;
2206 mode_t src_mode IF_LINT ( = 0);
2207 mode_t dst_mode IF_LINT ( = 0);
2208 mode_t dst_mode_bits;
2209 mode_t omitted_permissions;
2210 bool restore_dst_mode = false;
2211 char *earlier_file = nullptr;
2212 char *dst_backup = nullptr;
2213 char const *drelname = *dst_relname ? dst_relname : ".";
2214 bool delayed_ok;
2215 bool copied_as_regular = false;
2216 bool dest_is_symlink = false;
2217 bool have_dst_lstat = false;
2219 *copy_into_self = false;
2221 int rename_errno = x->rename_errno;
2222 if (x->move_mode)
2224 if (rename_errno < 0)
2225 rename_errno = (renameatu (AT_FDCWD, src_name, dst_dirfd, drelname,
2226 RENAME_NOREPLACE)
2227 ? errno : 0);
2228 nonexistent_dst = *rename_succeeded = rename_errno == 0;
2231 if (rename_errno == 0
2232 ? !x->last_file
2233 : rename_errno != EEXIST
2234 || (x->interactive != I_ALWAYS_NO && x->interactive != I_ALWAYS_SKIP))
2236 char const *name = rename_errno == 0 ? dst_name : src_name;
2237 int dirfd = rename_errno == 0 ? dst_dirfd : AT_FDCWD;
2238 char const *relname = rename_errno == 0 ? drelname : src_name;
2239 int fstatat_flags
2240 = x->dereference == DEREF_NEVER ? AT_SYMLINK_NOFOLLOW : 0;
2241 if (follow_fstatat (dirfd, relname, &src_sb, fstatat_flags) != 0)
2243 error (0, errno, _("cannot stat %s"), quoteaf (name));
2244 return false;
2247 src_mode = src_sb.st_mode;
2249 if (S_ISDIR (src_mode) && !x->recursive)
2251 error (0, 0, ! x->install_mode /* cp */
2252 ? _("-r not specified; omitting directory %s")
2253 : _("omitting directory %s"),
2254 quoteaf (src_name));
2255 return false;
2258 else
2260 #if defined lint && (defined __clang__ || defined __COVERITY__)
2261 affirm (x->move_mode);
2262 memset (&src_sb, 0, sizeof src_sb);
2263 #endif
2266 /* Detect the case in which the same source file appears more than
2267 once on the command line and no backup option has been selected.
2268 If so, simply warn and don't copy it the second time.
2269 This check is enabled only if x->src_info is non-null. */
2270 if (command_line_arg && x->src_info)
2272 if ( ! S_ISDIR (src_mode)
2273 && x->backup_type == no_backups
2274 && seen_file (x->src_info, src_name, &src_sb))
2276 error (0, 0, _("warning: source file %s specified more than once"),
2277 quoteaf (src_name));
2278 return true;
2281 record_file (x->src_info, src_name, &src_sb);
2284 bool dereference = should_dereference (x, command_line_arg);
2286 /* Whether the destination is (or was) known to be new, updated as
2287 more info comes in. This may become true if the destination is a
2288 dangling symlink, in contexts where dangling symlinks should be
2289 treated the same as nonexistent files. */
2290 bool new_dst = 0 < nonexistent_dst;
2292 if (! new_dst)
2294 /* Normally, fill in DST_SB or set NEW_DST so that later code
2295 can use DST_SB if NEW_DST is false. However, don't bother
2296 doing this when rename_errno == EEXIST and X->interactive is
2297 I_ALWAYS_NO or I_ALWAYS_SKIP, something that can happen only
2298 with mv in which case x->update must be false which means
2299 that even if !NEW_DST the move will be abandoned without
2300 looking at DST_SB. */
2301 if (! (rename_errno == EEXIST
2302 && (x->interactive == I_ALWAYS_NO
2303 || x->interactive == I_ALWAYS_SKIP)))
2305 /* Regular files can be created by writing through symbolic
2306 links, but other files cannot. So use stat on the
2307 destination when copying a regular file, and lstat otherwise.
2308 However, if we intend to unlink or remove the destination
2309 first, use lstat, since a copy won't actually be made to the
2310 destination in that case. */
2311 bool use_lstat
2312 = ((! S_ISREG (src_mode)
2313 && (! x->copy_as_regular
2314 || S_ISDIR (src_mode) || S_ISLNK (src_mode)))
2315 || x->move_mode || x->symbolic_link || x->hard_link
2316 || x->backup_type != no_backups
2317 || x->unlink_dest_before_opening);
2318 if (!use_lstat && nonexistent_dst < 0)
2319 new_dst = true;
2320 else if (0 <= follow_fstatat (dst_dirfd, drelname, &dst_sb,
2321 use_lstat ? AT_SYMLINK_NOFOLLOW : 0))
2323 have_dst_lstat = use_lstat;
2324 rename_errno = EEXIST;
2326 else if (errno == ENOENT)
2327 new_dst = true;
2328 else if (errno == ELOOP && !use_lstat
2329 && x->unlink_dest_after_failed_open)
2331 /* cp -f's destination might be a symlink loop.
2332 Leave new_dst=false so that we try to unlink later. */
2334 else
2336 error (0, errno, _("cannot stat %s"), quoteaf (dst_name));
2337 return false;
2341 if (rename_errno == EEXIST)
2343 bool return_now = false;
2344 bool return_val = true;
2345 bool skipped = false;
2347 if ((x->interactive != I_ALWAYS_NO && x->interactive != I_ALWAYS_SKIP)
2348 && ! same_file_ok (src_name, &src_sb, dst_dirfd, drelname,
2349 &dst_sb, x, &return_now))
2351 error (0, 0, _("%s and %s are the same file"),
2352 quoteaf_n (0, src_name), quoteaf_n (1, dst_name));
2353 return false;
2356 if (x->update && !S_ISDIR (src_mode))
2358 /* When preserving timestamps (but not moving within a file
2359 system), don't worry if the destination timestamp is
2360 less than the source merely because of timestamp
2361 truncation. */
2362 int options = ((x->preserve_timestamps
2363 && ! (x->move_mode
2364 && dst_sb.st_dev == src_sb.st_dev))
2365 ? UTIMECMP_TRUNCATE_SOURCE
2366 : 0);
2368 if (0 <= utimecmpat (dst_dirfd, dst_relname, &dst_sb,
2369 &src_sb, options))
2371 /* We're using --update and the destination is not older
2372 than the source, so do not copy or move. Pretend the
2373 rename succeeded, so the caller (if it's mv) doesn't
2374 end up removing the source file. */
2375 if (rename_succeeded)
2376 *rename_succeeded = true;
2378 /* However, we still must record that we've processed
2379 this src/dest pair, in case this source file is
2380 hard-linked to another one. In that case, we'll use
2381 the mapping information to link the corresponding
2382 destination names. */
2383 earlier_file = remember_copied (dst_relname, src_sb.st_ino,
2384 src_sb.st_dev);
2385 if (earlier_file)
2387 /* Note we currently replace DST_NAME unconditionally,
2388 even if it was a newer separate file. */
2389 if (! create_hard_link (nullptr, dst_dirfd, earlier_file,
2390 dst_name, dst_dirfd, dst_relname,
2391 true,
2392 x->verbose, dereference))
2394 goto un_backup;
2398 skipped = true;
2399 goto skip;
2403 /* When there is an existing destination file, we may end up
2404 returning early, and hence not copying/moving the file.
2405 This may be due to an interactive 'negative' reply to the
2406 prompt about the existing file. It may also be due to the
2407 use of the --no-clobber option.
2409 cp and mv treat -i and -f differently. */
2410 if (x->move_mode)
2412 if (abandon_move (x, dst_name, dst_dirfd, drelname, &dst_sb))
2414 /* Pretend the rename succeeded, so the caller (mv)
2415 doesn't end up removing the source file. */
2416 if (rename_succeeded)
2417 *rename_succeeded = true;
2419 skipped = true;
2420 return_val = x->interactive == I_ALWAYS_SKIP;
2423 else
2425 if (! S_ISDIR (src_mode)
2426 && (x->interactive == I_ALWAYS_NO
2427 || x->interactive == I_ALWAYS_SKIP
2428 || (x->interactive == I_ASK_USER
2429 && ! overwrite_ok (x, dst_name, dst_dirfd,
2430 dst_relname, &dst_sb))))
2432 skipped = true;
2433 return_val = x->interactive == I_ALWAYS_SKIP;
2437 skip:
2438 if (skipped)
2440 if (x->interactive == I_ALWAYS_NO)
2441 error (0, 0, _("not replacing %s"), quoteaf (dst_name));
2442 else if (x->debug)
2443 printf (_("skipped %s\n"), quoteaf (dst_name));
2445 return_now = true;
2448 if (return_now)
2449 return return_val;
2451 if (!S_ISDIR (dst_sb.st_mode))
2453 if (S_ISDIR (src_mode))
2455 if (x->move_mode && x->backup_type != no_backups)
2457 /* Moving a directory onto an existing
2458 non-directory is ok only with --backup. */
2460 else
2462 error (0, 0,
2463 _("cannot overwrite non-directory %s with directory %s"),
2464 quoteaf_n (0, dst_name), quoteaf_n (1, src_name));
2465 return false;
2469 /* Don't let the user destroy their data, even if they try hard:
2470 This mv command must fail (likewise for cp):
2471 rm -rf a b c; mkdir a b c; touch a/f b/f; mv a/f b/f c
2472 Otherwise, the contents of b/f would be lost.
2473 In the case of 'cp', b/f would be lost if the user simulated
2474 a move using cp and rm.
2475 Note that it works fine if you use --backup=numbered. */
2476 if (command_line_arg
2477 && x->backup_type != numbered_backups
2478 && seen_file (x->dest_info, dst_relname, &dst_sb))
2480 error (0, 0,
2481 _("will not overwrite just-created %s with %s"),
2482 quoteaf_n (0, dst_name), quoteaf_n (1, src_name));
2483 return false;
2487 if (!S_ISDIR (src_mode))
2489 if (S_ISDIR (dst_sb.st_mode))
2491 if (x->move_mode && x->backup_type != no_backups)
2493 /* Moving a non-directory onto an existing
2494 directory is ok only with --backup. */
2496 else
2498 error (0, 0,
2499 _("cannot overwrite directory %s with non-directory"),
2500 quoteaf (dst_name));
2501 return false;
2506 if (x->move_mode)
2508 /* Don't allow user to move a directory onto a non-directory. */
2509 if (S_ISDIR (src_sb.st_mode) && !S_ISDIR (dst_sb.st_mode)
2510 && x->backup_type == no_backups)
2512 error (0, 0,
2513 _("cannot move directory onto non-directory: %s -> %s"),
2514 quotef_n (0, src_name), quotef_n (0, dst_name));
2515 return false;
2519 char const *srcbase;
2520 if (x->backup_type != no_backups
2521 /* Don't try to back up a destination if the last
2522 component of src_name is "." or "..". */
2523 && ! dot_or_dotdot (srcbase = last_component (src_name))
2524 /* Create a backup of each destination directory in move mode,
2525 but not in copy mode. FIXME: it might make sense to add an
2526 option to suppress backup creation also for move mode.
2527 That would let one use mv to merge new content into an
2528 existing hierarchy. */
2529 && (x->move_mode || ! S_ISDIR (dst_sb.st_mode)))
2531 /* Fail if creating the backup file would likely destroy
2532 the source file. Otherwise, the commands:
2533 cd /tmp; rm -f a a~; : > a; echo A > a~; cp --b=simple a~ a
2534 would leave two zero-length files: a and a~. */
2535 if (x->backup_type != numbered_backups
2536 && source_is_dst_backup (srcbase, &src_sb,
2537 dst_dirfd, dst_relname))
2539 char const *fmt;
2540 fmt = (x->move_mode
2541 ? _("backing up %s might destroy source; %s not moved")
2542 : _("backing up %s might destroy source; %s not copied"));
2543 error (0, 0, fmt,
2544 quoteaf_n (0, dst_name),
2545 quoteaf_n (1, src_name));
2546 return false;
2549 char *tmp_backup = backup_file_rename (dst_dirfd, dst_relname,
2550 x->backup_type);
2552 /* FIXME: use fts:
2553 Using alloca for a file name that may be arbitrarily
2554 long is not recommended. In fact, even forming such a name
2555 should be discouraged. Eventually, this code will be rewritten
2556 to use fts, so using alloca here will be less of a problem. */
2557 if (tmp_backup)
2559 idx_t dirlen = dst_relname - dst_name;
2560 idx_t backupsize = strlen (tmp_backup) + 1;
2561 dst_backup = alloca (dirlen + backupsize);
2562 memcpy (mempcpy (dst_backup, dst_name, dirlen),
2563 tmp_backup, backupsize);
2564 free (tmp_backup);
2566 else if (errno != ENOENT)
2568 error (0, errno, _("cannot backup %s"), quoteaf (dst_name));
2569 return false;
2571 new_dst = true;
2573 else if (! S_ISDIR (dst_sb.st_mode)
2574 /* Never unlink dst_name when in move mode. */
2575 && ! x->move_mode
2576 && (x->unlink_dest_before_opening
2577 || (x->data_copy_required
2578 && ((x->preserve_links && 1 < dst_sb.st_nlink)
2579 || (x->dereference == DEREF_NEVER
2580 && ! S_ISREG (src_sb.st_mode))))
2583 if (unlinkat (dst_dirfd, dst_relname, 0) != 0 && errno != ENOENT)
2585 error (0, errno, _("cannot remove %s"), quoteaf (dst_name));
2586 return false;
2588 new_dst = true;
2589 if (x->verbose)
2590 printf (_("removed %s\n"), quoteaf (dst_name));
2595 /* Ensure we don't try to copy through a symlink that was
2596 created by a prior call to this function. */
2597 if (command_line_arg
2598 && x->dest_info
2599 && ! x->move_mode
2600 && x->backup_type == no_backups)
2602 /* If we did not follow symlinks above, good: use that data.
2603 Otherwise, use AT_SYMLINK_NOFOLLOW, in case dst_name is a symlink. */
2604 struct stat tmp_buf;
2605 struct stat *dst_lstat_sb
2606 = (have_dst_lstat ? &dst_sb
2607 : fstatat (dst_dirfd, drelname, &tmp_buf, AT_SYMLINK_NOFOLLOW) < 0
2608 ? nullptr : &tmp_buf);
2610 /* Never copy through a symlink we've just created. */
2611 if (dst_lstat_sb
2612 && S_ISLNK (dst_lstat_sb->st_mode)
2613 && seen_file (x->dest_info, dst_relname, dst_lstat_sb))
2615 error (0, 0,
2616 _("will not copy %s through just-created symlink %s"),
2617 quoteaf_n (0, src_name), quoteaf_n (1, dst_name));
2618 return false;
2622 /* If the source is a directory, we don't always create the destination
2623 directory. So --verbose should not announce anything until we're
2624 sure we'll create a directory. Also don't announce yet when moving
2625 so we can distinguish renames versus copies. */
2626 if (x->verbose && !x->move_mode && !S_ISDIR (src_mode))
2627 emit_verbose (src_name, dst_name, dst_backup);
2629 /* Associate the destination file name with the source device and inode
2630 so that if we encounter a matching dev/ino pair in the source tree
2631 we can arrange to create a hard link between the corresponding names
2632 in the destination tree.
2634 When using the --link (-l) option, there is no need to take special
2635 measures, because (barring race conditions) files that are hard-linked
2636 in the source tree will also be hard-linked in the destination tree.
2638 Sometimes, when preserving links, we have to record dev/ino even
2639 though st_nlink == 1:
2640 - when in move_mode, since we may be moving a group of N hard-linked
2641 files (via two or more command line arguments) to a different
2642 partition; the links may be distributed among the command line
2643 arguments (possibly hierarchies) so that the link count of
2644 the final, once-linked source file is reduced to 1 when it is
2645 considered below. But in this case (for mv) we don't need to
2646 incur the expense of recording the dev/ino => name mapping; all we
2647 really need is a lookup, to see if the dev/ino pair has already
2648 been copied.
2649 - when using -H and processing a command line argument;
2650 that command line argument could be a symlink pointing to another
2651 command line argument. With 'cp -H --preserve=link', we hard-link
2652 those two destination files.
2653 - likewise for -L except that it applies to all files, not just
2654 command line arguments.
2656 Also, with --recursive, record dev/ino of each command-line directory.
2657 We'll use that info to detect this problem: cp -R dir dir. */
2659 if (rename_errno == 0)
2660 earlier_file = nullptr;
2661 else if (x->recursive && S_ISDIR (src_mode))
2663 if (command_line_arg)
2664 earlier_file = remember_copied (dst_relname,
2665 src_sb.st_ino, src_sb.st_dev);
2666 else
2667 earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev);
2669 else if (x->move_mode && src_sb.st_nlink == 1)
2671 earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev);
2673 else if (x->preserve_links
2674 && !x->hard_link
2675 && (1 < src_sb.st_nlink
2676 || (command_line_arg
2677 && x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
2678 || x->dereference == DEREF_ALWAYS))
2680 earlier_file = remember_copied (dst_relname,
2681 src_sb.st_ino, src_sb.st_dev);
2684 /* Did we copy this inode somewhere else (in this command line argument)
2685 and therefore this is a second hard link to the inode? */
2687 if (earlier_file)
2689 /* Avoid damaging the destination file system by refusing to preserve
2690 hard-linked directories (which are found at least in Netapp snapshot
2691 directories). */
2692 if (S_ISDIR (src_mode))
2694 /* If src_name and earlier_file refer to the same directory entry,
2695 then warn about copying a directory into itself. */
2696 if (same_nameat (AT_FDCWD, src_name, dst_dirfd, earlier_file))
2698 error (0, 0, _("cannot copy a directory, %s, into itself, %s"),
2699 quoteaf_n (0, top_level_src_name),
2700 quoteaf_n (1, top_level_dst_name));
2701 *copy_into_self = true;
2702 goto un_backup;
2704 else if (same_nameat (dst_dirfd, dst_relname,
2705 dst_dirfd, earlier_file))
2707 error (0, 0, _("warning: source directory %s "
2708 "specified more than once"),
2709 quoteaf (top_level_src_name));
2710 /* In move mode, if a previous rename succeeded, then
2711 we won't be in this path as the source is missing. If the
2712 rename previously failed, then that has been handled, so
2713 pretend this attempt succeeded so the source isn't removed. */
2714 if (x->move_mode && rename_succeeded)
2715 *rename_succeeded = true;
2716 /* We only do backups in move mode, and for non directories.
2717 So just ignore this repeated entry. */
2718 return true;
2720 else if (x->dereference == DEREF_ALWAYS
2721 || (command_line_arg
2722 && x->dereference == DEREF_COMMAND_LINE_ARGUMENTS))
2724 /* This happens when e.g., encountering a directory for the
2725 second or subsequent time via symlinks when cp is invoked
2726 with -R and -L. E.g.,
2727 rm -rf a b c d; mkdir a b c d; ln -s ../c a; ln -s ../c b;
2728 cp -RL a b d
2731 else
2733 char *earlier = subst_suffix (dst_name, dst_relname,
2734 earlier_file);
2735 error (0, 0, _("will not create hard link %s to directory %s"),
2736 quoteaf_n (0, dst_name), quoteaf_n (1, earlier));
2737 free (earlier);
2738 goto un_backup;
2741 else
2743 if (! create_hard_link (nullptr, dst_dirfd, earlier_file,
2744 dst_name, dst_dirfd, dst_relname,
2745 true, x->verbose, dereference))
2746 goto un_backup;
2748 return true;
2752 if (x->move_mode)
2754 if (rename_errno == EEXIST)
2755 rename_errno = (renameat (AT_FDCWD, src_name, dst_dirfd, drelname) == 0
2756 ? 0 : errno);
2758 if (rename_errno == 0)
2760 if (x->verbose)
2762 printf (_("renamed "));
2763 emit_verbose (src_name, dst_name, dst_backup);
2766 if (x->set_security_context)
2768 /* -Z failures are only warnings currently. */
2769 (void) set_file_security_ctx (dst_name, true, x);
2772 if (rename_succeeded)
2773 *rename_succeeded = true;
2775 if (command_line_arg && !x->last_file)
2777 /* Record destination dev/ino/name, so that if we are asked
2778 to overwrite that file again, we can detect it and fail. */
2779 /* It's fine to use the _source_ stat buffer (src_sb) to get the
2780 _destination_ dev/ino, since the rename above can't have
2781 changed those, and 'mv' always uses lstat.
2782 We could limit it further by operating
2783 only on non-directories. */
2784 record_file (x->dest_info, dst_relname, &src_sb);
2787 return true;
2790 /* FIXME: someday, consider what to do when moving a directory into
2791 itself but when source and destination are on different devices. */
2793 /* This happens when attempting to rename a directory to a
2794 subdirectory of itself. */
2795 if (rename_errno == EINVAL)
2797 /* FIXME: this is a little fragile in that it relies on rename(2)
2798 failing with a specific errno value. Expect problems on
2799 non-POSIX systems. */
2800 error (0, 0, _("cannot move %s to a subdirectory of itself, %s"),
2801 quoteaf_n (0, top_level_src_name),
2802 quoteaf_n (1, top_level_dst_name));
2804 /* Note that there is no need to call forget_created here,
2805 (compare with the other calls in this file) since the
2806 destination directory didn't exist before. */
2808 *copy_into_self = true;
2809 /* FIXME-cleanup: Don't return true here; adjust mv.c accordingly.
2810 The only caller that uses this code (mv.c) ends up setting its
2811 exit status to nonzero when copy_into_self is nonzero. */
2812 return true;
2815 /* WARNING: there probably exist systems for which an inter-device
2816 rename fails with a value of errno not handled here.
2817 If/as those are reported, add them to the condition below.
2818 If this happens to you, please do the following and send the output
2819 to the bug-reporting address (e.g., in the output of cp --help):
2820 touch k; perl -e 'rename "k","/tmp/k" or print "$!(",$!+0,")\n"'
2821 where your current directory is on one partition and /tmp is the other.
2822 Also, please try to find the E* errno macro name corresponding to
2823 the diagnostic and parenthesized integer, and include that in your
2824 e-mail. One way to do that is to run a command like this
2825 find /usr/include/. -type f \
2826 | xargs grep 'define.*\<E[A-Z]*\>.*\<18\>' /dev/null
2827 where you'd replace '18' with the integer in parentheses that
2828 was output from the perl one-liner above.
2829 If necessary, of course, change '/tmp' to some other directory. */
2830 if (rename_errno != EXDEV || x->no_copy)
2832 /* There are many ways this can happen due to a race condition.
2833 When something happens between the initial follow_fstatat and the
2834 subsequent rename, we can get many different types of errors.
2835 For example, if the destination is initially a non-directory
2836 or non-existent, but it is created as a directory, the rename
2837 fails. If two 'mv' commands try to rename the same file at
2838 about the same time, one will succeed and the other will fail.
2839 If the permissions on the directory containing the source or
2840 destination file are made too restrictive, the rename will
2841 fail. Etc. */
2842 char const *quoted_dst_name = quoteaf_n (1, dst_name);
2843 switch (rename_errno)
2845 case EDQUOT: case EEXIST: case EISDIR: case EMLINK:
2846 case ENOSPC: case ETXTBSY:
2847 #if ENOTEMPTY != EEXIST
2848 case ENOTEMPTY:
2849 #endif
2850 /* The destination must be the problem. Don't mention
2851 the source as that is more likely to confuse the user
2852 than be helpful. */
2853 error (0, rename_errno, _("cannot overwrite %s"),
2854 quoted_dst_name);
2855 break;
2857 default:
2858 error (0, rename_errno, _("cannot move %s to %s"),
2859 quoteaf_n (0, src_name), quoted_dst_name);
2860 break;
2862 forget_created (src_sb.st_ino, src_sb.st_dev);
2863 return false;
2866 /* The rename attempt has failed. Remove any existing destination
2867 file so that a cross-device 'mv' acts as if it were really using
2868 the rename syscall. Note both src and dst must both be directories
2869 or not, and this is enforced above. Therefore we check the src_mode
2870 and operate on dst_name here as a tighter constraint and also because
2871 src_mode is readily available here. */
2872 if ((unlinkat (dst_dirfd, drelname,
2873 S_ISDIR (src_mode) ? AT_REMOVEDIR : 0)
2874 != 0)
2875 && errno != ENOENT)
2877 error (0, errno,
2878 _("inter-device move failed: %s to %s; unable to remove target"),
2879 quoteaf_n (0, src_name), quoteaf_n (1, dst_name));
2880 forget_created (src_sb.st_ino, src_sb.st_dev);
2881 return false;
2884 if (x->verbose && !S_ISDIR (src_mode))
2886 printf (_("copied "));
2887 emit_verbose (src_name, dst_name, dst_backup);
2889 new_dst = true;
2892 /* If the ownership might change, or if it is a directory (whose
2893 special mode bits may change after the directory is created),
2894 omit some permissions at first, so unauthorized users cannot nip
2895 in before the file is ready. */
2896 dst_mode_bits = (x->set_mode ? x->mode : src_mode) & CHMOD_MODE_BITS;
2897 omitted_permissions =
2898 (dst_mode_bits
2899 & (x->preserve_ownership ? S_IRWXG | S_IRWXO
2900 : S_ISDIR (src_mode) ? S_IWGRP | S_IWOTH
2901 : 0));
2903 delayed_ok = true;
2905 /* If required, set the default security context for new files.
2906 Also for existing files this is used as a reference
2907 when copying the context with --preserve=context.
2908 FIXME: Do we need to consider dst_mode_bits here? */
2909 if (! set_process_security_ctx (src_name, dst_name, src_mode, new_dst, x))
2910 return false;
2912 if (S_ISDIR (src_mode))
2914 struct dir_list *dir;
2916 /* If this directory has been copied before during the
2917 recursion, there is a symbolic link to an ancestor
2918 directory of the symbolic link. It is impossible to
2919 continue to copy this, unless we've got an infinite file system. */
2921 if (is_ancestor (&src_sb, ancestors))
2923 error (0, 0, _("cannot copy cyclic symbolic link %s"),
2924 quoteaf (src_name));
2925 goto un_backup;
2928 /* Insert the current directory in the list of parents. */
2930 dir = alloca (sizeof *dir);
2931 dir->parent = ancestors;
2932 dir->ino = src_sb.st_ino;
2933 dir->dev = src_sb.st_dev;
2935 if (new_dst || !S_ISDIR (dst_sb.st_mode))
2937 /* POSIX says mkdir's behavior is implementation-defined when
2938 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
2939 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
2940 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
2941 mode_t mode = dst_mode_bits & ~omitted_permissions;
2942 if (mkdirat (dst_dirfd, drelname, mode) != 0)
2944 error (0, errno, _("cannot create directory %s"),
2945 quoteaf (dst_name));
2946 goto un_backup;
2949 /* We need search and write permissions to the new directory
2950 for writing the directory's contents. Check if these
2951 permissions are there. */
2953 if (fstatat (dst_dirfd, drelname, &dst_sb, AT_SYMLINK_NOFOLLOW) != 0)
2955 error (0, errno, _("cannot stat %s"), quoteaf (dst_name));
2956 goto un_backup;
2958 else if ((dst_sb.st_mode & S_IRWXU) != S_IRWXU)
2960 /* Make the new directory searchable and writable. */
2962 dst_mode = dst_sb.st_mode;
2963 restore_dst_mode = true;
2965 if (lchmodat (dst_dirfd, drelname, dst_mode | S_IRWXU) != 0)
2967 error (0, errno, _("setting permissions for %s"),
2968 quoteaf (dst_name));
2969 goto un_backup;
2973 /* Record the created directory's inode and device numbers into
2974 the search structure, so that we can avoid copying it again.
2975 Do this only for the first directory that is created for each
2976 source command line argument. */
2977 if (!*first_dir_created_per_command_line_arg)
2979 remember_copied (dst_relname, dst_sb.st_ino, dst_sb.st_dev);
2980 *first_dir_created_per_command_line_arg = true;
2983 if (x->verbose)
2985 if (x->move_mode)
2986 printf (_("created directory %s\n"), quoteaf (dst_name));
2987 else
2988 emit_verbose (src_name, dst_name, nullptr);
2991 else
2993 omitted_permissions = 0;
2995 /* For directories, the process global context could be reset for
2996 descendants, so use it to set the context for existing dirs here.
2997 This will also give earlier indication of failure to set ctx. */
2998 if (x->set_security_context || x->preserve_security_context)
2999 if (! set_file_security_ctx (dst_name, false, x))
3001 if (x->require_preserve_context)
3002 goto un_backup;
3006 /* Decide whether to copy the contents of the directory. */
3007 if (x->one_file_system && parent && parent->st_dev != src_sb.st_dev)
3009 /* Here, we are crossing a file system boundary and cp's -x option
3010 is in effect: so don't copy the contents of this directory. */
3012 else
3014 /* Copy the contents of the directory. Don't just return if
3015 this fails -- otherwise, the failure to read a single file
3016 in a source directory would cause the containing destination
3017 directory not to have owner/perms set properly. */
3018 delayed_ok = copy_dir (src_name, dst_name, dst_dirfd, dst_relname,
3019 new_dst, &src_sb, dir, x,
3020 first_dir_created_per_command_line_arg,
3021 copy_into_self);
3024 else if (x->symbolic_link)
3026 dest_is_symlink = true;
3027 if (*src_name != '/')
3029 /* Check that DST_NAME denotes a file in the current directory. */
3030 struct stat dot_sb;
3031 struct stat dst_parent_sb;
3032 char *dst_parent;
3033 bool in_current_dir;
3035 dst_parent = dir_name (dst_relname);
3037 in_current_dir = ((dst_dirfd == AT_FDCWD && STREQ (".", dst_parent))
3038 /* If either stat call fails, it's ok not to report
3039 the failure and say dst_name is in the current
3040 directory. Other things will fail later. */
3041 || stat (".", &dot_sb) != 0
3042 || (fstatat (dst_dirfd, dst_parent, &dst_parent_sb,
3043 0) != 0)
3044 || psame_inode (&dot_sb, &dst_parent_sb));
3045 free (dst_parent);
3047 if (! in_current_dir)
3049 error (0, 0,
3050 _("%s: can make relative symbolic links only in current directory"),
3051 quotef (dst_name));
3052 goto un_backup;
3056 int err = force_symlinkat (src_name, dst_dirfd, dst_relname,
3057 x->unlink_dest_after_failed_open, -1);
3058 if (0 < err)
3060 error (0, err, _("cannot create symbolic link %s to %s"),
3061 quoteaf_n (0, dst_name), quoteaf_n (1, src_name));
3062 goto un_backup;
3066 /* POSIX 2008 states that it is implementation-defined whether
3067 link() on a symlink creates a hard-link to the symlink, or only
3068 to the referent (effectively dereferencing the symlink) (POSIX
3069 2001 required the latter behavior, although many systems provided
3070 the former). Yet cp, invoked with '--link --no-dereference',
3071 should not follow the link. We can approximate the desired
3072 behavior by skipping this hard-link creating block and instead
3073 copying the symlink, via the 'S_ISLNK'- copying code below.
3075 Note gnulib's linkat module, guarantees that the symlink is not
3076 dereferenced. However its emulation currently doesn't maintain
3077 timestamps or ownership so we only call it when we know the
3078 emulation will not be needed. */
3079 else if (x->hard_link
3080 && !(! CAN_HARDLINK_SYMLINKS && S_ISLNK (src_mode)
3081 && x->dereference == DEREF_NEVER))
3083 bool replace = (x->unlink_dest_after_failed_open
3084 || x->interactive == I_ASK_USER);
3085 if (! create_hard_link (src_name, AT_FDCWD, src_name,
3086 dst_name, dst_dirfd, dst_relname,
3087 replace, false, dereference))
3088 goto un_backup;
3090 else if (S_ISREG (src_mode)
3091 || (x->copy_as_regular && !S_ISLNK (src_mode)))
3093 copied_as_regular = true;
3094 /* POSIX says the permission bits of the source file must be
3095 used as the 3rd argument in the open call. Historical
3096 practice passed all the source mode bits to 'open', but the extra
3097 bits were ignored, so it should be the same either way.
3099 This call uses DST_MODE_BITS, not SRC_MODE. These are
3100 normally the same, and the exception (where x->set_mode) is
3101 used only by 'install', which POSIX does not specify and
3102 where DST_MODE_BITS is what's wanted. */
3103 if (! copy_reg (src_name, dst_name, dst_dirfd, dst_relname,
3104 x, dst_mode_bits & S_IRWXUGO,
3105 omitted_permissions, &new_dst, &src_sb))
3106 goto un_backup;
3108 else if (S_ISFIFO (src_mode))
3110 /* Use mknodat, rather than mkfifoat, because the former preserves
3111 the special mode bits of a fifo on Solaris 10, while mkfifoat
3112 does not. But fall back on mkfifoat, because on some BSD systems,
3113 mknodat always fails when asked to create a FIFO. */
3114 mode_t mode = src_mode & ~omitted_permissions;
3115 if (mknodat (dst_dirfd, dst_relname, mode, 0) != 0)
3116 if (mkfifoat (dst_dirfd, dst_relname, mode & ~S_IFIFO) != 0)
3118 error (0, errno, _("cannot create fifo %s"), quoteaf (dst_name));
3119 goto un_backup;
3122 else if (S_ISBLK (src_mode) || S_ISCHR (src_mode) || S_ISSOCK (src_mode))
3124 mode_t mode = src_mode & ~omitted_permissions;
3125 if (mknodat (dst_dirfd, dst_relname, mode, src_sb.st_rdev) != 0)
3127 error (0, errno, _("cannot create special file %s"),
3128 quoteaf (dst_name));
3129 goto un_backup;
3132 else if (S_ISLNK (src_mode))
3134 char *src_link_val = areadlink_with_size (src_name, src_sb.st_size);
3135 dest_is_symlink = true;
3136 if (src_link_val == nullptr)
3138 error (0, errno, _("cannot read symbolic link %s"),
3139 quoteaf (src_name));
3140 goto un_backup;
3143 int symlink_err = force_symlinkat (src_link_val, dst_dirfd, dst_relname,
3144 x->unlink_dest_after_failed_open, -1);
3145 if (0 < symlink_err && x->update && !new_dst && S_ISLNK (dst_sb.st_mode)
3146 && dst_sb.st_size == strlen (src_link_val))
3148 /* See if the destination is already the desired symlink.
3149 FIXME: This behavior isn't documented, and seems wrong
3150 in some cases, e.g., if the destination symlink has the
3151 wrong ownership, permissions, or timestamps. */
3152 char *dest_link_val =
3153 areadlinkat_with_size (dst_dirfd, dst_relname, dst_sb.st_size);
3154 if (dest_link_val)
3156 if (STREQ (dest_link_val, src_link_val))
3157 symlink_err = 0;
3158 free (dest_link_val);
3161 free (src_link_val);
3162 if (0 < symlink_err)
3164 error (0, symlink_err, _("cannot create symbolic link %s"),
3165 quoteaf (dst_name));
3166 goto un_backup;
3169 if (x->preserve_security_context)
3170 restore_default_fscreatecon_or_die ();
3172 if (x->preserve_ownership)
3174 /* Preserve the owner and group of the just-'copied'
3175 symbolic link, if possible. */
3176 if (HAVE_LCHOWN
3177 && (lchownat (dst_dirfd, dst_relname,
3178 src_sb.st_uid, src_sb.st_gid)
3179 != 0)
3180 && ! chown_failure_ok (x))
3182 error (0, errno, _("failed to preserve ownership for %s"),
3183 dst_name);
3184 if (x->require_preserve)
3185 goto un_backup;
3187 else
3189 /* Can't preserve ownership of symlinks.
3190 FIXME: maybe give a warning or even error for symlinks
3191 in directories with the sticky bit set -- there, not
3192 preserving owner/group is a potential security problem. */
3196 else
3198 error (0, 0, _("%s has unknown file type"), quoteaf (src_name));
3199 goto un_backup;
3202 /* With -Z or --preserve=context, set the context for existing files.
3203 Note this is done already for copy_reg() for reasons described therein. */
3204 if (!new_dst && !x->copy_as_regular && !S_ISDIR (src_mode)
3205 && (x->set_security_context || x->preserve_security_context))
3207 if (! set_file_security_ctx (dst_name, false, x))
3209 if (x->require_preserve_context)
3210 goto un_backup;
3214 if (command_line_arg && x->dest_info)
3216 /* Now that the destination file is very likely to exist,
3217 add its info to the set. */
3218 struct stat sb;
3219 if (fstatat (dst_dirfd, drelname, &sb, AT_SYMLINK_NOFOLLOW) == 0)
3220 record_file (x->dest_info, dst_relname, &sb);
3223 /* If we've just created a hard-link due to cp's --link option,
3224 we're done. */
3225 if (x->hard_link && ! S_ISDIR (src_mode)
3226 && !(! CAN_HARDLINK_SYMLINKS && S_ISLNK (src_mode)
3227 && x->dereference == DEREF_NEVER))
3228 return delayed_ok;
3230 if (copied_as_regular)
3231 return delayed_ok;
3233 /* POSIX says that 'cp -p' must restore the following:
3234 - permission bits
3235 - setuid, setgid bits
3236 - owner and group
3237 If it fails to restore any of those, we may give a warning but
3238 the destination must not be removed.
3239 FIXME: implement the above. */
3241 /* Adjust the times (and if possible, ownership) for the copy.
3242 chown turns off set[ug]id bits for non-root,
3243 so do the chmod last. */
3245 if (x->preserve_timestamps)
3247 struct timespec timespec[2];
3248 timespec[0] = get_stat_atime (&src_sb);
3249 timespec[1] = get_stat_mtime (&src_sb);
3251 int utimensat_flags = dest_is_symlink ? AT_SYMLINK_NOFOLLOW : 0;
3252 if (utimensat (dst_dirfd, drelname, timespec, utimensat_flags) != 0)
3254 error (0, errno, _("preserving times for %s"), quoteaf (dst_name));
3255 if (x->require_preserve)
3256 return false;
3260 /* Avoid calling chown if we know it's not necessary. */
3261 if (!dest_is_symlink && x->preserve_ownership
3262 && (new_dst || !SAME_OWNER_AND_GROUP (src_sb, dst_sb)))
3264 switch (set_owner (x, dst_name, dst_dirfd, drelname, -1,
3265 &src_sb, new_dst, &dst_sb))
3267 case -1:
3268 return false;
3270 case 0:
3271 src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX);
3272 break;
3276 /* Set xattrs after ownership as changing owners will clear capabilities. */
3277 if (x->preserve_xattr && ! copy_attr (src_name, -1, dst_name, -1, x)
3278 && x->require_preserve_xattr)
3279 return false;
3281 /* The operations beyond this point may dereference a symlink. */
3282 if (dest_is_symlink)
3283 return delayed_ok;
3285 set_author (dst_name, -1, &src_sb);
3287 if (x->preserve_mode || x->move_mode)
3289 if (copy_acl (src_name, -1, dst_name, -1, src_mode) != 0
3290 && x->require_preserve)
3291 return false;
3293 else if (x->set_mode)
3295 if (set_acl (dst_name, -1, x->mode) != 0)
3296 return false;
3298 else if (x->explicit_no_preserve_mode && new_dst)
3300 int default_permissions = S_ISDIR (src_mode) || S_ISSOCK (src_mode)
3301 ? S_IRWXUGO : MODE_RW_UGO;
3302 if (set_acl (dst_name, -1, default_permissions & ~cached_umask ()) != 0)
3303 return false;
3305 else
3307 if (omitted_permissions)
3309 omitted_permissions &= ~ cached_umask ();
3311 if (omitted_permissions && !restore_dst_mode)
3313 /* Permissions were deliberately omitted when the file
3314 was created due to security concerns. See whether
3315 they need to be re-added now. It'd be faster to omit
3316 the lstat, but deducing the current destination mode
3317 is tricky in the presence of implementation-defined
3318 rules for special mode bits. */
3319 if (new_dst && (fstatat (dst_dirfd, drelname, &dst_sb,
3320 AT_SYMLINK_NOFOLLOW)
3321 != 0))
3323 error (0, errno, _("cannot stat %s"), quoteaf (dst_name));
3324 return false;
3326 dst_mode = dst_sb.st_mode;
3327 if (omitted_permissions & ~dst_mode)
3328 restore_dst_mode = true;
3332 if (restore_dst_mode)
3334 if (lchmodat (dst_dirfd, drelname, dst_mode | omitted_permissions)
3335 != 0)
3337 error (0, errno, _("preserving permissions for %s"),
3338 quoteaf (dst_name));
3339 if (x->require_preserve)
3340 return false;
3345 return delayed_ok;
3347 un_backup:
3349 if (x->preserve_security_context)
3350 restore_default_fscreatecon_or_die ();
3352 /* We have failed to create the destination file.
3353 If we've just added a dev/ino entry via the remember_copied
3354 call above (i.e., unless we've just failed to create a hard link),
3355 remove the entry associating the source dev/ino with the
3356 destination file name, so we don't try to 'preserve' a link
3357 to a file we didn't create. */
3358 if (earlier_file == nullptr)
3359 forget_created (src_sb.st_ino, src_sb.st_dev);
3361 if (dst_backup)
3363 char const *dst_relbackup = &dst_backup[dst_relname - dst_name];
3364 if (renameat (dst_dirfd, dst_relbackup, dst_dirfd, drelname) != 0)
3365 error (0, errno, _("cannot un-backup %s"), quoteaf (dst_name));
3366 else
3368 if (x->verbose)
3369 printf (_("%s -> %s (unbackup)\n"),
3370 quoteaf_n (0, dst_backup), quoteaf_n (1, dst_name));
3373 return false;
3376 static void
3377 valid_options (const struct cp_options *co)
3379 affirm (VALID_BACKUP_TYPE (co->backup_type));
3380 affirm (VALID_SPARSE_MODE (co->sparse_mode));
3381 affirm (VALID_REFLINK_MODE (co->reflink_mode));
3382 affirm (!(co->hard_link && co->symbolic_link));
3383 affirm (!
3384 (co->reflink_mode == REFLINK_ALWAYS
3385 && co->sparse_mode != SPARSE_AUTO));
3388 /* Copy the file SRC_NAME to the file DST_NAME aka DST_DIRFD+DST_RELNAME.
3389 If NONEXISTENT_DST is positive, DST_NAME does not exist even as a
3390 dangling symlink; if negative, it does not exist except possibly
3391 as a dangling symlink; if zero, its existence status is unknown.
3392 OPTIONS summarizes the command-line options.
3393 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
3394 same as) DST_NAME; otherwise, set clear it.
3395 If X->move_mode, set *RENAME_SUCCEEDED according to whether
3396 the source was simply renamed to the destination.
3397 Return true if successful. */
3399 extern bool
3400 copy (char const *src_name, char const *dst_name,
3401 int dst_dirfd, char const *dst_relname,
3402 int nonexistent_dst, const struct cp_options *options,
3403 bool *copy_into_self, bool *rename_succeeded)
3405 valid_options (options);
3407 /* Record the file names: they're used in case of error, when copying
3408 a directory into itself. I don't like to make these tools do *any*
3409 extra work in the common case when that work is solely to handle
3410 exceptional cases, but in this case, I don't see a way to derive the
3411 top level source and destination directory names where they're used.
3412 An alternative is to use COPY_INTO_SELF and print the diagnostic
3413 from every caller -- but I don't want to do that. */
3414 top_level_src_name = src_name;
3415 top_level_dst_name = dst_name;
3417 bool first_dir_created_per_command_line_arg = false;
3418 return copy_internal (src_name, dst_name, dst_dirfd, dst_relname,
3419 nonexistent_dst, nullptr, nullptr,
3420 options, true,
3421 &first_dir_created_per_command_line_arg,
3422 copy_into_self, rename_succeeded);
3425 /* Set *X to the default options for a value of type struct cp_options. */
3427 extern void
3428 cp_options_default (struct cp_options *x)
3430 memset (x, 0, sizeof *x);
3431 #ifdef PRIV_FILE_CHOWN
3433 priv_set_t *pset = priv_allocset ();
3434 if (!pset)
3435 xalloc_die ();
3436 if (getppriv (PRIV_EFFECTIVE, pset) == 0)
3438 x->chown_privileges = priv_ismember (pset, PRIV_FILE_CHOWN);
3439 x->owner_privileges = priv_ismember (pset, PRIV_FILE_OWNER);
3441 priv_freeset (pset);
3443 #else
3444 x->chown_privileges = x->owner_privileges = (geteuid () == ROOT_UID);
3445 #endif
3446 x->rename_errno = -1;
3449 /* Return true if it's OK for chown to fail, where errno is
3450 the error number that chown failed with and X is the copying
3451 option set. */
3453 extern bool
3454 chown_failure_ok (struct cp_options const *x)
3456 /* If non-root uses -p, it's ok if we can't preserve ownership.
3457 But root probably wants to know, e.g. if NFS disallows it,
3458 or if the target system doesn't support file ownership.
3460 Treat EACCES like EPERM and EINVAL to work around a bug in Linux
3461 CIFS <https://bugs.gnu.org/65599>. Although this means coreutils
3462 will ignore EACCES errors that it should report, problems should
3463 occur only when some other process is racing with coreutils and
3464 coreutils is not immune to races anyway. */
3466 return ((errno == EPERM || errno == EINVAL || errno == EACCES)
3467 && !x->chown_privileges);
3470 /* Similarly, return true if it's OK for chmod and similar operations
3471 to fail, where errno is the error number that chmod failed with and
3472 X is the copying option set. */
3474 static bool
3475 owner_failure_ok (struct cp_options const *x)
3477 return ((errno == EPERM || errno == EINVAL || errno == EACCES)
3478 && !x->owner_privileges);
3481 /* Return the user's umask, caching the result.
3483 FIXME: If the destination's parent directory has has a default ACL,
3484 some operating systems (e.g., GNU/Linux's "POSIX" ACLs) use that
3485 ACL's mask rather than the process umask. Currently, the callers
3486 of cached_umask incorrectly assume that this situation cannot occur. */
3487 extern mode_t
3488 cached_umask (void)
3490 static mode_t mask = (mode_t) -1;
3491 if (mask == (mode_t) -1)
3493 mask = umask (0);
3494 umask (mask);
3496 return mask;