shuf: tiny simplification
[coreutils.git] / src / copy.c
blobd584a27eb5acda5ba76209218fc97ad6362ffd2e
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 *format, char const *src, char const *dst,
2079 char const *backup_dst_name)
2081 printf (format, quoteaf_n (0, src), quoteaf_n (1, dst));
2082 if (backup_dst_name)
2083 printf (_(" (backup: %s)"), quoteaf (backup_dst_name));
2084 putchar ('\n');
2087 /* A wrapper around "setfscreatecon (nullptr)" that exits upon failure. */
2088 static void
2089 restore_default_fscreatecon_or_die (void)
2091 if (setfscreatecon (nullptr) != 0)
2092 error (EXIT_FAILURE, errno,
2093 _("failed to restore the default file creation context"));
2096 /* Return a newly-allocated string that is like STR
2097 except replace its suffix SUFFIX with NEWSUFFIX. */
2098 static char *
2099 subst_suffix (char const *str, char const *suffix, char const *newsuffix)
2101 idx_t prefixlen = suffix - str;
2102 idx_t newsuffixsize = strlen (newsuffix) + 1;
2103 char *r = ximalloc (prefixlen + newsuffixsize);
2104 memcpy (r + prefixlen, newsuffix, newsuffixsize);
2105 return memcpy (r, str, prefixlen);
2108 /* Create a hard link to SRC_NAME aka SRC_DIRFD+SRC_RELNAME;
2109 the new link is at DST_NAME aka DST_DIRFD+DST_RELNAME.
2110 A null SRC_NAME stands for the file whose name is like DST_NAME
2111 except with DST_RELNAME replaced with SRC_RELNAME.
2112 Honor the REPLACE, VERBOSE and DEREFERENCE settings.
2113 Return true upon success. Otherwise, diagnose the
2114 failure and return false. If SRC_NAME is a symbolic link, then it will not
2115 be followed unless DEREFERENCE is true.
2116 If the system doesn't support hard links to symbolic links, then DST_NAME
2117 will be created as a symbolic link to SRC_NAME. */
2118 static bool
2119 create_hard_link (char const *src_name, int src_dirfd, char const *src_relname,
2120 char const *dst_name, int dst_dirfd, char const *dst_relname,
2121 bool replace, bool verbose, bool dereference)
2123 int err = force_linkat (src_dirfd, src_relname, dst_dirfd, dst_relname,
2124 dereference ? AT_SYMLINK_FOLLOW : 0,
2125 replace, -1);
2126 if (0 < err)
2129 char *a_src_name = nullptr;
2130 if (!src_name)
2131 src_name = a_src_name = subst_suffix (dst_name, dst_relname,
2132 src_relname);
2133 error (0, err, _("cannot create hard link %s to %s"),
2134 quoteaf_n (0, dst_name), quoteaf_n (1, src_name));
2135 free (a_src_name);
2136 return false;
2138 if (err < 0 && verbose)
2139 printf (_("removed %s\n"), quoteaf (dst_name));
2140 return true;
2143 /* Return true if the current file should be (tried to be) dereferenced:
2144 either for DEREF_ALWAYS or for DEREF_COMMAND_LINE_ARGUMENTS in the case
2145 where the current file is a COMMAND_LINE_ARG; otherwise return false. */
2146 ATTRIBUTE_PURE
2147 static inline bool
2148 should_dereference (const struct cp_options *x, bool command_line_arg)
2150 return x->dereference == DEREF_ALWAYS
2151 || (x->dereference == DEREF_COMMAND_LINE_ARGUMENTS
2152 && command_line_arg);
2155 /* Return true if the source file with basename SRCBASE and status SRC_ST
2156 is likely to be the simple backup file for DST_DIRFD+DST_RELNAME. */
2157 static bool
2158 source_is_dst_backup (char const *srcbase, struct stat const *src_st,
2159 int dst_dirfd, char const *dst_relname)
2161 size_t srcbaselen = strlen (srcbase);
2162 char const *dstbase = last_component (dst_relname);
2163 size_t dstbaselen = strlen (dstbase);
2164 size_t suffixlen = strlen (simple_backup_suffix);
2165 if (! (srcbaselen == dstbaselen + suffixlen
2166 && memcmp (srcbase, dstbase, dstbaselen) == 0
2167 && STREQ (srcbase + dstbaselen, simple_backup_suffix)))
2168 return false;
2169 char *dst_back = subst_suffix (dst_relname,
2170 dst_relname + strlen (dst_relname),
2171 simple_backup_suffix);
2172 struct stat dst_back_sb;
2173 int dst_back_status = fstatat (dst_dirfd, dst_back, &dst_back_sb, 0);
2174 free (dst_back);
2175 return dst_back_status == 0 && psame_inode (src_st, &dst_back_sb);
2178 /* Copy the file SRC_NAME to the file DST_NAME aka DST_DIRFD+DST_RELNAME.
2179 If NONEXISTENT_DST is positive, DST_NAME does not exist even as a
2180 dangling symlink; if negative, it does not exist except possibly
2181 as a dangling symlink; if zero, its existence status is unknown.
2182 A non-null PARENT describes the parent directory.
2183 ANCESTORS points to a linked, null terminated list of
2184 devices and inodes of parent directories of SRC_NAME.
2185 X summarizes the command-line options.
2186 COMMAND_LINE_ARG means SRC_NAME was specified on the command line.
2187 FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG is both input and output.
2188 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
2189 same as) DST_NAME; otherwise, clear it.
2190 If X->move_mode, set *RENAME_SUCCEEDED according to whether
2191 the source was simply renamed to the destination.
2192 Return true if successful. */
2193 static bool
2194 copy_internal (char const *src_name, char const *dst_name,
2195 int dst_dirfd, char const *dst_relname,
2196 int nonexistent_dst,
2197 struct stat const *parent,
2198 struct dir_list *ancestors,
2199 const struct cp_options *x,
2200 bool command_line_arg,
2201 bool *first_dir_created_per_command_line_arg,
2202 bool *copy_into_self,
2203 bool *rename_succeeded)
2205 struct stat src_sb;
2206 struct stat dst_sb;
2207 mode_t src_mode IF_LINT ( = 0);
2208 mode_t dst_mode IF_LINT ( = 0);
2209 mode_t dst_mode_bits;
2210 mode_t omitted_permissions;
2211 bool restore_dst_mode = false;
2212 char *earlier_file = nullptr;
2213 char *dst_backup = nullptr;
2214 char const *drelname = *dst_relname ? dst_relname : ".";
2215 bool delayed_ok;
2216 bool copied_as_regular = false;
2217 bool dest_is_symlink = false;
2218 bool have_dst_lstat = false;
2220 *copy_into_self = false;
2222 int rename_errno = x->rename_errno;
2223 if (x->move_mode && !x->exchange)
2225 if (rename_errno < 0)
2226 rename_errno = (renameatu (AT_FDCWD, src_name, dst_dirfd, drelname,
2227 RENAME_NOREPLACE)
2228 ? errno : 0);
2229 nonexistent_dst = *rename_succeeded = rename_errno == 0;
2232 if (rename_errno == 0
2233 ? !x->last_file
2234 : rename_errno != EEXIST
2235 || (x->interactive != I_ALWAYS_NO && x->interactive != I_ALWAYS_SKIP))
2237 char const *name = rename_errno == 0 ? dst_name : src_name;
2238 int dirfd = rename_errno == 0 ? dst_dirfd : AT_FDCWD;
2239 char const *relname = rename_errno == 0 ? drelname : src_name;
2240 int fstatat_flags
2241 = x->dereference == DEREF_NEVER ? AT_SYMLINK_NOFOLLOW : 0;
2242 if (follow_fstatat (dirfd, relname, &src_sb, fstatat_flags) != 0)
2244 error (0, errno, _("cannot stat %s"), quoteaf (name));
2245 return false;
2248 src_mode = src_sb.st_mode;
2250 if (S_ISDIR (src_mode) && !x->recursive)
2252 error (0, 0, ! x->install_mode /* cp */
2253 ? _("-r not specified; omitting directory %s")
2254 : _("omitting directory %s"),
2255 quoteaf (src_name));
2256 return false;
2259 else
2261 #if defined lint && (defined __clang__ || defined __COVERITY__)
2262 affirm (x->move_mode);
2263 memset (&src_sb, 0, sizeof src_sb);
2264 #endif
2267 /* Detect the case in which the same source file appears more than
2268 once on the command line and no backup option has been selected.
2269 If so, simply warn and don't copy it the second time.
2270 This check is enabled only if x->src_info is non-null. */
2271 if (command_line_arg && x->src_info)
2273 if ( ! S_ISDIR (src_mode)
2274 && x->backup_type == no_backups
2275 && seen_file (x->src_info, src_name, &src_sb))
2277 error (0, 0, _("warning: source file %s specified more than once"),
2278 quoteaf (src_name));
2279 return true;
2282 record_file (x->src_info, src_name, &src_sb);
2285 bool dereference = should_dereference (x, command_line_arg);
2287 /* Whether the destination is (or was) known to be new, updated as
2288 more info comes in. This may become true if the destination is a
2289 dangling symlink, in contexts where dangling symlinks should be
2290 treated the same as nonexistent files. */
2291 bool new_dst = 0 < nonexistent_dst;
2293 if (! new_dst)
2295 /* Normally, fill in DST_SB or set NEW_DST so that later code
2296 can use DST_SB if NEW_DST is false. However, don't bother
2297 doing this when rename_errno == EEXIST and X->interactive is
2298 I_ALWAYS_NO or I_ALWAYS_SKIP, something that can happen only
2299 with mv in which case x->update must be false which means
2300 that even if !NEW_DST the move will be abandoned without
2301 looking at DST_SB. */
2302 if (! (rename_errno == EEXIST
2303 && (x->interactive == I_ALWAYS_NO
2304 || x->interactive == I_ALWAYS_SKIP)))
2306 /* Regular files can be created by writing through symbolic
2307 links, but other files cannot. So use stat on the
2308 destination when copying a regular file, and lstat otherwise.
2309 However, if we intend to unlink or remove the destination
2310 first, use lstat, since a copy won't actually be made to the
2311 destination in that case. */
2312 bool use_lstat
2313 = ((! S_ISREG (src_mode)
2314 && (! x->copy_as_regular
2315 || (S_ISDIR (src_mode) && !x->keep_directory_symlink)
2316 || S_ISLNK (src_mode)))
2317 || x->move_mode || x->symbolic_link || x->hard_link
2318 || x->backup_type != no_backups
2319 || x->unlink_dest_before_opening);
2320 if (!use_lstat && nonexistent_dst < 0)
2321 new_dst = true;
2322 else if (0 <= follow_fstatat (dst_dirfd, drelname, &dst_sb,
2323 use_lstat ? AT_SYMLINK_NOFOLLOW : 0))
2325 have_dst_lstat = use_lstat;
2326 rename_errno = EEXIST;
2328 else if (errno == ENOENT)
2329 new_dst = true;
2330 else if (errno == ELOOP && !use_lstat
2331 && x->unlink_dest_after_failed_open)
2333 /* cp -f's destination might be a symlink loop.
2334 Leave new_dst=false so that we try to unlink later. */
2336 else
2338 error (0, errno, _("cannot stat %s"), quoteaf (dst_name));
2339 return false;
2343 if (rename_errno == EEXIST)
2345 bool return_now = false;
2346 bool return_val = true;
2347 bool skipped = false;
2349 if ((x->interactive != I_ALWAYS_NO && x->interactive != I_ALWAYS_SKIP)
2350 && ! same_file_ok (src_name, &src_sb, dst_dirfd, drelname,
2351 &dst_sb, x, &return_now))
2353 error (0, 0, _("%s and %s are the same file"),
2354 quoteaf_n (0, src_name), quoteaf_n (1, dst_name));
2355 return false;
2358 if (x->update && !S_ISDIR (src_mode))
2360 /* When preserving timestamps (but not moving within a file
2361 system), don't worry if the destination timestamp is
2362 less than the source merely because of timestamp
2363 truncation. */
2364 int options = ((x->preserve_timestamps
2365 && ! (x->move_mode
2366 && dst_sb.st_dev == src_sb.st_dev))
2367 ? UTIMECMP_TRUNCATE_SOURCE
2368 : 0);
2370 if (0 <= utimecmpat (dst_dirfd, dst_relname, &dst_sb,
2371 &src_sb, options))
2373 /* We're using --update and the destination is not older
2374 than the source, so do not copy or move. Pretend the
2375 rename succeeded, so the caller (if it's mv) doesn't
2376 end up removing the source file. */
2377 if (rename_succeeded)
2378 *rename_succeeded = true;
2380 /* However, we still must record that we've processed
2381 this src/dest pair, in case this source file is
2382 hard-linked to another one. In that case, we'll use
2383 the mapping information to link the corresponding
2384 destination names. */
2385 earlier_file = remember_copied (dst_relname, src_sb.st_ino,
2386 src_sb.st_dev);
2387 if (earlier_file)
2389 /* Note we currently replace DST_NAME unconditionally,
2390 even if it was a newer separate file. */
2391 if (! create_hard_link (nullptr, dst_dirfd, earlier_file,
2392 dst_name, dst_dirfd, dst_relname,
2393 true,
2394 x->verbose, dereference))
2396 goto un_backup;
2400 skipped = true;
2401 goto skip;
2405 /* When there is an existing destination file, we may end up
2406 returning early, and hence not copying/moving the file.
2407 This may be due to an interactive 'negative' reply to the
2408 prompt about the existing file. It may also be due to the
2409 use of the --no-clobber option.
2411 cp and mv treat -i and -f differently. */
2412 if (x->move_mode)
2414 if (abandon_move (x, dst_name, dst_dirfd, drelname, &dst_sb))
2416 /* Pretend the rename succeeded, so the caller (mv)
2417 doesn't end up removing the source file. */
2418 if (rename_succeeded)
2419 *rename_succeeded = true;
2421 skipped = true;
2422 return_val = x->interactive == I_ALWAYS_SKIP;
2425 else
2427 if (! S_ISDIR (src_mode)
2428 && (x->interactive == I_ALWAYS_NO
2429 || x->interactive == I_ALWAYS_SKIP
2430 || (x->interactive == I_ASK_USER
2431 && ! overwrite_ok (x, dst_name, dst_dirfd,
2432 dst_relname, &dst_sb))))
2434 skipped = true;
2435 return_val = x->interactive == I_ALWAYS_SKIP;
2439 skip:
2440 if (skipped)
2442 if (x->interactive == I_ALWAYS_NO)
2443 error (0, 0, _("not replacing %s"), quoteaf (dst_name));
2444 else if (x->debug)
2445 printf (_("skipped %s\n"), quoteaf (dst_name));
2447 return_now = true;
2450 if (return_now)
2451 return return_val;
2453 /* Copying a directory onto a non-directory, or vice versa,
2454 is ok only with --backup or --exchange. */
2455 if (!S_ISDIR (src_mode) != !S_ISDIR (dst_sb.st_mode)
2456 && x->backup_type == no_backups && !x->exchange)
2458 error (0, 0,
2459 _(S_ISDIR (src_mode)
2460 ? ("cannot overwrite non-directory %s "
2461 "with directory %s")
2462 : ("cannot overwrite directory %s "
2463 "with non-directory %s")),
2464 quoteaf_n (0, dst_name), quoteaf_n (1, src_name));
2465 return false;
2468 /* Don't let the user destroy their data, even if they try hard:
2469 This mv command must fail (likewise for cp):
2470 rm -rf a b c; mkdir a b c; touch a/f b/f; mv a/f b/f c
2471 Otherwise, the contents of b/f would be lost.
2472 In the case of 'cp', b/f would be lost if the user simulated
2473 a move using cp and rm.
2474 Nothing is lost if you use --backup=numbered or --exchange. */
2475 if (!S_ISDIR (dst_sb.st_mode) && command_line_arg
2476 && x->backup_type != numbered_backups && !x->exchange
2477 && seen_file (x->dest_info, dst_relname, &dst_sb))
2479 error (0, 0,
2480 _("will not overwrite just-created %s with %s"),
2481 quoteaf_n (0, dst_name), quoteaf_n (1, src_name));
2482 return false;
2485 char const *srcbase;
2486 if (x->backup_type != no_backups
2487 /* Don't try to back up a destination if the last
2488 component of src_name is "." or "..". */
2489 && ! dot_or_dotdot (srcbase = last_component (src_name))
2490 /* Create a backup of each destination directory in move mode,
2491 but not in copy mode. FIXME: it might make sense to add an
2492 option to suppress backup creation also for move mode.
2493 That would let one use mv to merge new content into an
2494 existing hierarchy. */
2495 && (x->move_mode || ! S_ISDIR (dst_sb.st_mode)))
2497 /* Fail if creating the backup file would likely destroy
2498 the source file. Otherwise, the commands:
2499 cd /tmp; rm -f a a~; : > a; echo A > a~; cp --b=simple a~ a
2500 would leave two zero-length files: a and a~. */
2501 if (x->backup_type != numbered_backups
2502 && source_is_dst_backup (srcbase, &src_sb,
2503 dst_dirfd, dst_relname))
2505 char const *fmt;
2506 fmt = (x->move_mode
2507 ? _("backing up %s might destroy source; %s not moved")
2508 : _("backing up %s might destroy source; %s not copied"));
2509 error (0, 0, fmt,
2510 quoteaf_n (0, dst_name),
2511 quoteaf_n (1, src_name));
2512 return false;
2515 char *tmp_backup = backup_file_rename (dst_dirfd, dst_relname,
2516 x->backup_type);
2518 /* FIXME: use fts:
2519 Using alloca for a file name that may be arbitrarily
2520 long is not recommended. In fact, even forming such a name
2521 should be discouraged. Eventually, this code will be rewritten
2522 to use fts, so using alloca here will be less of a problem. */
2523 if (tmp_backup)
2525 idx_t dirlen = dst_relname - dst_name;
2526 idx_t backupsize = strlen (tmp_backup) + 1;
2527 dst_backup = alloca (dirlen + backupsize);
2528 memcpy (mempcpy (dst_backup, dst_name, dirlen),
2529 tmp_backup, backupsize);
2530 free (tmp_backup);
2532 else if (errno != ENOENT)
2534 error (0, errno, _("cannot backup %s"), quoteaf (dst_name));
2535 return false;
2537 new_dst = true;
2539 else if (! S_ISDIR (dst_sb.st_mode)
2540 /* Never unlink dst_name when in move mode. */
2541 && ! x->move_mode
2542 && (x->unlink_dest_before_opening
2543 || (x->data_copy_required
2544 && ((x->preserve_links && 1 < dst_sb.st_nlink)
2545 || (x->dereference == DEREF_NEVER
2546 && ! S_ISREG (src_sb.st_mode))))
2549 if (unlinkat (dst_dirfd, dst_relname, 0) != 0 && errno != ENOENT)
2551 error (0, errno, _("cannot remove %s"), quoteaf (dst_name));
2552 return false;
2554 new_dst = true;
2555 if (x->verbose)
2556 printf (_("removed %s\n"), quoteaf (dst_name));
2561 /* Ensure we don't try to copy through a symlink that was
2562 created by a prior call to this function. */
2563 if (command_line_arg
2564 && x->dest_info
2565 && ! x->move_mode
2566 && x->backup_type == no_backups)
2568 /* If we did not follow symlinks above, good: use that data.
2569 Otherwise, use AT_SYMLINK_NOFOLLOW, in case dst_name is a symlink. */
2570 struct stat tmp_buf;
2571 struct stat *dst_lstat_sb
2572 = (have_dst_lstat ? &dst_sb
2573 : fstatat (dst_dirfd, drelname, &tmp_buf, AT_SYMLINK_NOFOLLOW) < 0
2574 ? nullptr : &tmp_buf);
2576 /* Never copy through a symlink we've just created. */
2577 if (dst_lstat_sb
2578 && S_ISLNK (dst_lstat_sb->st_mode)
2579 && seen_file (x->dest_info, dst_relname, dst_lstat_sb))
2581 error (0, 0,
2582 _("will not copy %s through just-created symlink %s"),
2583 quoteaf_n (0, src_name), quoteaf_n (1, dst_name));
2584 return false;
2588 /* If the source is a directory, we don't always create the destination
2589 directory. So --verbose should not announce anything until we're
2590 sure we'll create a directory. Also don't announce yet when moving
2591 so we can distinguish renames versus copies. */
2592 if (x->verbose && !x->move_mode && !S_ISDIR (src_mode))
2593 emit_verbose ("%s -> %s", src_name, dst_name, dst_backup);
2595 /* Associate the destination file name with the source device and inode
2596 so that if we encounter a matching dev/ino pair in the source tree
2597 we can arrange to create a hard link between the corresponding names
2598 in the destination tree.
2600 When using the --link (-l) option, there is no need to take special
2601 measures, because (barring race conditions) files that are hard-linked
2602 in the source tree will also be hard-linked in the destination tree.
2604 Sometimes, when preserving links, we have to record dev/ino even
2605 though st_nlink == 1:
2606 - when in move_mode, since we may be moving a group of N hard-linked
2607 files (via two or more command line arguments) to a different
2608 partition; the links may be distributed among the command line
2609 arguments (possibly hierarchies) so that the link count of
2610 the final, once-linked source file is reduced to 1 when it is
2611 considered below. But in this case (for mv) we don't need to
2612 incur the expense of recording the dev/ino => name mapping; all we
2613 really need is a lookup, to see if the dev/ino pair has already
2614 been copied.
2615 - when using -H and processing a command line argument;
2616 that command line argument could be a symlink pointing to another
2617 command line argument. With 'cp -H --preserve=link', we hard-link
2618 those two destination files.
2619 - likewise for -L except that it applies to all files, not just
2620 command line arguments.
2622 Also, with --recursive, record dev/ino of each command-line directory.
2623 We'll use that info to detect this problem: cp -R dir dir. */
2625 if (rename_errno == 0 || x->exchange)
2626 earlier_file = nullptr;
2627 else if (x->recursive && S_ISDIR (src_mode))
2629 if (command_line_arg)
2630 earlier_file = remember_copied (dst_relname,
2631 src_sb.st_ino, src_sb.st_dev);
2632 else
2633 earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev);
2635 else if (x->move_mode && src_sb.st_nlink == 1)
2637 earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev);
2639 else if (x->preserve_links
2640 && !x->hard_link
2641 && (1 < src_sb.st_nlink
2642 || (command_line_arg
2643 && x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
2644 || x->dereference == DEREF_ALWAYS))
2646 earlier_file = remember_copied (dst_relname,
2647 src_sb.st_ino, src_sb.st_dev);
2650 /* Did we copy this inode somewhere else (in this command line argument)
2651 and therefore this is a second hard link to the inode? */
2653 if (earlier_file)
2655 /* Avoid damaging the destination file system by refusing to preserve
2656 hard-linked directories (which are found at least in Netapp snapshot
2657 directories). */
2658 if (S_ISDIR (src_mode))
2660 /* If src_name and earlier_file refer to the same directory entry,
2661 then warn about copying a directory into itself. */
2662 if (same_nameat (AT_FDCWD, src_name, dst_dirfd, earlier_file))
2664 error (0, 0, _("cannot copy a directory, %s, into itself, %s"),
2665 quoteaf_n (0, top_level_src_name),
2666 quoteaf_n (1, top_level_dst_name));
2667 *copy_into_self = true;
2668 goto un_backup;
2670 else if (same_nameat (dst_dirfd, dst_relname,
2671 dst_dirfd, earlier_file))
2673 error (0, 0, _("warning: source directory %s "
2674 "specified more than once"),
2675 quoteaf (top_level_src_name));
2676 /* In move mode, if a previous rename succeeded, then
2677 we won't be in this path as the source is missing. If the
2678 rename previously failed, then that has been handled, so
2679 pretend this attempt succeeded so the source isn't removed. */
2680 if (x->move_mode && rename_succeeded)
2681 *rename_succeeded = true;
2682 /* We only do backups in move mode, and for non directories.
2683 So just ignore this repeated entry. */
2684 return true;
2686 else if (x->dereference == DEREF_ALWAYS
2687 || (command_line_arg
2688 && x->dereference == DEREF_COMMAND_LINE_ARGUMENTS))
2690 /* This happens when e.g., encountering a directory for the
2691 second or subsequent time via symlinks when cp is invoked
2692 with -R and -L. E.g.,
2693 rm -rf a b c d; mkdir a b c d; ln -s ../c a; ln -s ../c b;
2694 cp -RL a b d
2697 else
2699 char *earlier = subst_suffix (dst_name, dst_relname,
2700 earlier_file);
2701 error (0, 0, _("will not create hard link %s to directory %s"),
2702 quoteaf_n (0, dst_name), quoteaf_n (1, earlier));
2703 free (earlier);
2704 goto un_backup;
2707 else
2709 if (! create_hard_link (nullptr, dst_dirfd, earlier_file,
2710 dst_name, dst_dirfd, dst_relname,
2711 true, x->verbose, dereference))
2712 goto un_backup;
2714 return true;
2718 if (x->move_mode)
2720 if (rename_errno == EEXIST)
2721 rename_errno = ((renameatu (AT_FDCWD, src_name, dst_dirfd, drelname,
2722 x->exchange ? RENAME_EXCHANGE : 0)
2723 == 0)
2724 ? 0 : errno);
2726 if (rename_errno == 0)
2728 if (x->verbose)
2729 emit_verbose (x->exchange
2730 ? _("exchanged %s <-> %s")
2731 : _("renamed %s -> %s"),
2732 src_name, dst_name, dst_backup);
2734 if (x->set_security_context)
2736 /* -Z failures are only warnings currently. */
2737 (void) set_file_security_ctx (dst_name, true, x);
2740 if (rename_succeeded)
2741 *rename_succeeded = true;
2743 if (command_line_arg && !x->last_file)
2745 /* Record destination dev/ino/name, so that if we are asked
2746 to overwrite that file again, we can detect it and fail. */
2747 /* It's fine to use the _source_ stat buffer (src_sb) to get the
2748 _destination_ dev/ino, since the rename above can't have
2749 changed those, and 'mv' always uses lstat.
2750 We could limit it further by operating
2751 only on non-directories when !x->exchange. */
2752 record_file (x->dest_info, dst_relname, &src_sb);
2755 return true;
2758 /* FIXME: someday, consider what to do when moving a directory into
2759 itself but when source and destination are on different devices. */
2761 /* This happens when attempting to rename a directory to a
2762 subdirectory of itself. */
2763 if (rename_errno == EINVAL)
2765 /* FIXME: this is a little fragile in that it relies on rename(2)
2766 failing with a specific errno value. Expect problems on
2767 non-POSIX systems. */
2768 error (0, 0, _("cannot move %s to a subdirectory of itself, %s"),
2769 quoteaf_n (0, top_level_src_name),
2770 quoteaf_n (1, top_level_dst_name));
2772 /* Note that there is no need to call forget_created here,
2773 (compare with the other calls in this file) since the
2774 destination directory didn't exist before. */
2776 *copy_into_self = true;
2777 /* FIXME-cleanup: Don't return true here; adjust mv.c accordingly.
2778 The only caller that uses this code (mv.c) ends up setting its
2779 exit status to nonzero when copy_into_self is nonzero. */
2780 return true;
2783 /* WARNING: there probably exist systems for which an inter-device
2784 rename fails with a value of errno not handled here.
2785 If/as those are reported, add them to the condition below.
2786 If this happens to you, please do the following and send the output
2787 to the bug-reporting address (e.g., in the output of cp --help):
2788 touch k; perl -e 'rename "k","/tmp/k" or print "$!(",$!+0,")\n"'
2789 where your current directory is on one partition and /tmp is the other.
2790 Also, please try to find the E* errno macro name corresponding to
2791 the diagnostic and parenthesized integer, and include that in your
2792 e-mail. One way to do that is to run a command like this
2793 find /usr/include/. -type f \
2794 | xargs grep 'define.*\<E[A-Z]*\>.*\<18\>' /dev/null
2795 where you'd replace '18' with the integer in parentheses that
2796 was output from the perl one-liner above.
2797 If necessary, of course, change '/tmp' to some other directory. */
2798 if (rename_errno != EXDEV || x->no_copy || x->exchange)
2800 /* There are many ways this can happen due to a race condition.
2801 When something happens between the initial follow_fstatat and the
2802 subsequent rename, we can get many different types of errors.
2803 For example, if the destination is initially a non-directory
2804 or non-existent, but it is created as a directory, the rename
2805 fails. If two 'mv' commands try to rename the same file at
2806 about the same time, one will succeed and the other will fail.
2807 If the permissions on the directory containing the source or
2808 destination file are made too restrictive, the rename will
2809 fail. Etc. */
2810 char const *quoted_dst_name = quoteaf_n (1, dst_name);
2811 if (x->exchange)
2812 error (0, rename_errno, _("cannot exchange %s and %s"),
2813 quoteaf_n (0, src_name), quoted_dst_name);
2814 else
2815 switch (rename_errno)
2817 case EDQUOT: case EEXIST: case EISDIR: case EMLINK:
2818 case ENOSPC: case ETXTBSY:
2819 #if ENOTEMPTY != EEXIST
2820 case ENOTEMPTY:
2821 #endif
2822 /* The destination must be the problem. Don't mention
2823 the source as that is more likely to confuse the user
2824 than be helpful. */
2825 error (0, rename_errno, _("cannot overwrite %s"),
2826 quoted_dst_name);
2827 break;
2829 default:
2830 error (0, rename_errno, _("cannot move %s to %s"),
2831 quoteaf_n (0, src_name), quoted_dst_name);
2832 break;
2834 forget_created (src_sb.st_ino, src_sb.st_dev);
2835 return false;
2838 /* The rename attempt has failed. Remove any existing destination
2839 file so that a cross-device 'mv' acts as if it were really using
2840 the rename syscall. Note both src and dst must both be directories
2841 or not, and this is enforced above. Therefore we check the src_mode
2842 and operate on dst_name here as a tighter constraint and also because
2843 src_mode is readily available here. */
2844 if ((unlinkat (dst_dirfd, drelname,
2845 S_ISDIR (src_mode) ? AT_REMOVEDIR : 0)
2846 != 0)
2847 && errno != ENOENT)
2849 error (0, errno,
2850 _("inter-device move failed: %s to %s; unable to remove target"),
2851 quoteaf_n (0, src_name), quoteaf_n (1, dst_name));
2852 forget_created (src_sb.st_ino, src_sb.st_dev);
2853 return false;
2856 if (x->verbose && !S_ISDIR (src_mode))
2857 emit_verbose (_("copied %s -> %s"), src_name, dst_name, dst_backup);
2858 new_dst = true;
2861 /* If the ownership might change, or if it is a directory (whose
2862 special mode bits may change after the directory is created),
2863 omit some permissions at first, so unauthorized users cannot nip
2864 in before the file is ready. */
2865 dst_mode_bits = (x->set_mode ? x->mode : src_mode) & CHMOD_MODE_BITS;
2866 omitted_permissions =
2867 (dst_mode_bits
2868 & (x->preserve_ownership ? S_IRWXG | S_IRWXO
2869 : S_ISDIR (src_mode) ? S_IWGRP | S_IWOTH
2870 : 0));
2872 delayed_ok = true;
2874 /* If required, set the default security context for new files.
2875 Also for existing files this is used as a reference
2876 when copying the context with --preserve=context.
2877 FIXME: Do we need to consider dst_mode_bits here? */
2878 if (! set_process_security_ctx (src_name, dst_name, src_mode, new_dst, x))
2879 return false;
2881 if (S_ISDIR (src_mode))
2883 struct dir_list *dir;
2885 /* If this directory has been copied before during the
2886 recursion, there is a symbolic link to an ancestor
2887 directory of the symbolic link. It is impossible to
2888 continue to copy this, unless we've got an infinite file system. */
2890 if (is_ancestor (&src_sb, ancestors))
2892 error (0, 0, _("cannot copy cyclic symbolic link %s"),
2893 quoteaf (src_name));
2894 goto un_backup;
2897 /* Insert the current directory in the list of parents. */
2899 dir = alloca (sizeof *dir);
2900 dir->parent = ancestors;
2901 dir->ino = src_sb.st_ino;
2902 dir->dev = src_sb.st_dev;
2904 if (new_dst || !S_ISDIR (dst_sb.st_mode))
2906 /* POSIX says mkdir's behavior is implementation-defined when
2907 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
2908 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
2909 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
2910 mode_t mode = dst_mode_bits & ~omitted_permissions;
2911 if (mkdirat (dst_dirfd, drelname, mode) != 0)
2913 error (0, errno, _("cannot create directory %s"),
2914 quoteaf (dst_name));
2915 goto un_backup;
2918 /* We need search and write permissions to the new directory
2919 for writing the directory's contents. Check if these
2920 permissions are there. */
2922 if (fstatat (dst_dirfd, drelname, &dst_sb, AT_SYMLINK_NOFOLLOW) != 0)
2924 error (0, errno, _("cannot stat %s"), quoteaf (dst_name));
2925 goto un_backup;
2927 else if ((dst_sb.st_mode & S_IRWXU) != S_IRWXU)
2929 /* Make the new directory searchable and writable. */
2931 dst_mode = dst_sb.st_mode;
2932 restore_dst_mode = true;
2934 if (lchmodat (dst_dirfd, drelname, dst_mode | S_IRWXU) != 0)
2936 error (0, errno, _("setting permissions for %s"),
2937 quoteaf (dst_name));
2938 goto un_backup;
2942 /* Record the created directory's inode and device numbers into
2943 the search structure, so that we can avoid copying it again.
2944 Do this only for the first directory that is created for each
2945 source command line argument. */
2946 if (!*first_dir_created_per_command_line_arg)
2948 remember_copied (dst_relname, dst_sb.st_ino, dst_sb.st_dev);
2949 *first_dir_created_per_command_line_arg = true;
2952 if (x->verbose)
2954 if (x->move_mode)
2955 printf (_("created directory %s\n"), quoteaf (dst_name));
2956 else
2957 emit_verbose ("%s -> %s", src_name, dst_name, nullptr);
2960 else
2962 omitted_permissions = 0;
2964 /* For directories, the process global context could be reset for
2965 descendants, so use it to set the context for existing dirs here.
2966 This will also give earlier indication of failure to set ctx. */
2967 if (x->set_security_context || x->preserve_security_context)
2968 if (! set_file_security_ctx (dst_name, false, x))
2970 if (x->require_preserve_context)
2971 goto un_backup;
2975 /* Decide whether to copy the contents of the directory. */
2976 if (x->one_file_system && parent && parent->st_dev != src_sb.st_dev)
2978 /* Here, we are crossing a file system boundary and cp's -x option
2979 is in effect: so don't copy the contents of this directory. */
2981 else
2983 /* Copy the contents of the directory. Don't just return if
2984 this fails -- otherwise, the failure to read a single file
2985 in a source directory would cause the containing destination
2986 directory not to have owner/perms set properly. */
2987 delayed_ok = copy_dir (src_name, dst_name, dst_dirfd, dst_relname,
2988 new_dst, &src_sb, dir, x,
2989 first_dir_created_per_command_line_arg,
2990 copy_into_self);
2993 else if (x->symbolic_link)
2995 dest_is_symlink = true;
2996 if (*src_name != '/')
2998 /* Check that DST_NAME denotes a file in the current directory. */
2999 struct stat dot_sb;
3000 struct stat dst_parent_sb;
3001 char *dst_parent;
3002 bool in_current_dir;
3004 dst_parent = dir_name (dst_relname);
3006 in_current_dir = ((dst_dirfd == AT_FDCWD && STREQ (".", dst_parent))
3007 /* If either stat call fails, it's ok not to report
3008 the failure and say dst_name is in the current
3009 directory. Other things will fail later. */
3010 || stat (".", &dot_sb) != 0
3011 || (fstatat (dst_dirfd, dst_parent, &dst_parent_sb,
3012 0) != 0)
3013 || psame_inode (&dot_sb, &dst_parent_sb));
3014 free (dst_parent);
3016 if (! in_current_dir)
3018 error (0, 0,
3019 _("%s: can make relative symbolic links only in current directory"),
3020 quotef (dst_name));
3021 goto un_backup;
3025 int err = force_symlinkat (src_name, dst_dirfd, dst_relname,
3026 x->unlink_dest_after_failed_open, -1);
3027 if (0 < err)
3029 error (0, err, _("cannot create symbolic link %s to %s"),
3030 quoteaf_n (0, dst_name), quoteaf_n (1, src_name));
3031 goto un_backup;
3035 /* POSIX 2008 states that it is implementation-defined whether
3036 link() on a symlink creates a hard-link to the symlink, or only
3037 to the referent (effectively dereferencing the symlink) (POSIX
3038 2001 required the latter behavior, although many systems provided
3039 the former). Yet cp, invoked with '--link --no-dereference',
3040 should not follow the link. We can approximate the desired
3041 behavior by skipping this hard-link creating block and instead
3042 copying the symlink, via the 'S_ISLNK'- copying code below.
3044 Note gnulib's linkat module, guarantees that the symlink is not
3045 dereferenced. However its emulation currently doesn't maintain
3046 timestamps or ownership so we only call it when we know the
3047 emulation will not be needed. */
3048 else if (x->hard_link
3049 && !(! CAN_HARDLINK_SYMLINKS && S_ISLNK (src_mode)
3050 && x->dereference == DEREF_NEVER))
3052 bool replace = (x->unlink_dest_after_failed_open
3053 || x->interactive == I_ASK_USER);
3054 if (! create_hard_link (src_name, AT_FDCWD, src_name,
3055 dst_name, dst_dirfd, dst_relname,
3056 replace, false, dereference))
3057 goto un_backup;
3059 else if (S_ISREG (src_mode)
3060 || (x->copy_as_regular && !S_ISLNK (src_mode)))
3062 copied_as_regular = true;
3063 /* POSIX says the permission bits of the source file must be
3064 used as the 3rd argument in the open call. Historical
3065 practice passed all the source mode bits to 'open', but the extra
3066 bits were ignored, so it should be the same either way.
3068 This call uses DST_MODE_BITS, not SRC_MODE. These are
3069 normally the same, and the exception (where x->set_mode) is
3070 used only by 'install', which POSIX does not specify and
3071 where DST_MODE_BITS is what's wanted. */
3072 if (! copy_reg (src_name, dst_name, dst_dirfd, dst_relname,
3073 x, dst_mode_bits & S_IRWXUGO,
3074 omitted_permissions, &new_dst, &src_sb))
3075 goto un_backup;
3077 else if (S_ISFIFO (src_mode))
3079 /* Use mknodat, rather than mkfifoat, because the former preserves
3080 the special mode bits of a fifo on Solaris 10, while mkfifoat
3081 does not. But fall back on mkfifoat, because on some BSD systems,
3082 mknodat always fails when asked to create a FIFO. */
3083 mode_t mode = src_mode & ~omitted_permissions;
3084 if (mknodat (dst_dirfd, dst_relname, mode, 0) != 0)
3085 if (mkfifoat (dst_dirfd, dst_relname, mode & ~S_IFIFO) != 0)
3087 error (0, errno, _("cannot create fifo %s"), quoteaf (dst_name));
3088 goto un_backup;
3091 else if (S_ISBLK (src_mode) || S_ISCHR (src_mode) || S_ISSOCK (src_mode))
3093 mode_t mode = src_mode & ~omitted_permissions;
3094 if (mknodat (dst_dirfd, dst_relname, mode, src_sb.st_rdev) != 0)
3096 error (0, errno, _("cannot create special file %s"),
3097 quoteaf (dst_name));
3098 goto un_backup;
3101 else if (S_ISLNK (src_mode))
3103 char *src_link_val = areadlink_with_size (src_name, src_sb.st_size);
3104 dest_is_symlink = true;
3105 if (src_link_val == nullptr)
3107 error (0, errno, _("cannot read symbolic link %s"),
3108 quoteaf (src_name));
3109 goto un_backup;
3112 int symlink_err = force_symlinkat (src_link_val, dst_dirfd, dst_relname,
3113 x->unlink_dest_after_failed_open, -1);
3114 if (0 < symlink_err && x->update && !new_dst && S_ISLNK (dst_sb.st_mode)
3115 && dst_sb.st_size == strlen (src_link_val))
3117 /* See if the destination is already the desired symlink.
3118 FIXME: This behavior isn't documented, and seems wrong
3119 in some cases, e.g., if the destination symlink has the
3120 wrong ownership, permissions, or timestamps. */
3121 char *dest_link_val =
3122 areadlinkat_with_size (dst_dirfd, dst_relname, dst_sb.st_size);
3123 if (dest_link_val)
3125 if (STREQ (dest_link_val, src_link_val))
3126 symlink_err = 0;
3127 free (dest_link_val);
3130 free (src_link_val);
3131 if (0 < symlink_err)
3133 error (0, symlink_err, _("cannot create symbolic link %s"),
3134 quoteaf (dst_name));
3135 goto un_backup;
3138 if (x->preserve_security_context)
3139 restore_default_fscreatecon_or_die ();
3141 if (x->preserve_ownership)
3143 /* Preserve the owner and group of the just-'copied'
3144 symbolic link, if possible. */
3145 if (HAVE_LCHOWN
3146 && (lchownat (dst_dirfd, dst_relname,
3147 src_sb.st_uid, src_sb.st_gid)
3148 != 0)
3149 && ! chown_failure_ok (x))
3151 error (0, errno, _("failed to preserve ownership for %s"),
3152 dst_name);
3153 if (x->require_preserve)
3154 goto un_backup;
3156 else
3158 /* Can't preserve ownership of symlinks.
3159 FIXME: maybe give a warning or even error for symlinks
3160 in directories with the sticky bit set -- there, not
3161 preserving owner/group is a potential security problem. */
3165 else
3167 error (0, 0, _("%s has unknown file type"), quoteaf (src_name));
3168 goto un_backup;
3171 /* With -Z or --preserve=context, set the context for existing files.
3172 Note this is done already for copy_reg() for reasons described therein. */
3173 if (!new_dst && !x->copy_as_regular && !S_ISDIR (src_mode)
3174 && (x->set_security_context || x->preserve_security_context))
3176 if (! set_file_security_ctx (dst_name, false, x))
3178 if (x->require_preserve_context)
3179 goto un_backup;
3183 if (command_line_arg && x->dest_info)
3185 /* Now that the destination file is very likely to exist,
3186 add its info to the set. */
3187 struct stat sb;
3188 if (fstatat (dst_dirfd, drelname, &sb, AT_SYMLINK_NOFOLLOW) == 0)
3189 record_file (x->dest_info, dst_relname, &sb);
3192 /* If we've just created a hard-link due to cp's --link option,
3193 we're done. */
3194 if (x->hard_link && ! S_ISDIR (src_mode)
3195 && !(! CAN_HARDLINK_SYMLINKS && S_ISLNK (src_mode)
3196 && x->dereference == DEREF_NEVER))
3197 return delayed_ok;
3199 if (copied_as_regular)
3200 return delayed_ok;
3202 /* POSIX says that 'cp -p' must restore the following:
3203 - permission bits
3204 - setuid, setgid bits
3205 - owner and group
3206 If it fails to restore any of those, we may give a warning but
3207 the destination must not be removed.
3208 FIXME: implement the above. */
3210 /* Adjust the times (and if possible, ownership) for the copy.
3211 chown turns off set[ug]id bits for non-root,
3212 so do the chmod last. */
3214 if (x->preserve_timestamps)
3216 struct timespec timespec[2];
3217 timespec[0] = get_stat_atime (&src_sb);
3218 timespec[1] = get_stat_mtime (&src_sb);
3220 int utimensat_flags = dest_is_symlink ? AT_SYMLINK_NOFOLLOW : 0;
3221 if (utimensat (dst_dirfd, drelname, timespec, utimensat_flags) != 0)
3223 error (0, errno, _("preserving times for %s"), quoteaf (dst_name));
3224 if (x->require_preserve)
3225 return false;
3229 /* Avoid calling chown if we know it's not necessary. */
3230 if (!dest_is_symlink && x->preserve_ownership
3231 && (new_dst || !SAME_OWNER_AND_GROUP (src_sb, dst_sb)))
3233 switch (set_owner (x, dst_name, dst_dirfd, drelname, -1,
3234 &src_sb, new_dst, &dst_sb))
3236 case -1:
3237 return false;
3239 case 0:
3240 src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX);
3241 break;
3245 /* Set xattrs after ownership as changing owners will clear capabilities. */
3246 if (x->preserve_xattr && ! copy_attr (src_name, -1, dst_name, -1, x)
3247 && x->require_preserve_xattr)
3248 return false;
3250 /* The operations beyond this point may dereference a symlink. */
3251 if (dest_is_symlink)
3252 return delayed_ok;
3254 set_author (dst_name, -1, &src_sb);
3256 if (x->preserve_mode || x->move_mode)
3258 if (copy_acl (src_name, -1, dst_name, -1, src_mode) != 0
3259 && x->require_preserve)
3260 return false;
3262 else if (x->set_mode)
3264 if (set_acl (dst_name, -1, x->mode) != 0)
3265 return false;
3267 else if (x->explicit_no_preserve_mode && new_dst)
3269 int default_permissions = S_ISDIR (src_mode) || S_ISSOCK (src_mode)
3270 ? S_IRWXUGO : MODE_RW_UGO;
3271 dst_mode = dst_sb.st_mode;
3272 if (S_ISDIR (src_mode)) /* Keep set-group-ID for directories. */
3273 default_permissions |= (dst_mode & S_ISGID);
3274 if (set_acl (dst_name, -1, default_permissions & ~cached_umask ()) != 0)
3275 return false;
3277 else
3279 if (omitted_permissions)
3281 omitted_permissions &= ~ cached_umask ();
3283 if (omitted_permissions && !restore_dst_mode)
3285 /* Permissions were deliberately omitted when the file
3286 was created due to security concerns. See whether
3287 they need to be re-added now. It'd be faster to omit
3288 the lstat, but deducing the current destination mode
3289 is tricky in the presence of implementation-defined
3290 rules for special mode bits. */
3291 if (new_dst && (fstatat (dst_dirfd, drelname, &dst_sb,
3292 AT_SYMLINK_NOFOLLOW)
3293 != 0))
3295 error (0, errno, _("cannot stat %s"), quoteaf (dst_name));
3296 return false;
3298 dst_mode = dst_sb.st_mode;
3299 if (omitted_permissions & ~dst_mode)
3300 restore_dst_mode = true;
3304 if (restore_dst_mode)
3306 if (lchmodat (dst_dirfd, drelname, dst_mode | omitted_permissions)
3307 != 0)
3309 error (0, errno, _("preserving permissions for %s"),
3310 quoteaf (dst_name));
3311 if (x->require_preserve)
3312 return false;
3317 return delayed_ok;
3319 un_backup:
3321 if (x->preserve_security_context)
3322 restore_default_fscreatecon_or_die ();
3324 /* We have failed to create the destination file.
3325 If we've just added a dev/ino entry via the remember_copied
3326 call above (i.e., unless we've just failed to create a hard link),
3327 remove the entry associating the source dev/ino with the
3328 destination file name, so we don't try to 'preserve' a link
3329 to a file we didn't create. */
3330 if (earlier_file == nullptr)
3331 forget_created (src_sb.st_ino, src_sb.st_dev);
3333 if (dst_backup)
3335 char const *dst_relbackup = &dst_backup[dst_relname - dst_name];
3336 if (renameat (dst_dirfd, dst_relbackup, dst_dirfd, drelname) != 0)
3337 error (0, errno, _("cannot un-backup %s"), quoteaf (dst_name));
3338 else
3340 if (x->verbose)
3341 printf (_("%s -> %s (unbackup)\n"),
3342 quoteaf_n (0, dst_backup), quoteaf_n (1, dst_name));
3345 return false;
3348 static void
3349 valid_options (const struct cp_options *co)
3351 affirm (VALID_BACKUP_TYPE (co->backup_type));
3352 affirm (VALID_SPARSE_MODE (co->sparse_mode));
3353 affirm (VALID_REFLINK_MODE (co->reflink_mode));
3354 affirm (!(co->hard_link && co->symbolic_link));
3355 affirm (!
3356 (co->reflink_mode == REFLINK_ALWAYS
3357 && co->sparse_mode != SPARSE_AUTO));
3360 /* Copy the file SRC_NAME to the file DST_NAME aka DST_DIRFD+DST_RELNAME.
3361 If NONEXISTENT_DST is positive, DST_NAME does not exist even as a
3362 dangling symlink; if negative, it does not exist except possibly
3363 as a dangling symlink; if zero, its existence status is unknown.
3364 OPTIONS summarizes the command-line options.
3365 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
3366 same as) DST_NAME; otherwise, set clear it.
3367 If X->move_mode, set *RENAME_SUCCEEDED according to whether
3368 the source was simply renamed to the destination.
3369 Return true if successful. */
3371 extern bool
3372 copy (char const *src_name, char const *dst_name,
3373 int dst_dirfd, char const *dst_relname,
3374 int nonexistent_dst, const struct cp_options *options,
3375 bool *copy_into_self, bool *rename_succeeded)
3377 valid_options (options);
3379 /* Record the file names: they're used in case of error, when copying
3380 a directory into itself. I don't like to make these tools do *any*
3381 extra work in the common case when that work is solely to handle
3382 exceptional cases, but in this case, I don't see a way to derive the
3383 top level source and destination directory names where they're used.
3384 An alternative is to use COPY_INTO_SELF and print the diagnostic
3385 from every caller -- but I don't want to do that. */
3386 top_level_src_name = src_name;
3387 top_level_dst_name = dst_name;
3389 bool first_dir_created_per_command_line_arg = false;
3390 return copy_internal (src_name, dst_name, dst_dirfd, dst_relname,
3391 nonexistent_dst, nullptr, nullptr,
3392 options, true,
3393 &first_dir_created_per_command_line_arg,
3394 copy_into_self, rename_succeeded);
3397 /* Set *X to the default options for a value of type struct cp_options. */
3399 extern void
3400 cp_options_default (struct cp_options *x)
3402 memset (x, 0, sizeof *x);
3403 #ifdef PRIV_FILE_CHOWN
3405 priv_set_t *pset = priv_allocset ();
3406 if (!pset)
3407 xalloc_die ();
3408 if (getppriv (PRIV_EFFECTIVE, pset) == 0)
3410 x->chown_privileges = priv_ismember (pset, PRIV_FILE_CHOWN);
3411 x->owner_privileges = priv_ismember (pset, PRIV_FILE_OWNER);
3413 priv_freeset (pset);
3415 #else
3416 x->chown_privileges = x->owner_privileges = (geteuid () == ROOT_UID);
3417 #endif
3418 x->rename_errno = -1;
3421 /* Return true if it's OK for chown to fail, where errno is
3422 the error number that chown failed with and X is the copying
3423 option set. */
3425 extern bool
3426 chown_failure_ok (struct cp_options const *x)
3428 /* If non-root uses -p, it's ok if we can't preserve ownership.
3429 But root probably wants to know, e.g. if NFS disallows it,
3430 or if the target system doesn't support file ownership.
3432 Treat EACCES like EPERM and EINVAL to work around a bug in Linux
3433 CIFS <https://bugs.gnu.org/65599>. Although this means coreutils
3434 will ignore EACCES errors that it should report, problems should
3435 occur only when some other process is racing with coreutils and
3436 coreutils is not immune to races anyway. */
3438 return ((errno == EPERM || errno == EINVAL || errno == EACCES)
3439 && !x->chown_privileges);
3442 /* Similarly, return true if it's OK for chmod and similar operations
3443 to fail, where errno is the error number that chmod failed with and
3444 X is the copying option set. */
3446 static bool
3447 owner_failure_ok (struct cp_options const *x)
3449 return ((errno == EPERM || errno == EINVAL || errno == EACCES)
3450 && !x->owner_privileges);
3453 /* Return the user's umask, caching the result.
3455 FIXME: If the destination's parent directory has has a default ACL,
3456 some operating systems (e.g., GNU/Linux's "POSIX" ACLs) use that
3457 ACL's mask rather than the process umask. Currently, the callers
3458 of cached_umask incorrectly assume that this situation cannot occur. */
3459 extern mode_t
3460 cached_umask (void)
3462 static mode_t mask = (mode_t) -1;
3463 if (mask == (mode_t) -1)
3465 mask = umask (0);
3466 umask (mask);
3468 return mask;