ptx: prefer xpalloc to x2nrealloc
[coreutils.git] / src / copy.c
blobb1ac52c791ab856f368599fb574eac0093eab86a
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 #endif
76 #if HAVE_LINUX_FALLOC_H
77 # include <linux/falloc.h>
78 #endif
80 /* See HAVE_FALLOCATE workaround when including this file. */
81 #ifdef HAVE_LINUX_FS_H
82 # include <linux/fs.h>
83 #endif
85 #if !defined FICLONE && defined __linux__
86 # define FICLONE _IOW (0x94, 9, int)
87 #endif
89 #if HAVE_FCLONEFILEAT && !USE_XATTR
90 # include <sys/clonefile.h>
91 #endif
93 #ifndef USE_ACL
94 # define USE_ACL 0
95 #endif
97 #define SAME_OWNER(A, B) ((A).st_uid == (B).st_uid)
98 #define SAME_GROUP(A, B) ((A).st_gid == (B).st_gid)
99 #define SAME_OWNER_AND_GROUP(A, B) (SAME_OWNER (A, B) && SAME_GROUP (A, B))
101 /* LINK_FOLLOWS_SYMLINKS is tri-state; if it is -1, we don't know
102 how link() behaves, so assume we can't hardlink symlinks in that case. */
103 #if (defined HAVE_LINKAT && ! LINKAT_SYMLINK_NOTSUP) || ! LINK_FOLLOWS_SYMLINKS
104 # define CAN_HARDLINK_SYMLINKS 1
105 #else
106 # define CAN_HARDLINK_SYMLINKS 0
107 #endif
109 struct dir_list
111 struct dir_list *parent;
112 ino_t ino;
113 dev_t dev;
116 /* Initial size of the cp.dest_info hash table. */
117 #define DEST_INFO_INITIAL_CAPACITY 61
119 static bool copy_internal (char const *src_name, char const *dst_name,
120 int dst_dirfd, char const *dst_relname,
121 int nonexistent_dst, struct stat const *parent,
122 struct dir_list *ancestors,
123 const struct cp_options *x,
124 bool command_line_arg,
125 bool *first_dir_created_per_command_line_arg,
126 bool *copy_into_self,
127 bool *rename_succeeded);
128 static bool owner_failure_ok (struct cp_options const *x);
130 /* Pointers to the file names: they're used in the diagnostic that is issued
131 when we detect the user is trying to copy a directory into itself. */
132 static char const *top_level_src_name;
133 static char const *top_level_dst_name;
135 enum copy_debug_val
137 COPY_DEBUG_UNKNOWN,
138 COPY_DEBUG_NO,
139 COPY_DEBUG_YES,
140 COPY_DEBUG_EXTERNAL,
141 COPY_DEBUG_EXTERNAL_INTERNAL,
142 COPY_DEBUG_AVOIDED,
143 COPY_DEBUG_UNSUPPORTED,
146 /* debug info about the last file copy. */
147 static struct copy_debug
149 enum copy_debug_val offload;
150 enum copy_debug_val reflink;
151 enum copy_debug_val sparse_detection;
152 } copy_debug;
154 static const char*
155 copy_debug_string (enum copy_debug_val debug_val)
157 switch (debug_val)
159 case COPY_DEBUG_NO: return "no";
160 case COPY_DEBUG_YES: return "yes";
161 case COPY_DEBUG_AVOIDED: return "avoided";
162 case COPY_DEBUG_UNSUPPORTED: return "unsupported";
163 default: return "unknown";
167 static const char*
168 copy_debug_sparse_string (enum copy_debug_val debug_val)
170 switch (debug_val)
172 case COPY_DEBUG_NO: return "no";
173 case COPY_DEBUG_YES: return "zeros";
174 case COPY_DEBUG_EXTERNAL: return "SEEK_HOLE";
175 case COPY_DEBUG_EXTERNAL_INTERNAL: return "SEEK_HOLE + zeros";
176 default: return "unknown";
180 /* Print --debug output on standard output. */
181 static void
182 emit_debug (const struct cp_options *x)
184 if (! x->hard_link && ! x->symbolic_link && x->data_copy_required)
185 printf ("copy offload: %s, reflink: %s, sparse detection: %s\n",
186 copy_debug_string (copy_debug.offload),
187 copy_debug_string (copy_debug.reflink),
188 copy_debug_sparse_string (copy_debug.sparse_detection));
191 #ifndef DEV_FD_MIGHT_BE_CHR
192 # define DEV_FD_MIGHT_BE_CHR false
193 #endif
195 /* Act like fstat (DIRFD, FILENAME, ST, FLAGS), except when following
196 symbolic links on Solaris-like systems, treat any character-special
197 device like /dev/fd/0 as if it were the file it is open on. */
198 static int
199 follow_fstatat (int dirfd, char const *filename, struct stat *st, int flags)
201 int result = fstatat (dirfd, filename, st, flags);
203 if (DEV_FD_MIGHT_BE_CHR && result == 0 && !(flags & AT_SYMLINK_NOFOLLOW)
204 && S_ISCHR (st->st_mode))
206 static dev_t stdin_rdev;
207 static signed char stdin_rdev_status;
208 if (stdin_rdev_status == 0)
210 struct stat stdin_st;
211 if (stat ("/dev/stdin", &stdin_st) == 0 && S_ISCHR (stdin_st.st_mode)
212 && minor (stdin_st.st_rdev) == STDIN_FILENO)
214 stdin_rdev = stdin_st.st_rdev;
215 stdin_rdev_status = 1;
217 else
218 stdin_rdev_status = -1;
220 if (0 < stdin_rdev_status && major (stdin_rdev) == major (st->st_rdev))
221 result = fstat (minor (st->st_rdev), st);
224 return result;
227 /* Attempt to punch a hole to avoid any permanent
228 speculative preallocation on file systems such as XFS.
229 Return values as per fallocate(2) except ENOSYS etc. are ignored. */
231 static int
232 punch_hole (int fd, off_t offset, off_t length)
234 int ret = 0;
235 /* +0 is to work around older <linux/fs.h> defining HAVE_FALLOCATE to empty. */
236 #if HAVE_FALLOCATE + 0
237 # if defined FALLOC_FL_PUNCH_HOLE && defined FALLOC_FL_KEEP_SIZE
238 ret = fallocate (fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
239 offset, length);
240 if (ret < 0 && (is_ENOTSUP (errno) || errno == ENOSYS))
241 ret = 0;
242 # endif
243 #endif
244 return ret;
247 /* Create a hole at the end of a file,
248 avoiding preallocation if requested. */
250 static bool
251 create_hole (int fd, char const *name, bool punch_holes, off_t size)
253 off_t file_end = lseek (fd, size, SEEK_CUR);
255 if (file_end < 0)
257 error (0, errno, _("cannot lseek %s"), quoteaf (name));
258 return false;
261 /* Some file systems (like XFS) preallocate when write extending a file.
262 I.e., a previous write() may have preallocated extra space
263 that the seek above will not discard. A subsequent write() could
264 then make this allocation permanent. */
265 if (punch_holes && punch_hole (fd, file_end - size, size) < 0)
267 error (0, errno, _("error deallocating %s"), quoteaf (name));
268 return false;
271 return true;
275 /* Whether an errno value ERR, set by FICLONE or copy_file_range,
276 indicates that the copying operation has terminally failed, even
277 though it was invoked correctly (so that, e.g, EBADF cannot occur)
278 and even though !is_CLONENOTSUP (ERR). */
280 static bool
281 is_terminal_error (int err)
283 return err == EIO || err == ENOMEM || err == ENOSPC || err == EDQUOT;
286 /* Similarly, whether ERR indicates that the copying operation is not
287 supported or allowed for this file or process, even though the
288 operation was invoked correctly. */
290 static bool
291 is_CLONENOTSUP (int err)
293 return err == ENOSYS || err == ENOTTY || is_ENOTSUP (err)
294 || err == EINVAL || err == EBADF
295 || err == EXDEV || err == ETXTBSY
296 || err == EPERM || err == EACCES;
300 /* Copy the regular file open on SRC_FD/SRC_NAME to DST_FD/DST_NAME,
301 honoring the MAKE_HOLES setting and using the BUF_SIZE-byte buffer
302 *ABUF for temporary storage, allocating it lazily if *ABUF is null.
303 Copy no more than MAX_N_READ bytes.
304 Return true upon successful completion;
305 print a diagnostic and return false upon error.
306 Note that for best results, BUF should be "well"-aligned.
307 Set *LAST_WRITE_MADE_HOLE to true if the final operation on
308 DEST_FD introduced a hole. Set *TOTAL_N_READ to the number of
309 bytes read. */
310 static bool
311 sparse_copy (int src_fd, int dest_fd, char **abuf, size_t buf_size,
312 size_t hole_size, bool punch_holes, bool allow_reflink,
313 char const *src_name, char const *dst_name,
314 uintmax_t max_n_read, off_t *total_n_read,
315 bool *last_write_made_hole)
317 *last_write_made_hole = false;
318 *total_n_read = 0;
320 if (copy_debug.sparse_detection == COPY_DEBUG_UNKNOWN)
321 copy_debug.sparse_detection = hole_size ? COPY_DEBUG_YES : COPY_DEBUG_NO;
322 else if (hole_size && copy_debug.sparse_detection == COPY_DEBUG_EXTERNAL)
323 copy_debug.sparse_detection = COPY_DEBUG_EXTERNAL_INTERNAL;
325 /* If not looking for holes, use copy_file_range if functional,
326 but don't use if reflink disallowed as that may be implicit. */
327 if (!hole_size && allow_reflink)
328 while (max_n_read)
330 /* Copy at most COPY_MAX bytes at a time; this is min
331 (SSIZE_MAX, SIZE_MAX) truncated to a value that is
332 surely aligned well. */
333 ssize_t copy_max = MIN (SSIZE_MAX, SIZE_MAX) >> 30 << 30;
334 ssize_t n_copied = copy_file_range (src_fd, nullptr, dest_fd, nullptr,
335 MIN (max_n_read, copy_max), 0);
336 if (n_copied == 0)
338 /* copy_file_range incorrectly returns 0 when reading from
339 the proc file system on the Linux kernel through at
340 least 5.6.19 (2020), so fall back on 'read' if the
341 input file seems empty. */
342 if (*total_n_read == 0)
343 break;
344 copy_debug.offload = COPY_DEBUG_YES;
345 return true;
347 if (n_copied < 0)
349 copy_debug.offload = COPY_DEBUG_UNSUPPORTED;
351 /* Consider operation unsupported only if no data copied.
352 For example, EPERM could occur if copy_file_range not enabled
353 in seccomp filters, so retry with a standard copy. EPERM can
354 also occur for immutable files, but that would only be in the
355 edge case where the file is made immutable after creating,
356 in which case the (more accurate) error is still shown. */
357 if (*total_n_read == 0 && is_CLONENOTSUP (errno))
358 break;
360 /* ENOENT was seen sometimes across CIFS shares, resulting in
361 no data being copied, but subsequent standard copies succeed. */
362 if (*total_n_read == 0 && errno == ENOENT)
363 break;
365 if (errno == EINTR)
366 n_copied = 0;
367 else
369 error (0, errno, _("error copying %s to %s"),
370 quoteaf_n (0, src_name), quoteaf_n (1, dst_name));
371 return false;
374 copy_debug.offload = COPY_DEBUG_YES;
375 max_n_read -= n_copied;
376 *total_n_read += n_copied;
378 else
379 copy_debug.offload = COPY_DEBUG_AVOIDED;
382 bool make_hole = false;
383 off_t psize = 0;
385 while (max_n_read)
387 if (!*abuf)
388 *abuf = xalignalloc (getpagesize (), buf_size);
389 char *buf = *abuf;
390 ssize_t n_read = read (src_fd, buf, MIN (max_n_read, buf_size));
391 if (n_read < 0)
393 if (errno == EINTR)
394 continue;
395 error (0, errno, _("error reading %s"), quoteaf (src_name));
396 return false;
398 if (n_read == 0)
399 break;
400 max_n_read -= n_read;
401 *total_n_read += n_read;
403 /* Loop over the input buffer in chunks of hole_size. */
404 size_t csize = hole_size ? hole_size : buf_size;
405 char *cbuf = buf;
406 char *pbuf = buf;
408 while (n_read)
410 bool prev_hole = make_hole;
411 csize = MIN (csize, n_read);
413 if (hole_size && csize)
414 make_hole = is_nul (cbuf, csize);
416 bool transition = (make_hole != prev_hole) && psize;
417 bool last_chunk = (n_read == csize && ! make_hole) || ! csize;
419 if (transition || last_chunk)
421 if (! transition)
422 psize += csize;
424 if (! prev_hole)
426 if (full_write (dest_fd, pbuf, psize) != psize)
428 error (0, errno, _("error writing %s"),
429 quoteaf (dst_name));
430 return false;
433 else
435 if (! create_hole (dest_fd, dst_name, punch_holes, psize))
436 return false;
439 pbuf = cbuf;
440 psize = csize;
442 if (last_chunk)
444 if (! csize)
445 n_read = 0; /* Finished processing buffer. */
447 if (transition)
448 csize = 0; /* Loop again to deal with last chunk. */
449 else
450 psize = 0; /* Reset for next read loop. */
453 else /* Coalesce writes/seeks. */
455 if (ckd_add (&psize, psize, csize))
457 error (0, 0, _("overflow reading %s"), quoteaf (src_name));
458 return false;
462 n_read -= csize;
463 cbuf += csize;
466 *last_write_made_hole = make_hole;
468 /* It's tempting to break early here upon a short read from
469 a regular file. That would save the final read syscall
470 for each file. Unfortunately that doesn't work for
471 certain files in /proc or /sys with linux kernels. */
474 /* Ensure a trailing hole is created, so that subsequent
475 calls of sparse_copy() start at the correct offset. */
476 if (make_hole && ! create_hole (dest_fd, dst_name, punch_holes, psize))
477 return false;
478 else
479 return true;
482 /* Perform the O(1) btrfs clone operation, if possible.
483 Upon success, return 0. Otherwise, return -1 and set errno. */
484 static inline int
485 clone_file (int dest_fd, int src_fd)
487 #ifdef FICLONE
488 return ioctl (dest_fd, FICLONE, src_fd);
489 #else
490 (void) dest_fd;
491 (void) src_fd;
492 errno = ENOTSUP;
493 return -1;
494 #endif
497 /* Write N_BYTES zero bytes to file descriptor FD. Return true if successful.
498 Upon write failure, set errno and return false. */
499 static bool
500 write_zeros (int fd, off_t n_bytes)
502 static char *zeros;
503 static size_t nz = IO_BUFSIZE;
505 /* Attempt to use a relatively large calloc'd source buffer for
506 efficiency, but if that allocation fails, resort to a smaller
507 statically allocated one. */
508 if (zeros == nullptr)
510 static char fallback[1024];
511 zeros = calloc (nz, 1);
512 if (zeros == nullptr)
514 zeros = fallback;
515 nz = sizeof fallback;
519 while (n_bytes)
521 size_t n = MIN (nz, n_bytes);
522 if ((full_write (fd, zeros, n)) != n)
523 return false;
524 n_bytes -= n;
527 return true;
530 #ifdef SEEK_HOLE
531 /* Perform an efficient extent copy, if possible. This avoids
532 the overhead of detecting holes in hole-introducing/preserving
533 copy, and thus makes copying sparse files much more efficient.
534 Copy from SRC_FD to DEST_FD, using *ABUF (of size BUF_SIZE) for a buffer.
535 Allocate *ABUF lazily if *ABUF is null.
536 Look for holes of size HOLE_SIZE in the input.
537 The input file is of size SRC_TOTAL_SIZE.
538 Use SPARSE_MODE to determine whether to create holes in the output.
539 SRC_NAME and DST_NAME are the input and output file names.
540 Return true if successful, false (with a diagnostic) otherwise. */
542 static bool
543 lseek_copy (int src_fd, int dest_fd, char **abuf, size_t buf_size,
544 size_t hole_size, off_t ext_start, off_t src_total_size,
545 enum Sparse_type sparse_mode,
546 bool allow_reflink,
547 char const *src_name, char const *dst_name)
549 off_t last_ext_start = 0;
550 off_t last_ext_len = 0;
551 off_t dest_pos = 0;
552 bool wrote_hole_at_eof = true;
554 copy_debug.sparse_detection = COPY_DEBUG_EXTERNAL;
556 while (0 <= ext_start)
558 off_t ext_end = lseek (src_fd, ext_start, SEEK_HOLE);
559 if (ext_end < 0)
561 if (errno != ENXIO)
562 goto cannot_lseek;
563 ext_end = src_total_size;
564 if (ext_end <= ext_start)
566 /* The input file grew; get its current size. */
567 src_total_size = lseek (src_fd, 0, SEEK_END);
568 if (src_total_size < 0)
569 goto cannot_lseek;
571 /* If the input file shrank after growing, stop copying. */
572 if (src_total_size <= ext_start)
573 break;
575 ext_end = src_total_size;
578 /* If the input file must have grown, increase its measured size. */
579 if (src_total_size < ext_end)
580 src_total_size = ext_end;
582 if (lseek (src_fd, ext_start, SEEK_SET) < 0)
583 goto cannot_lseek;
585 wrote_hole_at_eof = false;
586 off_t ext_hole_size = ext_start - last_ext_start - last_ext_len;
588 if (ext_hole_size)
590 if (sparse_mode != SPARSE_NEVER)
592 if (! create_hole (dest_fd, dst_name,
593 sparse_mode == SPARSE_ALWAYS,
594 ext_hole_size))
595 return false;
596 wrote_hole_at_eof = true;
598 else
600 /* When not inducing holes and when there is a hole between
601 the end of the previous extent and the beginning of the
602 current one, write zeros to the destination file. */
603 if (! write_zeros (dest_fd, ext_hole_size))
605 error (0, errno, _("%s: write failed"),
606 quotef (dst_name));
607 return false;
612 off_t ext_len = ext_end - ext_start;
613 last_ext_start = ext_start;
614 last_ext_len = ext_len;
616 /* Copy this extent, looking for further opportunities to not
617 bother to write zeros if --sparse=always, since SEEK_HOLE
618 is conservative and may miss some holes. */
619 off_t n_read;
620 bool read_hole;
621 if ( ! sparse_copy (src_fd, dest_fd, abuf, buf_size,
622 sparse_mode != SPARSE_ALWAYS ? 0 : hole_size,
623 true, allow_reflink, src_name, dst_name,
624 ext_len, &n_read, &read_hole))
625 return false;
627 dest_pos = ext_start + n_read;
628 if (n_read)
629 wrote_hole_at_eof = read_hole;
630 if (n_read < ext_len)
632 /* The input file shrank. */
633 src_total_size = dest_pos;
634 break;
637 ext_start = lseek (src_fd, dest_pos, SEEK_DATA);
638 if (ext_start < 0 && errno != ENXIO)
639 goto cannot_lseek;
642 /* When the source file ends with a hole, we have to do a little more work,
643 since the above copied only up to and including the final extent.
644 In order to complete the copy, we may have to insert a hole or write
645 zeros in the destination corresponding to the source file's hole-at-EOF.
647 In addition, if the final extent was a block of zeros at EOF and we've
648 just converted them to a hole in the destination, we must call ftruncate
649 here in order to record the proper length in the destination. */
650 if ((dest_pos < src_total_size || wrote_hole_at_eof)
651 && ! (sparse_mode == SPARSE_NEVER
652 ? write_zeros (dest_fd, src_total_size - dest_pos)
653 : ftruncate (dest_fd, src_total_size) == 0))
655 error (0, errno, _("failed to extend %s"), quoteaf (dst_name));
656 return false;
659 if (sparse_mode == SPARSE_ALWAYS && dest_pos < src_total_size
660 && punch_hole (dest_fd, dest_pos, src_total_size - dest_pos) < 0)
662 error (0, errno, _("error deallocating %s"), quoteaf (dst_name));
663 return false;
666 return true;
668 cannot_lseek:
669 error (0, errno, _("cannot lseek %s"), quoteaf (src_name));
670 return false;
672 #endif
674 /* FIXME: describe */
675 /* FIXME: rewrite this to use a hash table so we avoid the quadratic
676 performance hit that's probably noticeable only on trees deeper
677 than a few hundred levels. See use of active_dir_map in remove.c */
679 ATTRIBUTE_PURE
680 static bool
681 is_ancestor (const struct stat *sb, const struct dir_list *ancestors)
683 while (ancestors != 0)
685 if (ancestors->ino == sb->st_ino && ancestors->dev == sb->st_dev)
686 return true;
687 ancestors = ancestors->parent;
689 return false;
692 static bool
693 errno_unsupported (int err)
695 return err == ENOTSUP || err == ENODATA;
698 #if USE_XATTR
699 ATTRIBUTE_FORMAT ((printf, 2, 3))
700 static void
701 copy_attr_error (MAYBE_UNUSED struct error_context *ctx,
702 char const *fmt, ...)
704 if (!errno_unsupported (errno))
706 int err = errno;
707 va_list ap;
709 /* use verror module to print error message */
710 va_start (ap, fmt);
711 verror (0, err, fmt, ap);
712 va_end (ap);
716 ATTRIBUTE_FORMAT ((printf, 2, 3))
717 static void
718 copy_attr_allerror (MAYBE_UNUSED struct error_context *ctx,
719 char const *fmt, ...)
721 int err = errno;
722 va_list ap;
724 /* use verror module to print error message */
725 va_start (ap, fmt);
726 verror (0, err, fmt, ap);
727 va_end (ap);
730 static char const *
731 copy_attr_quote (MAYBE_UNUSED struct error_context *ctx, char const *str)
733 return quoteaf (str);
736 static void
737 copy_attr_free (MAYBE_UNUSED struct error_context *ctx,
738 MAYBE_UNUSED char const *str)
742 /* Exclude SELinux extended attributes that are otherwise handled,
743 and are problematic to copy again. Also honor attributes
744 configured for exclusion in /etc/xattr.conf.
745 FIXME: Should we handle POSIX ACLs similarly?
746 Return zero to skip. */
747 static int
748 check_selinux_attr (char const *name, struct error_context *ctx)
750 return STRNCMP_LIT (name, "security.selinux")
751 && attr_copy_check_permissions (name, ctx);
754 /* If positive SRC_FD and DST_FD descriptors are passed,
755 then copy by fd, otherwise copy by name. */
757 static bool
758 copy_attr (char const *src_path, int src_fd,
759 char const *dst_path, int dst_fd, struct cp_options const *x)
761 bool all_errors = (!x->data_copy_required || x->require_preserve_xattr);
762 bool some_errors = (!all_errors && !x->reduce_diagnostics);
763 int (*check) (char const *, struct error_context *)
764 = (x->preserve_security_context || x->set_security_context
765 ? check_selinux_attr : nullptr);
767 # if 4 < __GNUC__ + (8 <= __GNUC_MINOR__)
768 /* Pacify gcc -Wsuggest-attribute=format through at least GCC 13.2.1. */
769 # pragma GCC diagnostic push
770 # pragma GCC diagnostic ignored "-Wsuggest-attribute=format"
771 # endif
772 struct error_context *ctx
773 = (all_errors || some_errors
774 ? (&(struct error_context) {
775 .error = all_errors ? copy_attr_allerror : copy_attr_error,
776 .quote = copy_attr_quote,
777 .quote_free = copy_attr_free
779 : nullptr);
780 # if 4 < __GNUC__ + (8 <= __GNUC_MINOR__)
781 # pragma GCC diagnostic pop
782 # endif
784 return ! (0 <= src_fd && 0 <= dst_fd
785 ? attr_copy_fd (src_path, src_fd, dst_path, dst_fd, check, ctx)
786 : attr_copy_file (src_path, dst_path, check, ctx));
788 #else /* USE_XATTR */
790 static bool
791 copy_attr (MAYBE_UNUSED char const *src_path,
792 MAYBE_UNUSED int src_fd,
793 MAYBE_UNUSED char const *dst_path,
794 MAYBE_UNUSED int dst_fd,
795 MAYBE_UNUSED struct cp_options const *x)
797 return true;
799 #endif /* USE_XATTR */
801 /* Read the contents of the directory SRC_NAME_IN, and recursively
802 copy the contents to DST_NAME_IN aka DST_DIRFD+DST_RELNAME_IN.
803 NEW_DST is true if DST_NAME_IN is a directory
804 that was created previously in the recursion.
805 SRC_SB and ANCESTORS describe SRC_NAME_IN.
806 Set *COPY_INTO_SELF if SRC_NAME_IN is a parent of
807 (or the same as) DST_NAME_IN; otherwise, clear it.
808 Propagate *FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG from
809 caller to each invocation of copy_internal. Be careful to
810 pass the address of a temporary, and to update
811 *FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG only upon completion.
812 Return true if successful. */
814 static bool
815 copy_dir (char const *src_name_in, char const *dst_name_in,
816 int dst_dirfd, char const *dst_relname_in, bool new_dst,
817 const struct stat *src_sb, struct dir_list *ancestors,
818 const struct cp_options *x,
819 bool *first_dir_created_per_command_line_arg,
820 bool *copy_into_self)
822 char *name_space;
823 char *namep;
824 struct cp_options non_command_line_options = *x;
825 bool ok = true;
827 name_space = savedir (src_name_in, SAVEDIR_SORT_FASTREAD);
828 if (name_space == nullptr)
830 /* This diagnostic is a bit vague because savedir can fail in
831 several different ways. */
832 error (0, errno, _("cannot access %s"), quoteaf (src_name_in));
833 return false;
836 /* For cp's -H option, dereference command line arguments, but do not
837 dereference symlinks that are found via recursive traversal. */
838 if (x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
839 non_command_line_options.dereference = DEREF_NEVER;
841 bool new_first_dir_created = false;
842 namep = name_space;
843 while (*namep != '\0')
845 bool local_copy_into_self;
846 char *src_name = file_name_concat (src_name_in, namep, nullptr);
847 char *dst_name = file_name_concat (dst_name_in, namep, nullptr);
848 bool first_dir_created = *first_dir_created_per_command_line_arg;
849 bool rename_succeeded;
851 ok &= copy_internal (src_name, dst_name, dst_dirfd,
852 dst_name + (dst_relname_in - dst_name_in),
853 new_dst, src_sb,
854 ancestors, &non_command_line_options, false,
855 &first_dir_created,
856 &local_copy_into_self, &rename_succeeded);
857 *copy_into_self |= local_copy_into_self;
859 free (dst_name);
860 free (src_name);
862 /* If we're copying into self, there's no point in continuing,
863 and in fact, that would even infloop, now that we record only
864 the first created directory per command line argument. */
865 if (local_copy_into_self)
866 break;
868 new_first_dir_created |= first_dir_created;
869 namep += strlen (namep) + 1;
871 free (name_space);
872 *first_dir_created_per_command_line_arg = new_first_dir_created;
874 return ok;
877 /* Change the file mode bits of the file identified by DESC or
878 DIRFD+NAME to MODE. Use DESC if DESC is valid and fchmod is
879 available, DIRFD+NAME otherwise. */
881 static int
882 fchmod_or_lchmod (int desc, int dirfd, char const *name, mode_t mode)
884 #if HAVE_FCHMOD
885 if (0 <= desc)
886 return fchmod (desc, mode);
887 #endif
888 return lchmodat (dirfd, name, mode);
891 /* Change the ownership of the file identified by DESC or
892 DIRFD+NAME to UID+GID. Use DESC if DESC is valid and fchown is
893 available, DIRFD+NAME otherwise. */
895 static int
896 fchown_or_lchown (int desc, int dirfd, char const *name, uid_t uid, gid_t gid)
898 #if HAVE_FCHOWN
899 if (0 <= desc)
900 return fchown (desc, uid, gid);
901 #endif
902 return lchownat (dirfd, name, uid, gid);
905 /* Set the owner and owning group of DEST_DESC to the st_uid and
906 st_gid fields of SRC_SB. If DEST_DESC is undefined (-1), set
907 the owner and owning group of DST_NAME aka DST_DIRFD+DST_RELNAME
908 instead; for safety prefer lchownat since no
909 symbolic links should be involved. DEST_DESC must
910 refer to the same file as DST_NAME if defined.
911 Upon failure to set both UID and GID, try to set only the GID.
912 NEW_DST is true if the file was newly created; otherwise,
913 DST_SB is the status of the destination.
914 Return 1 if the initial syscall succeeds, 0 if it fails but it's OK
915 not to preserve ownership, -1 otherwise. */
917 static int
918 set_owner (const struct cp_options *x, char const *dst_name,
919 int dst_dirfd, char const *dst_relname, int dest_desc,
920 struct stat const *src_sb, bool new_dst,
921 struct stat const *dst_sb)
923 uid_t uid = src_sb->st_uid;
924 gid_t gid = src_sb->st_gid;
926 /* Naively changing the ownership of an already-existing file before
927 changing its permissions would create a window of vulnerability if
928 the file's old permissions are too generous for the new owner and
929 group. Avoid the window by first changing to a restrictive
930 temporary mode if necessary. */
932 if (!new_dst && (x->preserve_mode || x->move_mode || x->set_mode))
934 mode_t old_mode = dst_sb->st_mode;
935 mode_t new_mode =
936 (x->preserve_mode || x->move_mode ? src_sb->st_mode : x->mode);
937 mode_t restrictive_temp_mode = old_mode & new_mode & S_IRWXU;
939 if ((USE_ACL
940 || (old_mode & CHMOD_MODE_BITS
941 & (~new_mode | S_ISUID | S_ISGID | S_ISVTX)))
942 && qset_acl (dst_name, dest_desc, restrictive_temp_mode) != 0)
944 if (! owner_failure_ok (x))
945 error (0, errno, _("clearing permissions for %s"),
946 quoteaf (dst_name));
947 return -x->require_preserve;
951 if (fchown_or_lchown (dest_desc, dst_dirfd, dst_relname, uid, gid) == 0)
952 return 1;
954 /* The ownership change failed. If the failure merely means we lack
955 privileges to change owner+group, try to change just the group
956 and ignore any failure of this. Otherwise, report an error. */
957 if (chown_failure_ok (x))
958 ignore_value (fchown_or_lchown (dest_desc, dst_dirfd, dst_relname,
959 -1, gid));
960 else
962 error (0, errno, _("failed to preserve ownership for %s"),
963 quoteaf (dst_name));
964 if (x->require_preserve)
965 return -1;
968 return 0;
971 /* Set the st_author field of DEST_DESC to the st_author field of
972 SRC_SB. If DEST_DESC is undefined (-1), set the st_author field
973 of DST_NAME instead. DEST_DESC must refer to the same file as
974 DST_NAME if defined. */
976 static void
977 set_author (char const *dst_name, int dest_desc, const struct stat *src_sb)
979 #if HAVE_STRUCT_STAT_ST_AUTHOR
980 /* FIXME: Modify the following code so that it does not
981 follow symbolic links. */
983 /* Preserve the st_author field. */
984 file_t file = (dest_desc < 0
985 ? file_name_lookup (dst_name, 0, 0)
986 : getdport (dest_desc));
987 if (file == MACH_PORT_NULL)
988 error (0, errno, _("failed to lookup file %s"), quoteaf (dst_name));
989 else
991 error_t err = file_chauthor (file, src_sb->st_author);
992 if (err)
993 error (0, err, _("failed to preserve authorship for %s"),
994 quoteaf (dst_name));
995 mach_port_deallocate (mach_task_self (), file);
997 #else
998 (void) dst_name;
999 (void) dest_desc;
1000 (void) src_sb;
1001 #endif
1004 /* Set the default security context for the process. New files will
1005 have this security context set. Also existing files can have their
1006 context adjusted based on this process context, by
1007 set_file_security_ctx() called with PROCESS_LOCAL=true.
1008 This should be called before files are created so there is no race
1009 where a file may be present without an appropriate security context.
1010 Based on CP_OPTIONS, diagnose warnings and fail when appropriate.
1011 Return FALSE on failure, TRUE on success. */
1013 bool
1014 set_process_security_ctx (char const *src_name, char const *dst_name,
1015 mode_t mode, bool new_dst, const struct cp_options *x)
1017 if (x->preserve_security_context)
1019 /* Set the default context for the process to match the source. */
1020 bool all_errors = !x->data_copy_required || x->require_preserve_context;
1021 bool some_errors = !all_errors && !x->reduce_diagnostics;
1022 char *con_raw;
1024 if (0 <= lgetfilecon_raw (src_name, &con_raw))
1026 if (setfscreatecon_raw (con_raw) < 0)
1028 if (all_errors || (some_errors && !errno_unsupported (errno)))
1029 error (0, errno,
1030 _("failed to set default file creation context to %s"),
1031 quote (con_raw));
1032 if (x->require_preserve_context)
1034 freecon (con_raw);
1035 return false;
1038 freecon (con_raw);
1040 else
1042 if (all_errors || (some_errors && !errno_unsupported (errno)))
1044 error (0, errno,
1045 _("failed to get security context of %s"),
1046 quoteaf (src_name));
1048 if (x->require_preserve_context)
1049 return false;
1052 else if (x->set_security_context)
1054 /* With -Z, adjust the default context for the process
1055 to have the type component adjusted as per the destination path. */
1056 if (new_dst && defaultcon (x->set_security_context, dst_name, mode) < 0
1057 && ! ignorable_ctx_err (errno))
1059 error (0, errno,
1060 _("failed to set default file creation context for %s"),
1061 quoteaf (dst_name));
1065 return true;
1068 /* Reset the security context of DST_NAME, to that already set
1069 as the process default if !X->set_security_context. Otherwise
1070 adjust the type component of DST_NAME's security context as
1071 per the system default for that path. Issue warnings upon
1072 failure, when allowed by various settings in X.
1073 Return false on failure, true on success. */
1075 bool
1076 set_file_security_ctx (char const *dst_name,
1077 bool recurse, const struct cp_options *x)
1079 bool all_errors = (!x->data_copy_required
1080 || x->require_preserve_context);
1081 bool some_errors = !all_errors && !x->reduce_diagnostics;
1083 if (! restorecon (x->set_security_context, dst_name, recurse))
1085 if (all_errors || (some_errors && !errno_unsupported (errno)))
1086 error (0, errno, _("failed to set the security context of %s"),
1087 quoteaf_n (0, dst_name));
1088 return false;
1091 return true;
1094 #ifndef HAVE_STRUCT_STAT_ST_BLOCKS
1095 # define HAVE_STRUCT_STAT_ST_BLOCKS 0
1096 #endif
1098 /* Type of scan being done on the input when looking for sparseness. */
1099 enum scantype
1101 /* An error was found when determining scantype. */
1102 ERROR_SCANTYPE,
1104 /* No fancy scanning; just read and write. */
1105 PLAIN_SCANTYPE,
1107 /* Read and examine data looking for zero blocks; useful when
1108 attempting to create sparse output. */
1109 ZERO_SCANTYPE,
1111 /* lseek information is available. */
1112 LSEEK_SCANTYPE,
1115 /* Result of infer_scantype. */
1116 union scan_inference
1118 /* Used if infer_scantype returns LSEEK_SCANTYPE. This is the
1119 offset of the first data block, or -1 if the file has no data. */
1120 off_t ext_start;
1123 /* Return how to scan a file with descriptor FD and stat buffer SB.
1124 *SCAN_INFERENCE is set to a valid value if returning LSEEK_SCANTYPE. */
1125 static enum scantype
1126 infer_scantype (int fd, struct stat const *sb,
1127 union scan_inference *scan_inference)
1129 scan_inference->ext_start = -1; /* avoid -Wmaybe-uninitialized */
1131 /* Only attempt SEEK_HOLE if this heuristic
1132 suggests the file is sparse. */
1133 if (! (HAVE_STRUCT_STAT_ST_BLOCKS
1134 && S_ISREG (sb->st_mode)
1135 && STP_NBLOCKS (sb) < sb->st_size / ST_NBLOCKSIZE))
1136 return PLAIN_SCANTYPE;
1138 #ifdef SEEK_HOLE
1139 off_t ext_start = lseek (fd, 0, SEEK_DATA);
1140 if (0 <= ext_start || errno == ENXIO)
1142 scan_inference->ext_start = ext_start;
1143 return LSEEK_SCANTYPE;
1145 else if (errno != EINVAL && !is_ENOTSUP (errno))
1146 return ERROR_SCANTYPE;
1147 #endif
1149 return ZERO_SCANTYPE;
1152 #if HAVE_FCLONEFILEAT && !USE_XATTR
1153 # include <sys/acl.h>
1154 /* Return true if FD has a nontrivial ACL. */
1155 static bool
1156 fd_has_acl (int fd)
1158 /* Every platform with fclonefileat (macOS 10.12 or later) also has
1159 acl_get_fd_np. */
1160 bool has_acl = false;
1161 acl_t acl = acl_get_fd_np (fd, ACL_TYPE_EXTENDED);
1162 if (acl)
1164 acl_entry_t ace;
1165 has_acl = 0 <= acl_get_entry (acl, ACL_FIRST_ENTRY, &ace);
1166 acl_free (acl);
1168 return has_acl;
1170 #endif
1172 /* Handle failure from FICLONE or fclonefileat.
1173 Return FALSE if it's a terminal failure for this file. */
1175 static bool
1176 handle_clone_fail (int dst_dirfd, char const *dst_relname,
1177 char const *src_name, char const *dst_name,
1178 int dest_desc, bool new_dst, enum Reflink_type reflink_mode)
1180 /* When the clone operation fails, report failure only with errno values
1181 known to mean trouble when the clone is supported and called properly.
1182 Do not report failure merely because !is_CLONENOTSUP (errno),
1183 as systems may yield oddball errno values here with FICLONE,
1184 and is_CLONENOTSUP is not appropriate for fclonefileat. */
1185 bool report_failure = is_terminal_error (errno);
1187 if (reflink_mode == REFLINK_ALWAYS || report_failure)
1188 error (0, errno, _("failed to clone %s from %s"),
1189 quoteaf_n (0, dst_name), quoteaf_n (1, src_name));
1191 /* Remove the destination if cp --reflink=always created it
1192 but cloned no data. */
1193 if (new_dst /* currently not for fclonefileat(). */
1194 && reflink_mode == REFLINK_ALWAYS
1195 && ((! report_failure) || lseek (dest_desc, 0, SEEK_END) == 0)
1196 && unlinkat (dst_dirfd, dst_relname, 0) != 0 && errno != ENOENT)
1197 error (0, errno, _("cannot remove %s"), quoteaf (dst_name));
1199 if (! report_failure)
1200 copy_debug.reflink = COPY_DEBUG_UNSUPPORTED;
1202 if (reflink_mode == REFLINK_ALWAYS || report_failure)
1203 return false;
1205 return true;
1209 /* Copy a regular file from SRC_NAME to DST_NAME aka DST_DIRFD+DST_RELNAME.
1210 If the source file contains holes, copies holes and blocks of zeros
1211 in the source file as holes in the destination file.
1212 (Holes are read as zeroes by the 'read' system call.)
1213 When creating the destination, use DST_MODE & ~OMITTED_PERMISSIONS
1214 as the third argument in the call to open, adding
1215 OMITTED_PERMISSIONS after copying as needed.
1216 X provides many option settings.
1217 Return true if successful.
1218 *NEW_DST is initially as in copy_internal.
1219 If successful, set *NEW_DST to true if the destination file was created and
1220 to false otherwise; if unsuccessful, perhaps set *NEW_DST to some value.
1221 SRC_SB is the result of calling follow_fstatat on SRC_NAME;
1222 it might be updated by calling fstat again on the same file,
1223 to give it slightly more up-to-date contents. */
1225 static bool
1226 copy_reg (char const *src_name, char const *dst_name,
1227 int dst_dirfd, char const *dst_relname,
1228 const struct cp_options *x,
1229 mode_t dst_mode, mode_t omitted_permissions, bool *new_dst,
1230 struct stat *src_sb)
1232 char *buf = nullptr;
1233 int dest_desc;
1234 int dest_errno;
1235 int source_desc;
1236 mode_t extra_permissions;
1237 struct stat sb;
1238 struct stat src_open_sb;
1239 union scan_inference scan_inference;
1240 bool return_val = true;
1241 bool data_copy_required = x->data_copy_required;
1242 bool preserve_xattr = USE_XATTR & x->preserve_xattr;
1244 copy_debug.offload = COPY_DEBUG_UNKNOWN;
1245 copy_debug.reflink = x->reflink_mode ? COPY_DEBUG_UNKNOWN : COPY_DEBUG_NO;
1246 copy_debug.sparse_detection = COPY_DEBUG_UNKNOWN;
1248 source_desc = open (src_name,
1249 (O_RDONLY | O_BINARY
1250 | (x->dereference == DEREF_NEVER ? O_NOFOLLOW : 0)));
1251 if (source_desc < 0)
1253 error (0, errno, _("cannot open %s for reading"), quoteaf (src_name));
1254 return false;
1257 if (fstat (source_desc, &src_open_sb) != 0)
1259 error (0, errno, _("cannot fstat %s"), quoteaf (src_name));
1260 return_val = false;
1261 goto close_src_desc;
1264 /* Compare the source dev/ino from the open file to the incoming,
1265 saved ones obtained via a previous call to stat. */
1266 if (! psame_inode (src_sb, &src_open_sb))
1268 error (0, 0,
1269 _("skipping file %s, as it was replaced while being copied"),
1270 quoteaf (src_name));
1271 return_val = false;
1272 goto close_src_desc;
1275 /* Might as well tell the caller about the latest version of the
1276 source file status, since we have it already. */
1277 *src_sb = src_open_sb;
1278 mode_t src_mode = src_sb->st_mode;
1280 /* The semantics of the following open calls are mandated
1281 by the specs for both cp and mv. */
1282 if (! *new_dst)
1284 int open_flags =
1285 O_WRONLY | O_BINARY | (data_copy_required ? O_TRUNC : 0);
1286 dest_desc = openat (dst_dirfd, dst_relname, open_flags);
1287 dest_errno = errno;
1289 /* When using cp --preserve=context to copy to an existing destination,
1290 reset the context as per the default context, which has already been
1291 set according to the src.
1292 When using the mutually exclusive -Z option, then adjust the type of
1293 the existing context according to the system default for the dest.
1294 Note we set the context here, _after_ the file is opened, lest the
1295 new context disallow that. */
1296 if (0 <= dest_desc
1297 && (x->set_security_context || x->preserve_security_context))
1299 if (! set_file_security_ctx (dst_name, false, x))
1301 if (x->require_preserve_context)
1303 return_val = false;
1304 goto close_src_and_dst_desc;
1309 if (dest_desc < 0 && dest_errno != ENOENT
1310 && x->unlink_dest_after_failed_open)
1312 if (unlinkat (dst_dirfd, dst_relname, 0) == 0)
1314 if (x->verbose)
1315 printf (_("removed %s\n"), quoteaf (dst_name));
1317 else if (errno != ENOENT)
1319 error (0, errno, _("cannot remove %s"), quoteaf (dst_name));
1320 return_val = false;
1321 goto close_src_desc;
1324 dest_errno = ENOENT;
1327 if (dest_desc < 0 && dest_errno == ENOENT)
1329 /* Ensure there is no race where a file may be left without
1330 an appropriate security context. */
1331 if (x->set_security_context)
1333 if (! set_process_security_ctx (src_name, dst_name, dst_mode,
1334 true, x))
1336 return_val = false;
1337 goto close_src_desc;
1341 /* Tell caller that the destination file is created. */
1342 *new_dst = true;
1346 if (*new_dst)
1348 #if HAVE_FCLONEFILEAT && !USE_XATTR
1349 # ifndef CLONE_ACL
1350 # define CLONE_ACL 0 /* Added in macOS 12.6. */
1351 # endif
1352 # ifndef CLONE_NOOWNERCOPY
1353 # define CLONE_NOOWNERCOPY 0 /* Added in macOS 10.13. */
1354 # endif
1355 /* Try fclonefileat if copying data in reflink mode.
1356 Use CLONE_NOFOLLOW to avoid security issues that could occur
1357 if writing through dangling symlinks. Although the circa
1358 2023 macOS documentation doesn't say so, CLONE_NOFOLLOW
1359 affects the destination file too. */
1360 if (data_copy_required && x->reflink_mode
1361 && (CLONE_NOOWNERCOPY || x->preserve_ownership))
1363 /* Try fclonefileat so long as it won't create the
1364 destination with unwanted permissions, which could lead
1365 to a security race. */
1366 mode_t cloned_mode_bits = S_ISVTX | S_IRWXUGO;
1367 mode_t cloned_mode = src_mode & cloned_mode_bits;
1368 mode_t desired_mode
1369 = (x->preserve_mode ? src_mode & CHMOD_MODE_BITS
1370 : x->set_mode ? x->mode
1371 : ((x->explicit_no_preserve_mode ? MODE_RW_UGO : dst_mode)
1372 & ~ cached_umask ()));
1373 if (! (cloned_mode & ~desired_mode))
1375 int fc_flags
1376 = (CLONE_NOFOLLOW
1377 | (x->preserve_mode ? CLONE_ACL : 0)
1378 | (x->preserve_ownership ? 0 : CLONE_NOOWNERCOPY));
1379 int s = fclonefileat (source_desc, dst_dirfd, dst_relname,
1380 fc_flags);
1381 if (s != 0 && (fc_flags & CLONE_ACL) && errno == EINVAL)
1383 fc_flags &= ~CLONE_ACL;
1384 s = fclonefileat (source_desc, dst_dirfd, dst_relname,
1385 fc_flags);
1387 if (s == 0)
1389 copy_debug.reflink = COPY_DEBUG_YES;
1391 /* Update the clone's timestamps and permissions
1392 as needed. */
1394 if (!x->preserve_timestamps)
1396 struct timespec timespec[2];
1397 timespec[0].tv_nsec = timespec[1].tv_nsec = UTIME_NOW;
1398 if (utimensat (dst_dirfd, dst_relname, timespec,
1399 AT_SYMLINK_NOFOLLOW)
1400 != 0)
1402 error (0, errno, _("updating times for %s"),
1403 quoteaf (dst_name));
1404 return_val = false;
1405 goto close_src_desc;
1409 extra_permissions = desired_mode & ~cloned_mode;
1410 if (!extra_permissions
1411 && (!x->preserve_mode || (fc_flags & CLONE_ACL)
1412 || !fd_has_acl (source_desc)))
1414 goto close_src_desc;
1417 /* Either some desired permissions were not cloned,
1418 or ACLs were not cloned despite that being requested. */
1419 omitted_permissions = 0;
1420 dest_desc = -1;
1421 goto set_dest_mode;
1423 if (! handle_clone_fail (dst_dirfd, dst_relname, src_name,
1424 dst_name,
1425 -1, false /* We didn't create dst */,
1426 x->reflink_mode))
1428 return_val = false;
1429 goto close_src_desc;
1432 else
1433 copy_debug.reflink = COPY_DEBUG_AVOIDED;
1435 else if (data_copy_required && x->reflink_mode)
1437 if (! CLONE_NOOWNERCOPY)
1438 copy_debug.reflink = COPY_DEBUG_AVOIDED;
1440 #endif
1442 /* To allow copying xattrs on read-only files, create with u+w.
1443 This satisfies an inode permission check done by
1444 xattr_permission in fs/xattr.c of the GNU/Linux kernel. */
1445 mode_t open_mode =
1446 ((dst_mode & ~omitted_permissions)
1447 | (preserve_xattr && !x->owner_privileges ? S_IWUSR : 0));
1448 extra_permissions = open_mode & ~dst_mode; /* either 0 or S_IWUSR */
1450 int open_flags = O_WRONLY | O_CREAT | O_BINARY;
1451 dest_desc = openat (dst_dirfd, dst_relname, open_flags | O_EXCL,
1452 open_mode);
1453 dest_errno = errno;
1455 /* When trying to copy through a dangling destination symlink,
1456 the above open fails with EEXIST. If that happens, and
1457 readlinkat shows that it is a symlink, then we
1458 have a problem: trying to resolve this dangling symlink to
1459 a directory/destination-entry pair is fundamentally racy,
1460 so punt. If x->open_dangling_dest_symlink is set (cp sets
1461 that when POSIXLY_CORRECT is set in the environment), simply
1462 call open again, but without O_EXCL (potentially dangerous).
1463 If not, fail with a diagnostic. These shenanigans are necessary
1464 only when copying, i.e., not in move_mode. */
1465 if (dest_desc < 0 && dest_errno == EEXIST && ! x->move_mode)
1467 char dummy[1];
1468 if (0 <= readlinkat (dst_dirfd, dst_relname, dummy, sizeof dummy))
1470 if (x->open_dangling_dest_symlink)
1472 dest_desc = openat (dst_dirfd, dst_relname,
1473 open_flags, open_mode);
1474 dest_errno = errno;
1476 else
1478 error (0, 0, _("not writing through dangling symlink %s"),
1479 quoteaf (dst_name));
1480 return_val = false;
1481 goto close_src_desc;
1486 /* Improve quality of diagnostic when a nonexistent dst_name
1487 ends in a slash and open fails with errno == EISDIR. */
1488 if (dest_desc < 0 && dest_errno == EISDIR
1489 && *dst_name && dst_name[strlen (dst_name) - 1] == '/')
1490 dest_errno = ENOTDIR;
1492 else
1494 omitted_permissions = extra_permissions = 0;
1497 if (dest_desc < 0)
1499 error (0, dest_errno, _("cannot create regular file %s"),
1500 quoteaf (dst_name));
1501 return_val = false;
1502 goto close_src_desc;
1505 /* --attributes-only overrides --reflink. */
1506 if (data_copy_required && x->reflink_mode)
1508 if (clone_file (dest_desc, source_desc) == 0)
1510 data_copy_required = false;
1511 copy_debug.reflink = COPY_DEBUG_YES;
1513 else
1515 if (! handle_clone_fail (dst_dirfd, dst_relname, src_name, dst_name,
1516 dest_desc, *new_dst, x->reflink_mode))
1518 return_val = false;
1519 goto close_src_and_dst_desc;
1524 if (! (data_copy_required | x->preserve_ownership | extra_permissions))
1525 sb.st_mode = 0;
1526 else if (fstat (dest_desc, &sb) != 0)
1528 error (0, errno, _("cannot fstat %s"), quoteaf (dst_name));
1529 return_val = false;
1530 goto close_src_and_dst_desc;
1533 /* If extra permissions needed for copy_xattr didn't happen (e.g.,
1534 due to umask) chmod to add them temporarily; if that fails give
1535 up with extra permissions, letting copy_attr fail later. */
1536 mode_t temporary_mode = sb.st_mode | extra_permissions;
1537 if (temporary_mode != sb.st_mode
1538 && (fchmod_or_lchmod (dest_desc, dst_dirfd, dst_relname, temporary_mode)
1539 != 0))
1540 extra_permissions = 0;
1542 if (data_copy_required)
1544 /* Choose a suitable buffer size; it may be adjusted later. */
1545 size_t buf_size = io_blksize (&sb);
1546 size_t hole_size = STP_BLKSIZE (&sb);
1548 /* Deal with sparse files. */
1549 enum scantype scantype = infer_scantype (source_desc, &src_open_sb,
1550 &scan_inference);
1551 if (scantype == ERROR_SCANTYPE)
1553 error (0, errno, _("cannot lseek %s"), quoteaf (src_name));
1554 return_val = false;
1555 goto close_src_and_dst_desc;
1557 bool make_holes
1558 = (S_ISREG (sb.st_mode)
1559 && (x->sparse_mode == SPARSE_ALWAYS
1560 || (x->sparse_mode == SPARSE_AUTO
1561 && scantype != PLAIN_SCANTYPE)));
1563 fdadvise (source_desc, 0, 0, FADVISE_SEQUENTIAL);
1565 /* If not making a sparse file, try to use a more-efficient
1566 buffer size. */
1567 if (! make_holes)
1569 /* Compute the least common multiple of the input and output
1570 buffer sizes, adjusting for outlandish values.
1571 Note we read in multiples of the reported block size
1572 to support (unusual) devices that have this constraint. */
1573 size_t blcm_max = MIN (SIZE_MAX, SSIZE_MAX);
1574 size_t blcm = buffer_lcm (io_blksize (&src_open_sb), buf_size,
1575 blcm_max);
1577 /* Do not bother with a buffer larger than the input file, plus one
1578 byte to make sure the file has not grown while reading it. */
1579 if (S_ISREG (src_open_sb.st_mode) && src_open_sb.st_size < buf_size)
1580 buf_size = src_open_sb.st_size + 1;
1582 /* However, stick with a block size that is a positive multiple of
1583 blcm, overriding the above adjustments. Watch out for
1584 overflow. */
1585 buf_size += blcm - 1;
1586 buf_size -= buf_size % blcm;
1587 if (buf_size == 0 || blcm_max < buf_size)
1588 buf_size = blcm;
1591 off_t n_read;
1592 bool wrote_hole_at_eof = false;
1593 if (! (
1594 #ifdef SEEK_HOLE
1595 scantype == LSEEK_SCANTYPE
1596 ? lseek_copy (source_desc, dest_desc, &buf, buf_size, hole_size,
1597 scan_inference.ext_start, src_open_sb.st_size,
1598 make_holes ? x->sparse_mode : SPARSE_NEVER,
1599 x->reflink_mode != REFLINK_NEVER,
1600 src_name, dst_name)
1602 #endif
1603 sparse_copy (source_desc, dest_desc, &buf, buf_size,
1604 make_holes ? hole_size : 0,
1605 x->sparse_mode == SPARSE_ALWAYS,
1606 x->reflink_mode != REFLINK_NEVER,
1607 src_name, dst_name, UINTMAX_MAX, &n_read,
1608 &wrote_hole_at_eof)))
1610 return_val = false;
1611 goto close_src_and_dst_desc;
1613 else if (wrote_hole_at_eof && ftruncate (dest_desc, n_read) < 0)
1615 error (0, errno, _("failed to extend %s"), quoteaf (dst_name));
1616 return_val = false;
1617 goto close_src_and_dst_desc;
1621 if (x->preserve_timestamps)
1623 struct timespec timespec[2];
1624 timespec[0] = get_stat_atime (src_sb);
1625 timespec[1] = get_stat_mtime (src_sb);
1627 if (fdutimensat (dest_desc, dst_dirfd, dst_relname, timespec, 0) != 0)
1629 error (0, errno, _("preserving times for %s"), quoteaf (dst_name));
1630 if (x->require_preserve)
1632 return_val = false;
1633 goto close_src_and_dst_desc;
1638 /* Set ownership before xattrs as changing owners will
1639 clear capabilities. */
1640 if (x->preserve_ownership && ! SAME_OWNER_AND_GROUP (*src_sb, sb))
1642 switch (set_owner (x, dst_name, dst_dirfd, dst_relname, dest_desc,
1643 src_sb, *new_dst, &sb))
1645 case -1:
1646 return_val = false;
1647 goto close_src_and_dst_desc;
1649 case 0:
1650 src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX);
1651 break;
1655 if (preserve_xattr)
1657 if (!copy_attr (src_name, source_desc, dst_name, dest_desc, x)
1658 && x->require_preserve_xattr)
1659 return_val = false;
1662 set_author (dst_name, dest_desc, src_sb);
1664 #if HAVE_FCLONEFILEAT && !USE_XATTR
1665 set_dest_mode:
1666 #endif
1667 if (x->preserve_mode || x->move_mode)
1669 if (xcopy_acl (src_name, source_desc, dst_name, dest_desc, src_mode) != 0
1670 && x->require_preserve)
1671 return_val = false;
1673 else if (x->set_mode)
1675 if (xset_acl (dst_name, dest_desc, x->mode) != 0)
1676 return_val = false;
1678 else if (x->explicit_no_preserve_mode && *new_dst)
1680 if (xset_acl (dst_name, dest_desc, MODE_RW_UGO & ~cached_umask ()) != 0)
1681 return_val = false;
1683 else if (omitted_permissions | extra_permissions)
1685 omitted_permissions &= ~ cached_umask ();
1686 if ((omitted_permissions | extra_permissions)
1687 && (fchmod_or_lchmod (dest_desc, dst_dirfd, dst_relname,
1688 dst_mode & ~ cached_umask ())
1689 != 0))
1691 error (0, errno, _("preserving permissions for %s"),
1692 quoteaf (dst_name));
1693 if (x->require_preserve)
1694 return_val = false;
1698 if (dest_desc < 0)
1699 goto close_src_desc;
1701 close_src_and_dst_desc:
1702 if (close (dest_desc) < 0)
1704 error (0, errno, _("failed to close %s"), quoteaf (dst_name));
1705 return_val = false;
1707 close_src_desc:
1708 if (close (source_desc) < 0)
1710 error (0, errno, _("failed to close %s"), quoteaf (src_name));
1711 return_val = false;
1714 /* Output debug info for data copying operations. */
1715 if (x->debug)
1716 emit_debug (x);
1718 alignfree (buf);
1719 return return_val;
1722 /* Return whether it's OK that two files are the "same" by some measure.
1723 The first file is SRC_NAME and has status SRC_SB.
1724 The second is DST_DIRFD+DST_RELNAME and has status DST_SB.
1725 The copying options are X. The goal is to avoid
1726 making the 'copy' operation remove both copies of the file
1727 in that case, while still allowing the user to e.g., move or
1728 copy a regular file onto a symlink that points to it.
1729 Try to minimize the cost of this function in the common case.
1730 Set *RETURN_NOW if we've determined that the caller has no more
1731 work to do and should return successfully, right away. */
1733 static bool
1734 same_file_ok (char const *src_name, struct stat const *src_sb,
1735 int dst_dirfd, char const *dst_relname, struct stat const *dst_sb,
1736 const struct cp_options *x, bool *return_now)
1738 const struct stat *src_sb_link;
1739 const struct stat *dst_sb_link;
1740 struct stat tmp_dst_sb;
1741 struct stat tmp_src_sb;
1743 bool same_link;
1744 bool same = psame_inode (src_sb, dst_sb);
1746 *return_now = false;
1748 /* FIXME: this should (at the very least) be moved into the following
1749 if-block. More likely, it should be removed, because it inhibits
1750 making backups. But removing it will result in a change in behavior
1751 that will probably have to be documented -- and tests will have to
1752 be updated. */
1753 if (same && x->hard_link)
1755 *return_now = true;
1756 return true;
1759 if (x->dereference == DEREF_NEVER)
1761 same_link = same;
1763 /* If both the source and destination files are symlinks (and we'll
1764 know this here IFF preserving symlinks), then it's usually ok
1765 when they are distinct. */
1766 if (S_ISLNK (src_sb->st_mode) && S_ISLNK (dst_sb->st_mode))
1768 bool sn = same_nameat (AT_FDCWD, src_name, dst_dirfd, dst_relname);
1769 if ( ! sn)
1771 /* It's fine when we're making any type of backup. */
1772 if (x->backup_type != no_backups)
1773 return true;
1775 /* Here we have two symlinks that are hard-linked together,
1776 and we're not making backups. In this unusual case, simply
1777 returning true would lead to mv calling "rename(A,B)",
1778 which would do nothing and return 0. */
1779 if (same_link)
1781 *return_now = true;
1782 return ! x->move_mode;
1786 return ! sn;
1789 src_sb_link = src_sb;
1790 dst_sb_link = dst_sb;
1792 else
1794 if (!same)
1795 return true;
1797 if (fstatat (dst_dirfd, dst_relname, &tmp_dst_sb,
1798 AT_SYMLINK_NOFOLLOW) != 0
1799 || lstat (src_name, &tmp_src_sb) != 0)
1800 return true;
1802 src_sb_link = &tmp_src_sb;
1803 dst_sb_link = &tmp_dst_sb;
1805 same_link = psame_inode (src_sb_link, dst_sb_link);
1807 /* If both are symlinks, then it's ok, but only if the destination
1808 will be unlinked before being opened. This is like the test
1809 above, but with the addition of the unlink_dest_before_opening
1810 conjunct because otherwise, with two symlinks to the same target,
1811 we'd end up truncating the source file. */
1812 if (S_ISLNK (src_sb_link->st_mode) && S_ISLNK (dst_sb_link->st_mode)
1813 && x->unlink_dest_before_opening)
1814 return true;
1817 /* The backup code ensures there's a copy, so it's usually ok to
1818 remove any destination file. One exception is when both
1819 source and destination are the same directory entry. In that
1820 case, moving the destination file aside (in making the backup)
1821 would also rename the source file and result in an error. */
1822 if (x->backup_type != no_backups)
1824 if (!same_link)
1826 /* In copy mode when dereferencing symlinks, if the source is a
1827 symlink and the dest is not, then backing up the destination
1828 (moving it aside) would make it a dangling symlink, and the
1829 subsequent attempt to open it in copy_reg would fail with
1830 a misleading diagnostic. Avoid that by returning zero in
1831 that case so the caller can make cp (or mv when it has to
1832 resort to reading the source file) fail now. */
1834 /* FIXME-note: even with the following kludge, we can still provoke
1835 the offending diagnostic. It's just a little harder to do :-)
1836 $ rm -f a b c; touch c; ln -s c b; ln -s b a; cp -b a b
1837 cp: cannot open 'a' for reading: No such file or directory
1838 That's misleading, since a subsequent 'ls' shows that 'a'
1839 is still there.
1840 One solution would be to open the source file *before* moving
1841 aside the destination, but that'd involve a big rewrite. */
1842 if ( ! x->move_mode
1843 && x->dereference != DEREF_NEVER
1844 && S_ISLNK (src_sb_link->st_mode)
1845 && ! S_ISLNK (dst_sb_link->st_mode))
1846 return false;
1848 return true;
1851 /* FIXME: What about case insensitive file systems ? */
1852 return ! same_nameat (AT_FDCWD, src_name, dst_dirfd, dst_relname);
1855 #if 0
1856 /* FIXME: use or remove */
1858 /* If we're making a backup, we'll detect the problem case in
1859 copy_reg because SRC_NAME will no longer exist. Allowing
1860 the test to be deferred lets cp do some useful things.
1861 But when creating hardlinks and SRC_NAME is a symlink
1862 but DST_RELNAME is not we must test anyway. */
1863 if (x->hard_link
1864 || !S_ISLNK (src_sb_link->st_mode)
1865 || S_ISLNK (dst_sb_link->st_mode))
1866 return true;
1868 if (x->dereference != DEREF_NEVER)
1869 return true;
1870 #endif
1872 if (x->move_mode || x->unlink_dest_before_opening)
1874 /* They may refer to the same file if we're in move mode and the
1875 target is a symlink. That is ok, since we remove any existing
1876 destination file before opening it -- via 'rename' if they're on
1877 the same file system, via unlinkat otherwise. */
1878 if (S_ISLNK (dst_sb_link->st_mode))
1879 return true;
1881 /* It's not ok if they're distinct hard links to the same file as
1882 this causes a race condition and we may lose data in this case. */
1883 if (same_link
1884 && 1 < dst_sb_link->st_nlink
1885 && ! same_nameat (AT_FDCWD, src_name, dst_dirfd, dst_relname))
1886 return ! x->move_mode;
1889 /* If neither is a symlink, then it's ok as long as they aren't
1890 hard links to the same file. */
1891 if (!S_ISLNK (src_sb_link->st_mode) && !S_ISLNK (dst_sb_link->st_mode))
1893 if (!psame_inode (src_sb_link, dst_sb_link))
1894 return true;
1896 /* If they are the same file, it's ok if we're making hard links. */
1897 if (x->hard_link)
1899 *return_now = true;
1900 return true;
1904 /* At this point, it is normally an error (data loss) to move a symlink
1905 onto its referent, but in at least one narrow case, it is not:
1906 In move mode, when
1907 1) src is a symlink,
1908 2) dest has a link count of 2 or more and
1909 3) dest and the referent of src are not the same directory entry,
1910 then it's ok, since while we'll lose one of those hard links,
1911 src will still point to a remaining link.
1912 Note that technically, condition #3 obviates condition #2, but we
1913 retain the 1 < st_nlink condition because that means fewer invocations
1914 of the more expensive #3.
1916 Given this,
1917 $ touch f && ln f l && ln -s f s
1918 $ ls -og f l s
1919 -rw-------. 2 0 Jan 4 22:46 f
1920 -rw-------. 2 0 Jan 4 22:46 l
1921 lrwxrwxrwx. 1 1 Jan 4 22:46 s -> f
1922 this must fail: mv s f
1923 this must succeed: mv s l */
1924 if (x->move_mode
1925 && S_ISLNK (src_sb->st_mode)
1926 && 1 < dst_sb_link->st_nlink)
1928 char *abs_src = canonicalize_file_name (src_name);
1929 if (abs_src)
1931 bool result = ! same_nameat (AT_FDCWD, abs_src,
1932 dst_dirfd, dst_relname);
1933 free (abs_src);
1934 return result;
1938 /* It's ok to recreate a destination symlink. */
1939 if (x->symbolic_link && S_ISLNK (dst_sb_link->st_mode))
1940 return true;
1942 if (x->dereference == DEREF_NEVER)
1944 if ( ! S_ISLNK (src_sb_link->st_mode))
1945 tmp_src_sb = *src_sb_link;
1946 else if (stat (src_name, &tmp_src_sb) != 0)
1947 return true;
1949 if ( ! S_ISLNK (dst_sb_link->st_mode))
1950 tmp_dst_sb = *dst_sb_link;
1951 else if (fstatat (dst_dirfd, dst_relname, &tmp_dst_sb, 0) != 0)
1952 return true;
1954 if (!psame_inode (&tmp_src_sb, &tmp_dst_sb))
1955 return true;
1957 if (x->hard_link)
1959 /* It's ok to attempt to hardlink the same file,
1960 and return early if not replacing a symlink.
1961 Note we need to return early to avoid a later
1962 unlink() of DST (when SRC is a symlink). */
1963 *return_now = ! S_ISLNK (dst_sb_link->st_mode);
1964 return true;
1968 return false;
1971 /* Return whether DST_DIRFD+DST_RELNAME, with mode MODE,
1972 is writable in the sense of 'mv'.
1973 Always consider a symbolic link to be writable. */
1974 static bool
1975 writable_destination (int dst_dirfd, char const *dst_relname, mode_t mode)
1977 return (S_ISLNK (mode)
1978 || can_write_any_file ()
1979 || faccessat (dst_dirfd, dst_relname, W_OK, AT_EACCESS) == 0);
1982 static bool
1983 overwrite_ok (struct cp_options const *x, char const *dst_name,
1984 int dst_dirfd, char const *dst_relname,
1985 struct stat const *dst_sb)
1987 if (! writable_destination (dst_dirfd, dst_relname, dst_sb->st_mode))
1989 char perms[12]; /* "-rwxrwxrwx " ls-style modes. */
1990 strmode (dst_sb->st_mode, perms);
1991 perms[10] = '\0';
1992 fprintf (stderr,
1993 (x->move_mode || x->unlink_dest_before_opening
1994 || x->unlink_dest_after_failed_open)
1995 ? _("%s: replace %s, overriding mode %04lo (%s)? ")
1996 : _("%s: unwritable %s (mode %04lo, %s); try anyway? "),
1997 program_name, quoteaf (dst_name),
1998 (unsigned long int) (dst_sb->st_mode & CHMOD_MODE_BITS),
1999 &perms[1]);
2001 else
2003 fprintf (stderr, _("%s: overwrite %s? "),
2004 program_name, quoteaf (dst_name));
2007 return yesno ();
2010 /* Initialize the hash table implementing a set of F_triple entries
2011 corresponding to destination files. */
2012 extern void
2013 dest_info_init (struct cp_options *x)
2015 x->dest_info
2016 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
2017 nullptr,
2018 triple_hash,
2019 triple_compare,
2020 triple_free);
2021 if (! x->dest_info)
2022 xalloc_die ();
2025 /* Initialize the hash table implementing a set of F_triple entries
2026 corresponding to source files listed on the command line. */
2027 extern void
2028 src_info_init (struct cp_options *x)
2031 /* Note that we use triple_hash_no_name here.
2032 Contrast with the use of triple_hash above.
2033 That is necessary because a source file may be specified
2034 in many different ways. We want to warn about this
2035 cp a a d/
2036 as well as this:
2037 cp a ./a d/
2039 x->src_info
2040 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
2041 nullptr,
2042 triple_hash_no_name,
2043 triple_compare,
2044 triple_free);
2045 if (! x->src_info)
2046 xalloc_die ();
2049 /* When effecting a move (e.g., for mv(1)), and given the name DST_NAME
2050 aka DST_DIRFD+DST_RELNAME
2051 of the destination and a corresponding stat buffer, DST_SB, return
2052 true if the logical 'move' operation should _not_ proceed.
2053 Otherwise, return false.
2054 Depending on options specified in X, this code may issue an
2055 interactive prompt asking whether it's ok to overwrite DST_NAME. */
2056 static bool
2057 abandon_move (const struct cp_options *x,
2058 char const *dst_name,
2059 int dst_dirfd, char const *dst_relname,
2060 struct stat const *dst_sb)
2062 affirm (x->move_mode);
2063 return (x->interactive == I_ALWAYS_NO
2064 || x->interactive == I_ALWAYS_SKIP
2065 || ((x->interactive == I_ASK_USER
2066 || (x->interactive == I_UNSPECIFIED
2067 && x->stdin_tty
2068 && ! writable_destination (dst_dirfd, dst_relname,
2069 dst_sb->st_mode)))
2070 && ! overwrite_ok (x, dst_name, dst_dirfd, dst_relname, dst_sb)));
2073 /* Print --verbose output on standard output, e.g. 'new' -> 'old'.
2074 If BACKUP_DST_NAME is non-null, then also indicate that it is
2075 the name of a backup file. */
2076 static void
2077 emit_verbose (char const *format, char const *src, char const *dst,
2078 char const *backup_dst_name)
2080 printf (format, quoteaf_n (0, src), quoteaf_n (1, dst));
2081 if (backup_dst_name)
2082 printf (_(" (backup: %s)"), quoteaf (backup_dst_name));
2083 putchar ('\n');
2086 /* A wrapper around "setfscreatecon (nullptr)" that exits upon failure. */
2087 static void
2088 restore_default_fscreatecon_or_die (void)
2090 if (setfscreatecon (nullptr) != 0)
2091 error (EXIT_FAILURE, errno,
2092 _("failed to restore the default file creation context"));
2095 /* Return a newly-allocated string that is like STR
2096 except replace its suffix SUFFIX with NEWSUFFIX. */
2097 static char *
2098 subst_suffix (char const *str, char const *suffix, char const *newsuffix)
2100 idx_t prefixlen = suffix - str;
2101 idx_t newsuffixsize = strlen (newsuffix) + 1;
2102 char *r = ximalloc (prefixlen + newsuffixsize);
2103 memcpy (r + prefixlen, newsuffix, newsuffixsize);
2104 return memcpy (r, str, prefixlen);
2107 /* Create a hard link to SRC_NAME aka SRC_DIRFD+SRC_RELNAME;
2108 the new link is at DST_NAME aka DST_DIRFD+DST_RELNAME.
2109 A null SRC_NAME stands for the file whose name is like DST_NAME
2110 except with DST_RELNAME replaced with SRC_RELNAME.
2111 Honor the REPLACE, VERBOSE and DEREFERENCE settings.
2112 Return true upon success. Otherwise, diagnose the
2113 failure and return false. If SRC_NAME is a symbolic link, then it will not
2114 be followed unless DEREFERENCE is true.
2115 If the system doesn't support hard links to symbolic links, then DST_NAME
2116 will be created as a symbolic link to SRC_NAME. */
2117 static bool
2118 create_hard_link (char const *src_name, int src_dirfd, char const *src_relname,
2119 char const *dst_name, int dst_dirfd, char const *dst_relname,
2120 bool replace, bool verbose, bool dereference)
2122 int err = force_linkat (src_dirfd, src_relname, dst_dirfd, dst_relname,
2123 dereference ? AT_SYMLINK_FOLLOW : 0,
2124 replace, -1);
2125 if (0 < err)
2128 char *a_src_name = nullptr;
2129 if (!src_name)
2130 src_name = a_src_name = subst_suffix (dst_name, dst_relname,
2131 src_relname);
2132 error (0, err, _("cannot create hard link %s to %s"),
2133 quoteaf_n (0, dst_name), quoteaf_n (1, src_name));
2134 free (a_src_name);
2135 return false;
2137 if (err < 0 && verbose)
2138 printf (_("removed %s\n"), quoteaf (dst_name));
2139 return true;
2142 /* Return true if the current file should be (tried to be) dereferenced:
2143 either for DEREF_ALWAYS or for DEREF_COMMAND_LINE_ARGUMENTS in the case
2144 where the current file is a COMMAND_LINE_ARG; otherwise return false. */
2145 ATTRIBUTE_PURE
2146 static inline bool
2147 should_dereference (const struct cp_options *x, bool command_line_arg)
2149 return x->dereference == DEREF_ALWAYS
2150 || (x->dereference == DEREF_COMMAND_LINE_ARGUMENTS
2151 && command_line_arg);
2154 /* Return true if the source file with basename SRCBASE and status SRC_ST
2155 is likely to be the simple backup file for DST_DIRFD+DST_RELNAME. */
2156 static bool
2157 source_is_dst_backup (char const *srcbase, struct stat const *src_st,
2158 int dst_dirfd, char const *dst_relname)
2160 size_t srcbaselen = strlen (srcbase);
2161 char const *dstbase = last_component (dst_relname);
2162 size_t dstbaselen = strlen (dstbase);
2163 size_t suffixlen = strlen (simple_backup_suffix);
2164 if (! (srcbaselen == dstbaselen + suffixlen
2165 && memcmp (srcbase, dstbase, dstbaselen) == 0
2166 && STREQ (srcbase + dstbaselen, simple_backup_suffix)))
2167 return false;
2168 char *dst_back = subst_suffix (dst_relname,
2169 dst_relname + strlen (dst_relname),
2170 simple_backup_suffix);
2171 struct stat dst_back_sb;
2172 int dst_back_status = fstatat (dst_dirfd, dst_back, &dst_back_sb, 0);
2173 free (dst_back);
2174 return dst_back_status == 0 && psame_inode (src_st, &dst_back_sb);
2177 /* Copy the file SRC_NAME to the file DST_NAME aka DST_DIRFD+DST_RELNAME.
2178 If NONEXISTENT_DST is positive, DST_NAME does not exist even as a
2179 dangling symlink; if negative, it does not exist except possibly
2180 as a dangling symlink; if zero, its existence status is unknown.
2181 A non-null PARENT describes the parent directory.
2182 ANCESTORS points to a linked, null terminated list of
2183 devices and inodes of parent directories of SRC_NAME.
2184 X summarizes the command-line options.
2185 COMMAND_LINE_ARG means SRC_NAME was specified on the command line.
2186 FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG is both input and output.
2187 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
2188 same as) DST_NAME; otherwise, clear it.
2189 If X->move_mode, set *RENAME_SUCCEEDED according to whether
2190 the source was simply renamed to the destination.
2191 Return true if successful. */
2192 static bool
2193 copy_internal (char const *src_name, char const *dst_name,
2194 int dst_dirfd, char const *dst_relname,
2195 int nonexistent_dst,
2196 struct stat const *parent,
2197 struct dir_list *ancestors,
2198 const struct cp_options *x,
2199 bool command_line_arg,
2200 bool *first_dir_created_per_command_line_arg,
2201 bool *copy_into_self,
2202 bool *rename_succeeded)
2204 struct stat src_sb;
2205 struct stat dst_sb;
2206 mode_t src_mode IF_LINT ( = 0);
2207 mode_t dst_mode IF_LINT ( = 0);
2208 mode_t dst_mode_bits;
2209 mode_t omitted_permissions;
2210 bool restore_dst_mode = false;
2211 char *earlier_file = nullptr;
2212 char *dst_backup = nullptr;
2213 char const *drelname = *dst_relname ? dst_relname : ".";
2214 bool delayed_ok;
2215 bool copied_as_regular = false;
2216 bool dest_is_symlink = false;
2217 bool have_dst_lstat = false;
2219 *copy_into_self = false;
2221 int rename_errno = x->rename_errno;
2222 if (x->move_mode && !x->exchange)
2224 if (rename_errno < 0)
2225 rename_errno = (renameatu (AT_FDCWD, src_name, dst_dirfd, drelname,
2226 RENAME_NOREPLACE)
2227 ? errno : 0);
2228 nonexistent_dst = *rename_succeeded = rename_errno == 0;
2231 if (rename_errno == 0
2232 ? !x->last_file
2233 : rename_errno != EEXIST
2234 || (x->interactive != I_ALWAYS_NO && x->interactive != I_ALWAYS_SKIP))
2236 char const *name = rename_errno == 0 ? dst_name : src_name;
2237 int dirfd = rename_errno == 0 ? dst_dirfd : AT_FDCWD;
2238 char const *relname = rename_errno == 0 ? drelname : src_name;
2239 int fstatat_flags
2240 = x->dereference == DEREF_NEVER ? AT_SYMLINK_NOFOLLOW : 0;
2241 if (follow_fstatat (dirfd, relname, &src_sb, fstatat_flags) != 0)
2243 error (0, errno, _("cannot stat %s"), quoteaf (name));
2244 return false;
2247 src_mode = src_sb.st_mode;
2249 if (S_ISDIR (src_mode) && !x->recursive)
2251 error (0, 0, ! x->install_mode /* cp */
2252 ? _("-r not specified; omitting directory %s")
2253 : _("omitting directory %s"),
2254 quoteaf (src_name));
2255 return false;
2258 else
2260 #if defined lint && (defined __clang__ || defined __COVERITY__)
2261 affirm (x->move_mode);
2262 memset (&src_sb, 0, sizeof src_sb);
2263 #endif
2266 /* Detect the case in which the same source file appears more than
2267 once on the command line and no backup option has been selected.
2268 If so, simply warn and don't copy it the second time.
2269 This check is enabled only if x->src_info is non-null. */
2270 if (command_line_arg && x->src_info)
2272 if ( ! S_ISDIR (src_mode)
2273 && x->backup_type == no_backups
2274 && seen_file (x->src_info, src_name, &src_sb))
2276 error (0, 0, _("warning: source file %s specified more than once"),
2277 quoteaf (src_name));
2278 return true;
2281 record_file (x->src_info, src_name, &src_sb);
2284 bool dereference = should_dereference (x, command_line_arg);
2286 /* Whether the destination is (or was) known to be new, updated as
2287 more info comes in. This may become true if the destination is a
2288 dangling symlink, in contexts where dangling symlinks should be
2289 treated the same as nonexistent files. */
2290 bool new_dst = 0 < nonexistent_dst;
2292 if (! new_dst)
2294 /* Normally, fill in DST_SB or set NEW_DST so that later code
2295 can use DST_SB if NEW_DST is false. However, don't bother
2296 doing this when rename_errno == EEXIST and X->interactive is
2297 I_ALWAYS_NO or I_ALWAYS_SKIP, something that can happen only
2298 with mv in which case x->update must be false which means
2299 that even if !NEW_DST the move will be abandoned without
2300 looking at DST_SB. */
2301 if (! (rename_errno == EEXIST
2302 && (x->interactive == I_ALWAYS_NO
2303 || x->interactive == I_ALWAYS_SKIP)))
2305 /* Regular files can be created by writing through symbolic
2306 links, but other files cannot. So use stat on the
2307 destination when copying a regular file, and lstat otherwise.
2308 However, if we intend to unlink or remove the destination
2309 first, use lstat, since a copy won't actually be made to the
2310 destination in that case. */
2311 bool use_lstat
2312 = ((! S_ISREG (src_mode)
2313 && (! x->copy_as_regular
2314 || (S_ISDIR (src_mode) && !x->keep_directory_symlink)
2315 || S_ISLNK (src_mode)))
2316 || x->move_mode || x->symbolic_link || x->hard_link
2317 || x->backup_type != no_backups
2318 || x->unlink_dest_before_opening);
2319 if (!use_lstat && nonexistent_dst < 0)
2320 new_dst = true;
2321 else if (0 <= follow_fstatat (dst_dirfd, drelname, &dst_sb,
2322 use_lstat ? AT_SYMLINK_NOFOLLOW : 0))
2324 have_dst_lstat = use_lstat;
2325 rename_errno = EEXIST;
2327 else if (errno == ENOENT)
2328 new_dst = true;
2329 else if (errno == ELOOP && !use_lstat
2330 && x->unlink_dest_after_failed_open)
2332 /* cp -f's destination might be a symlink loop.
2333 Leave new_dst=false so that we try to unlink later. */
2335 else
2337 error (0, errno, _("cannot stat %s"), quoteaf (dst_name));
2338 return false;
2342 if (rename_errno == EEXIST)
2344 bool return_now = false;
2345 bool return_val = true;
2346 bool skipped = false;
2348 if ((x->interactive != I_ALWAYS_NO && x->interactive != I_ALWAYS_SKIP)
2349 && ! same_file_ok (src_name, &src_sb, dst_dirfd, drelname,
2350 &dst_sb, x, &return_now))
2352 error (0, 0, _("%s and %s are the same file"),
2353 quoteaf_n (0, src_name), quoteaf_n (1, dst_name));
2354 return false;
2357 if (x->update && !S_ISDIR (src_mode))
2359 /* When preserving timestamps (but not moving within a file
2360 system), don't worry if the destination timestamp is
2361 less than the source merely because of timestamp
2362 truncation. */
2363 int options = ((x->preserve_timestamps
2364 && ! (x->move_mode
2365 && dst_sb.st_dev == src_sb.st_dev))
2366 ? UTIMECMP_TRUNCATE_SOURCE
2367 : 0);
2369 if (0 <= utimecmpat (dst_dirfd, dst_relname, &dst_sb,
2370 &src_sb, options))
2372 /* We're using --update and the destination is not older
2373 than the source, so do not copy or move. Pretend the
2374 rename succeeded, so the caller (if it's mv) doesn't
2375 end up removing the source file. */
2376 if (rename_succeeded)
2377 *rename_succeeded = true;
2379 /* However, we still must record that we've processed
2380 this src/dest pair, in case this source file is
2381 hard-linked to another one. In that case, we'll use
2382 the mapping information to link the corresponding
2383 destination names. */
2384 earlier_file = remember_copied (dst_relname, src_sb.st_ino,
2385 src_sb.st_dev);
2386 if (earlier_file)
2388 /* Note we currently replace DST_NAME unconditionally,
2389 even if it was a newer separate file. */
2390 if (! create_hard_link (nullptr, dst_dirfd, earlier_file,
2391 dst_name, dst_dirfd, dst_relname,
2392 true,
2393 x->verbose, dereference))
2395 goto un_backup;
2399 skipped = true;
2400 goto skip;
2404 /* When there is an existing destination file, we may end up
2405 returning early, and hence not copying/moving the file.
2406 This may be due to an interactive 'negative' reply to the
2407 prompt about the existing file. It may also be due to the
2408 use of the --no-clobber option.
2410 cp and mv treat -i and -f differently. */
2411 if (x->move_mode)
2413 if (abandon_move (x, dst_name, dst_dirfd, drelname, &dst_sb))
2415 /* Pretend the rename succeeded, so the caller (mv)
2416 doesn't end up removing the source file. */
2417 if (rename_succeeded)
2418 *rename_succeeded = true;
2420 skipped = true;
2421 return_val = x->interactive == I_ALWAYS_SKIP;
2424 else
2426 if (! S_ISDIR (src_mode)
2427 && (x->interactive == I_ALWAYS_NO
2428 || x->interactive == I_ALWAYS_SKIP
2429 || (x->interactive == I_ASK_USER
2430 && ! overwrite_ok (x, dst_name, dst_dirfd,
2431 dst_relname, &dst_sb))))
2433 skipped = true;
2434 return_val = x->interactive == I_ALWAYS_SKIP;
2438 skip:
2439 if (skipped)
2441 if (x->interactive == I_ALWAYS_NO)
2442 error (0, 0, _("not replacing %s"), quoteaf (dst_name));
2443 else if (x->debug)
2444 printf (_("skipped %s\n"), quoteaf (dst_name));
2446 return_now = true;
2449 if (return_now)
2450 return return_val;
2452 /* Copying a directory onto a non-directory, or vice versa,
2453 is ok only with --backup or --exchange. */
2454 if (!S_ISDIR (src_mode) != !S_ISDIR (dst_sb.st_mode)
2455 && x->backup_type == no_backups && !x->exchange)
2457 error (0, 0,
2458 _(S_ISDIR (src_mode)
2459 ? ("cannot overwrite non-directory %s "
2460 "with directory %s")
2461 : ("cannot overwrite directory %s "
2462 "with non-directory %s")),
2463 quoteaf_n (0, dst_name), quoteaf_n (1, src_name));
2464 return false;
2467 /* Don't let the user destroy their data, even if they try hard:
2468 This mv command must fail (likewise for cp):
2469 rm -rf a b c; mkdir a b c; touch a/f b/f; mv a/f b/f c
2470 Otherwise, the contents of b/f would be lost.
2471 In the case of 'cp', b/f would be lost if the user simulated
2472 a move using cp and rm.
2473 Nothing is lost if you use --backup=numbered or --exchange. */
2474 if (!S_ISDIR (dst_sb.st_mode) && command_line_arg
2475 && x->backup_type != numbered_backups && !x->exchange
2476 && seen_file (x->dest_info, dst_relname, &dst_sb))
2478 error (0, 0,
2479 _("will not overwrite just-created %s with %s"),
2480 quoteaf_n (0, dst_name), quoteaf_n (1, src_name));
2481 return false;
2484 char const *srcbase;
2485 if (x->backup_type != no_backups
2486 /* Don't try to back up a destination if the last
2487 component of src_name is "." or "..". */
2488 && ! dot_or_dotdot (srcbase = last_component (src_name))
2489 /* Create a backup of each destination directory in move mode,
2490 but not in copy mode. FIXME: it might make sense to add an
2491 option to suppress backup creation also for move mode.
2492 That would let one use mv to merge new content into an
2493 existing hierarchy. */
2494 && (x->move_mode || ! S_ISDIR (dst_sb.st_mode)))
2496 /* Fail if creating the backup file would likely destroy
2497 the source file. Otherwise, the commands:
2498 cd /tmp; rm -f a a~; : > a; echo A > a~; cp --b=simple a~ a
2499 would leave two zero-length files: a and a~. */
2500 if (x->backup_type != numbered_backups
2501 && source_is_dst_backup (srcbase, &src_sb,
2502 dst_dirfd, dst_relname))
2504 char const *fmt;
2505 fmt = (x->move_mode
2506 ? _("backing up %s might destroy source; %s not moved")
2507 : _("backing up %s might destroy source; %s not copied"));
2508 error (0, 0, fmt,
2509 quoteaf_n (0, dst_name),
2510 quoteaf_n (1, src_name));
2511 return false;
2514 char *tmp_backup = backup_file_rename (dst_dirfd, dst_relname,
2515 x->backup_type);
2517 /* FIXME: use fts:
2518 Using alloca for a file name that may be arbitrarily
2519 long is not recommended. In fact, even forming such a name
2520 should be discouraged. Eventually, this code will be rewritten
2521 to use fts, so using alloca here will be less of a problem. */
2522 if (tmp_backup)
2524 idx_t dirlen = dst_relname - dst_name;
2525 idx_t backupsize = strlen (tmp_backup) + 1;
2526 dst_backup = alloca (dirlen + backupsize);
2527 memcpy (mempcpy (dst_backup, dst_name, dirlen),
2528 tmp_backup, backupsize);
2529 free (tmp_backup);
2531 else if (errno != ENOENT)
2533 error (0, errno, _("cannot backup %s"), quoteaf (dst_name));
2534 return false;
2536 new_dst = true;
2538 else if (! S_ISDIR (dst_sb.st_mode)
2539 /* Never unlink dst_name when in move mode. */
2540 && ! x->move_mode
2541 && (x->unlink_dest_before_opening
2542 || (x->data_copy_required
2543 && ((x->preserve_links && 1 < dst_sb.st_nlink)
2544 || (x->dereference == DEREF_NEVER
2545 && ! S_ISREG (src_sb.st_mode))))
2548 if (unlinkat (dst_dirfd, dst_relname, 0) != 0 && errno != ENOENT)
2550 error (0, errno, _("cannot remove %s"), quoteaf (dst_name));
2551 return false;
2553 new_dst = true;
2554 if (x->verbose)
2555 printf (_("removed %s\n"), quoteaf (dst_name));
2560 /* Ensure we don't try to copy through a symlink that was
2561 created by a prior call to this function. */
2562 if (command_line_arg
2563 && x->dest_info
2564 && ! x->move_mode
2565 && x->backup_type == no_backups)
2567 /* If we did not follow symlinks above, good: use that data.
2568 Otherwise, use AT_SYMLINK_NOFOLLOW, in case dst_name is a symlink. */
2569 struct stat tmp_buf;
2570 struct stat *dst_lstat_sb
2571 = (have_dst_lstat ? &dst_sb
2572 : fstatat (dst_dirfd, drelname, &tmp_buf, AT_SYMLINK_NOFOLLOW) < 0
2573 ? nullptr : &tmp_buf);
2575 /* Never copy through a symlink we've just created. */
2576 if (dst_lstat_sb
2577 && S_ISLNK (dst_lstat_sb->st_mode)
2578 && seen_file (x->dest_info, dst_relname, dst_lstat_sb))
2580 error (0, 0,
2581 _("will not copy %s through just-created symlink %s"),
2582 quoteaf_n (0, src_name), quoteaf_n (1, dst_name));
2583 return false;
2587 /* If the source is a directory, we don't always create the destination
2588 directory. So --verbose should not announce anything until we're
2589 sure we'll create a directory. Also don't announce yet when moving
2590 so we can distinguish renames versus copies. */
2591 if (x->verbose && !x->move_mode && !S_ISDIR (src_mode))
2592 emit_verbose ("%s -> %s", src_name, dst_name, dst_backup);
2594 /* Associate the destination file name with the source device and inode
2595 so that if we encounter a matching dev/ino pair in the source tree
2596 we can arrange to create a hard link between the corresponding names
2597 in the destination tree.
2599 When using the --link (-l) option, there is no need to take special
2600 measures, because (barring race conditions) files that are hard-linked
2601 in the source tree will also be hard-linked in the destination tree.
2603 Sometimes, when preserving links, we have to record dev/ino even
2604 though st_nlink == 1:
2605 - when in move_mode, since we may be moving a group of N hard-linked
2606 files (via two or more command line arguments) to a different
2607 partition; the links may be distributed among the command line
2608 arguments (possibly hierarchies) so that the link count of
2609 the final, once-linked source file is reduced to 1 when it is
2610 considered below. But in this case (for mv) we don't need to
2611 incur the expense of recording the dev/ino => name mapping; all we
2612 really need is a lookup, to see if the dev/ino pair has already
2613 been copied.
2614 - when using -H and processing a command line argument;
2615 that command line argument could be a symlink pointing to another
2616 command line argument. With 'cp -H --preserve=link', we hard-link
2617 those two destination files.
2618 - likewise for -L except that it applies to all files, not just
2619 command line arguments.
2621 Also, with --recursive, record dev/ino of each command-line directory.
2622 We'll use that info to detect this problem: cp -R dir dir. */
2624 if (rename_errno == 0 || x->exchange)
2625 earlier_file = nullptr;
2626 else if (x->recursive && S_ISDIR (src_mode))
2628 if (command_line_arg)
2629 earlier_file = remember_copied (dst_relname,
2630 src_sb.st_ino, src_sb.st_dev);
2631 else
2632 earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev);
2634 else if (x->move_mode && src_sb.st_nlink == 1)
2636 earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev);
2638 else if (x->preserve_links
2639 && !x->hard_link
2640 && (1 < src_sb.st_nlink
2641 || (command_line_arg
2642 && x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
2643 || x->dereference == DEREF_ALWAYS))
2645 earlier_file = remember_copied (dst_relname,
2646 src_sb.st_ino, src_sb.st_dev);
2649 /* Did we copy this inode somewhere else (in this command line argument)
2650 and therefore this is a second hard link to the inode? */
2652 if (earlier_file)
2654 /* Avoid damaging the destination file system by refusing to preserve
2655 hard-linked directories (which are found at least in Netapp snapshot
2656 directories). */
2657 if (S_ISDIR (src_mode))
2659 /* If src_name and earlier_file refer to the same directory entry,
2660 then warn about copying a directory into itself. */
2661 if (same_nameat (AT_FDCWD, src_name, dst_dirfd, earlier_file))
2663 error (0, 0, _("cannot copy a directory, %s, into itself, %s"),
2664 quoteaf_n (0, top_level_src_name),
2665 quoteaf_n (1, top_level_dst_name));
2666 *copy_into_self = true;
2667 goto un_backup;
2669 else if (same_nameat (dst_dirfd, dst_relname,
2670 dst_dirfd, earlier_file))
2672 error (0, 0, _("warning: source directory %s "
2673 "specified more than once"),
2674 quoteaf (top_level_src_name));
2675 /* In move mode, if a previous rename succeeded, then
2676 we won't be in this path as the source is missing. If the
2677 rename previously failed, then that has been handled, so
2678 pretend this attempt succeeded so the source isn't removed. */
2679 if (x->move_mode && rename_succeeded)
2680 *rename_succeeded = true;
2681 /* We only do backups in move mode, and for non directories.
2682 So just ignore this repeated entry. */
2683 return true;
2685 else if (x->dereference == DEREF_ALWAYS
2686 || (command_line_arg
2687 && x->dereference == DEREF_COMMAND_LINE_ARGUMENTS))
2689 /* This happens when e.g., encountering a directory for the
2690 second or subsequent time via symlinks when cp is invoked
2691 with -R and -L. E.g.,
2692 rm -rf a b c d; mkdir a b c d; ln -s ../c a; ln -s ../c b;
2693 cp -RL a b d
2696 else
2698 char *earlier = subst_suffix (dst_name, dst_relname,
2699 earlier_file);
2700 error (0, 0, _("will not create hard link %s to directory %s"),
2701 quoteaf_n (0, dst_name), quoteaf_n (1, earlier));
2702 free (earlier);
2703 goto un_backup;
2706 else
2708 if (! create_hard_link (nullptr, dst_dirfd, earlier_file,
2709 dst_name, dst_dirfd, dst_relname,
2710 true, x->verbose, dereference))
2711 goto un_backup;
2713 return true;
2717 if (x->move_mode)
2719 if (rename_errno == EEXIST)
2720 rename_errno = ((renameatu (AT_FDCWD, src_name, dst_dirfd, drelname,
2721 x->exchange ? RENAME_EXCHANGE : 0)
2722 == 0)
2723 ? 0 : errno);
2725 if (rename_errno == 0)
2727 if (x->verbose)
2728 emit_verbose (x->exchange
2729 ? _("exchanged %s <-> %s")
2730 : _("renamed %s -> %s"),
2731 src_name, dst_name, dst_backup);
2733 if (x->set_security_context)
2735 /* -Z failures are only warnings currently. */
2736 (void) set_file_security_ctx (dst_name, true, x);
2739 if (rename_succeeded)
2740 *rename_succeeded = true;
2742 if (command_line_arg && !x->last_file)
2744 /* Record destination dev/ino/name, so that if we are asked
2745 to overwrite that file again, we can detect it and fail. */
2746 /* It's fine to use the _source_ stat buffer (src_sb) to get the
2747 _destination_ dev/ino, since the rename above can't have
2748 changed those, and 'mv' always uses lstat.
2749 We could limit it further by operating
2750 only on non-directories when !x->exchange. */
2751 record_file (x->dest_info, dst_relname, &src_sb);
2754 return true;
2757 /* FIXME: someday, consider what to do when moving a directory into
2758 itself but when source and destination are on different devices. */
2760 /* This happens when attempting to rename a directory to a
2761 subdirectory of itself. */
2762 if (rename_errno == EINVAL)
2764 /* FIXME: this is a little fragile in that it relies on rename(2)
2765 failing with a specific errno value. Expect problems on
2766 non-POSIX systems. */
2767 error (0, 0, _("cannot move %s to a subdirectory of itself, %s"),
2768 quoteaf_n (0, top_level_src_name),
2769 quoteaf_n (1, top_level_dst_name));
2771 /* Note that there is no need to call forget_created here,
2772 (compare with the other calls in this file) since the
2773 destination directory didn't exist before. */
2775 *copy_into_self = true;
2776 /* FIXME-cleanup: Don't return true here; adjust mv.c accordingly.
2777 The only caller that uses this code (mv.c) ends up setting its
2778 exit status to nonzero when copy_into_self is nonzero. */
2779 return true;
2782 /* WARNING: there probably exist systems for which an inter-device
2783 rename fails with a value of errno not handled here.
2784 If/as those are reported, add them to the condition below.
2785 If this happens to you, please do the following and send the output
2786 to the bug-reporting address (e.g., in the output of cp --help):
2787 touch k; perl -e 'rename "k","/tmp/k" or print "$!(",$!+0,")\n"'
2788 where your current directory is on one partition and /tmp is the other.
2789 Also, please try to find the E* errno macro name corresponding to
2790 the diagnostic and parenthesized integer, and include that in your
2791 e-mail. One way to do that is to run a command like this
2792 find /usr/include/. -type f \
2793 | xargs grep 'define.*\<E[A-Z]*\>.*\<18\>' /dev/null
2794 where you'd replace '18' with the integer in parentheses that
2795 was output from the perl one-liner above.
2796 If necessary, of course, change '/tmp' to some other directory. */
2797 if (rename_errno != EXDEV || x->no_copy || x->exchange)
2799 /* There are many ways this can happen due to a race condition.
2800 When something happens between the initial follow_fstatat and the
2801 subsequent rename, we can get many different types of errors.
2802 For example, if the destination is initially a non-directory
2803 or non-existent, but it is created as a directory, the rename
2804 fails. If two 'mv' commands try to rename the same file at
2805 about the same time, one will succeed and the other will fail.
2806 If the permissions on the directory containing the source or
2807 destination file are made too restrictive, the rename will
2808 fail. Etc. */
2809 char const *quoted_dst_name = quoteaf_n (1, dst_name);
2810 if (x->exchange)
2811 error (0, rename_errno, _("cannot exchange %s and %s"),
2812 quoteaf_n (0, src_name), quoted_dst_name);
2813 else
2814 switch (rename_errno)
2816 case EDQUOT: case EEXIST: case EISDIR: case EMLINK:
2817 case ENOSPC: case ETXTBSY:
2818 #if ENOTEMPTY != EEXIST
2819 case ENOTEMPTY:
2820 #endif
2821 /* The destination must be the problem. Don't mention
2822 the source as that is more likely to confuse the user
2823 than be helpful. */
2824 error (0, rename_errno, _("cannot overwrite %s"),
2825 quoted_dst_name);
2826 break;
2828 default:
2829 error (0, rename_errno, _("cannot move %s to %s"),
2830 quoteaf_n (0, src_name), quoted_dst_name);
2831 break;
2833 forget_created (src_sb.st_ino, src_sb.st_dev);
2834 return false;
2837 /* The rename attempt has failed. Remove any existing destination
2838 file so that a cross-device 'mv' acts as if it were really using
2839 the rename syscall. Note both src and dst must both be directories
2840 or not, and this is enforced above. Therefore we check the src_mode
2841 and operate on dst_name here as a tighter constraint and also because
2842 src_mode is readily available here. */
2843 if ((unlinkat (dst_dirfd, drelname,
2844 S_ISDIR (src_mode) ? AT_REMOVEDIR : 0)
2845 != 0)
2846 && errno != ENOENT)
2848 error (0, errno,
2849 _("inter-device move failed: %s to %s; unable to remove target"),
2850 quoteaf_n (0, src_name), quoteaf_n (1, dst_name));
2851 forget_created (src_sb.st_ino, src_sb.st_dev);
2852 return false;
2855 if (x->verbose && !S_ISDIR (src_mode))
2856 emit_verbose (_("copied %s -> %s"), src_name, dst_name, dst_backup);
2857 new_dst = true;
2860 /* If the ownership might change, or if it is a directory (whose
2861 special mode bits may change after the directory is created),
2862 omit some permissions at first, so unauthorized users cannot nip
2863 in before the file is ready. */
2864 dst_mode_bits = (x->set_mode ? x->mode : src_mode) & CHMOD_MODE_BITS;
2865 omitted_permissions =
2866 (dst_mode_bits
2867 & (x->preserve_ownership ? S_IRWXG | S_IRWXO
2868 : S_ISDIR (src_mode) ? S_IWGRP | S_IWOTH
2869 : 0));
2871 delayed_ok = true;
2873 /* If required, set the default security context for new files.
2874 Also for existing files this is used as a reference
2875 when copying the context with --preserve=context.
2876 FIXME: Do we need to consider dst_mode_bits here? */
2877 if (! set_process_security_ctx (src_name, dst_name, src_mode, new_dst, x))
2878 return false;
2880 if (S_ISDIR (src_mode))
2882 struct dir_list *dir;
2884 /* If this directory has been copied before during the
2885 recursion, there is a symbolic link to an ancestor
2886 directory of the symbolic link. It is impossible to
2887 continue to copy this, unless we've got an infinite file system. */
2889 if (is_ancestor (&src_sb, ancestors))
2891 error (0, 0, _("cannot copy cyclic symbolic link %s"),
2892 quoteaf (src_name));
2893 goto un_backup;
2896 /* Insert the current directory in the list of parents. */
2898 dir = alloca (sizeof *dir);
2899 dir->parent = ancestors;
2900 dir->ino = src_sb.st_ino;
2901 dir->dev = src_sb.st_dev;
2903 if (new_dst || !S_ISDIR (dst_sb.st_mode))
2905 /* POSIX says mkdir's behavior is implementation-defined when
2906 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
2907 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
2908 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
2909 mode_t mode = dst_mode_bits & ~omitted_permissions;
2910 if (mkdirat (dst_dirfd, drelname, mode) != 0)
2912 error (0, errno, _("cannot create directory %s"),
2913 quoteaf (dst_name));
2914 goto un_backup;
2917 /* We need search and write permissions to the new directory
2918 for writing the directory's contents. Check if these
2919 permissions are there. */
2921 if (fstatat (dst_dirfd, drelname, &dst_sb, AT_SYMLINK_NOFOLLOW) != 0)
2923 error (0, errno, _("cannot stat %s"), quoteaf (dst_name));
2924 goto un_backup;
2926 else if ((dst_sb.st_mode & S_IRWXU) != S_IRWXU)
2928 /* Make the new directory searchable and writable. */
2930 dst_mode = dst_sb.st_mode;
2931 restore_dst_mode = true;
2933 if (lchmodat (dst_dirfd, drelname, dst_mode | S_IRWXU) != 0)
2935 error (0, errno, _("setting permissions for %s"),
2936 quoteaf (dst_name));
2937 goto un_backup;
2941 /* Record the created directory's inode and device numbers into
2942 the search structure, so that we can avoid copying it again.
2943 Do this only for the first directory that is created for each
2944 source command line argument. */
2945 if (!*first_dir_created_per_command_line_arg)
2947 remember_copied (dst_relname, dst_sb.st_ino, dst_sb.st_dev);
2948 *first_dir_created_per_command_line_arg = true;
2951 if (x->verbose)
2953 if (x->move_mode)
2954 printf (_("created directory %s\n"), quoteaf (dst_name));
2955 else
2956 emit_verbose ("%s -> %s", src_name, dst_name, nullptr);
2959 else
2961 omitted_permissions = 0;
2963 /* For directories, the process global context could be reset for
2964 descendants, so use it to set the context for existing dirs here.
2965 This will also give earlier indication of failure to set ctx. */
2966 if (x->set_security_context || x->preserve_security_context)
2967 if (! set_file_security_ctx (dst_name, false, x))
2969 if (x->require_preserve_context)
2970 goto un_backup;
2974 /* Decide whether to copy the contents of the directory. */
2975 if (x->one_file_system && parent && parent->st_dev != src_sb.st_dev)
2977 /* Here, we are crossing a file system boundary and cp's -x option
2978 is in effect: so don't copy the contents of this directory. */
2980 else
2982 /* Copy the contents of the directory. Don't just return if
2983 this fails -- otherwise, the failure to read a single file
2984 in a source directory would cause the containing destination
2985 directory not to have owner/perms set properly. */
2986 delayed_ok = copy_dir (src_name, dst_name, dst_dirfd, dst_relname,
2987 new_dst, &src_sb, dir, x,
2988 first_dir_created_per_command_line_arg,
2989 copy_into_self);
2992 else if (x->symbolic_link)
2994 dest_is_symlink = true;
2995 if (*src_name != '/')
2997 /* Check that DST_NAME denotes a file in the current directory. */
2998 struct stat dot_sb;
2999 struct stat dst_parent_sb;
3000 char *dst_parent;
3001 bool in_current_dir;
3003 dst_parent = dir_name (dst_relname);
3005 in_current_dir = ((dst_dirfd == AT_FDCWD && STREQ (".", dst_parent))
3006 /* If either stat call fails, it's ok not to report
3007 the failure and say dst_name is in the current
3008 directory. Other things will fail later. */
3009 || stat (".", &dot_sb) != 0
3010 || (fstatat (dst_dirfd, dst_parent, &dst_parent_sb,
3011 0) != 0)
3012 || psame_inode (&dot_sb, &dst_parent_sb));
3013 free (dst_parent);
3015 if (! in_current_dir)
3017 error (0, 0,
3018 _("%s: can make relative symbolic links only in current directory"),
3019 quotef (dst_name));
3020 goto un_backup;
3024 int err = force_symlinkat (src_name, dst_dirfd, dst_relname,
3025 x->unlink_dest_after_failed_open, -1);
3026 if (0 < err)
3028 error (0, err, _("cannot create symbolic link %s to %s"),
3029 quoteaf_n (0, dst_name), quoteaf_n (1, src_name));
3030 goto un_backup;
3034 /* POSIX 2008 states that it is implementation-defined whether
3035 link() on a symlink creates a hard-link to the symlink, or only
3036 to the referent (effectively dereferencing the symlink) (POSIX
3037 2001 required the latter behavior, although many systems provided
3038 the former). Yet cp, invoked with '--link --no-dereference',
3039 should not follow the link. We can approximate the desired
3040 behavior by skipping this hard-link creating block and instead
3041 copying the symlink, via the 'S_ISLNK'- copying code below.
3043 Note gnulib's linkat module, guarantees that the symlink is not
3044 dereferenced. However its emulation currently doesn't maintain
3045 timestamps or ownership so we only call it when we know the
3046 emulation will not be needed. */
3047 else if (x->hard_link
3048 && !(! CAN_HARDLINK_SYMLINKS && S_ISLNK (src_mode)
3049 && x->dereference == DEREF_NEVER))
3051 bool replace = (x->unlink_dest_after_failed_open
3052 || x->interactive == I_ASK_USER);
3053 if (! create_hard_link (src_name, AT_FDCWD, src_name,
3054 dst_name, dst_dirfd, dst_relname,
3055 replace, false, dereference))
3056 goto un_backup;
3058 else if (S_ISREG (src_mode)
3059 || (x->copy_as_regular && !S_ISLNK (src_mode)))
3061 copied_as_regular = true;
3062 /* POSIX says the permission bits of the source file must be
3063 used as the 3rd argument in the open call. Historical
3064 practice passed all the source mode bits to 'open', but the extra
3065 bits were ignored, so it should be the same either way.
3067 This call uses DST_MODE_BITS, not SRC_MODE. These are
3068 normally the same, and the exception (where x->set_mode) is
3069 used only by 'install', which POSIX does not specify and
3070 where DST_MODE_BITS is what's wanted. */
3071 if (! copy_reg (src_name, dst_name, dst_dirfd, dst_relname,
3072 x, dst_mode_bits & S_IRWXUGO,
3073 omitted_permissions, &new_dst, &src_sb))
3074 goto un_backup;
3076 else if (S_ISFIFO (src_mode))
3078 /* Use mknodat, rather than mkfifoat, because the former preserves
3079 the special mode bits of a fifo on Solaris 10, while mkfifoat
3080 does not. But fall back on mkfifoat, because on some BSD systems,
3081 mknodat always fails when asked to create a FIFO. */
3082 mode_t mode = src_mode & ~omitted_permissions;
3083 if (mknodat (dst_dirfd, dst_relname, mode, 0) != 0)
3084 if (mkfifoat (dst_dirfd, dst_relname, mode & ~S_IFIFO) != 0)
3086 error (0, errno, _("cannot create fifo %s"), quoteaf (dst_name));
3087 goto un_backup;
3090 else if (S_ISBLK (src_mode) || S_ISCHR (src_mode) || S_ISSOCK (src_mode))
3092 mode_t mode = src_mode & ~omitted_permissions;
3093 if (mknodat (dst_dirfd, dst_relname, mode, src_sb.st_rdev) != 0)
3095 error (0, errno, _("cannot create special file %s"),
3096 quoteaf (dst_name));
3097 goto un_backup;
3100 else if (S_ISLNK (src_mode))
3102 char *src_link_val = areadlink_with_size (src_name, src_sb.st_size);
3103 dest_is_symlink = true;
3104 if (src_link_val == nullptr)
3106 error (0, errno, _("cannot read symbolic link %s"),
3107 quoteaf (src_name));
3108 goto un_backup;
3111 int symlink_err = force_symlinkat (src_link_val, dst_dirfd, dst_relname,
3112 x->unlink_dest_after_failed_open, -1);
3113 if (0 < symlink_err && x->update && !new_dst && S_ISLNK (dst_sb.st_mode)
3114 && dst_sb.st_size == strlen (src_link_val))
3116 /* See if the destination is already the desired symlink.
3117 FIXME: This behavior isn't documented, and seems wrong
3118 in some cases, e.g., if the destination symlink has the
3119 wrong ownership, permissions, or timestamps. */
3120 char *dest_link_val =
3121 areadlinkat_with_size (dst_dirfd, dst_relname, dst_sb.st_size);
3122 if (dest_link_val)
3124 if (STREQ (dest_link_val, src_link_val))
3125 symlink_err = 0;
3126 free (dest_link_val);
3129 free (src_link_val);
3130 if (0 < symlink_err)
3132 error (0, symlink_err, _("cannot create symbolic link %s"),
3133 quoteaf (dst_name));
3134 goto un_backup;
3137 if (x->preserve_security_context)
3138 restore_default_fscreatecon_or_die ();
3140 if (x->preserve_ownership)
3142 /* Preserve the owner and group of the just-'copied'
3143 symbolic link, if possible. */
3144 if (HAVE_LCHOWN
3145 && (lchownat (dst_dirfd, dst_relname,
3146 src_sb.st_uid, src_sb.st_gid)
3147 != 0)
3148 && ! chown_failure_ok (x))
3150 error (0, errno, _("failed to preserve ownership for %s"),
3151 dst_name);
3152 if (x->require_preserve)
3153 goto un_backup;
3155 else
3157 /* Can't preserve ownership of symlinks.
3158 FIXME: maybe give a warning or even error for symlinks
3159 in directories with the sticky bit set -- there, not
3160 preserving owner/group is a potential security problem. */
3164 else
3166 error (0, 0, _("%s has unknown file type"), quoteaf (src_name));
3167 goto un_backup;
3170 /* With -Z or --preserve=context, set the context for existing files.
3171 Note this is done already for copy_reg() for reasons described therein. */
3172 if (!new_dst && !x->copy_as_regular && !S_ISDIR (src_mode)
3173 && (x->set_security_context || x->preserve_security_context))
3175 if (! set_file_security_ctx (dst_name, false, x))
3177 if (x->require_preserve_context)
3178 goto un_backup;
3182 if (command_line_arg && x->dest_info)
3184 /* Now that the destination file is very likely to exist,
3185 add its info to the set. */
3186 struct stat sb;
3187 if (fstatat (dst_dirfd, drelname, &sb, AT_SYMLINK_NOFOLLOW) == 0)
3188 record_file (x->dest_info, dst_relname, &sb);
3191 /* If we've just created a hard-link due to cp's --link option,
3192 we're done. */
3193 if (x->hard_link && ! S_ISDIR (src_mode)
3194 && !(! CAN_HARDLINK_SYMLINKS && S_ISLNK (src_mode)
3195 && x->dereference == DEREF_NEVER))
3196 return delayed_ok;
3198 if (copied_as_regular)
3199 return delayed_ok;
3201 /* POSIX says that 'cp -p' must restore the following:
3202 - permission bits
3203 - setuid, setgid bits
3204 - owner and group
3205 If it fails to restore any of those, we may give a warning but
3206 the destination must not be removed.
3207 FIXME: implement the above. */
3209 /* Adjust the times (and if possible, ownership) for the copy.
3210 chown turns off set[ug]id bits for non-root,
3211 so do the chmod last. */
3213 if (x->preserve_timestamps)
3215 struct timespec timespec[2];
3216 timespec[0] = get_stat_atime (&src_sb);
3217 timespec[1] = get_stat_mtime (&src_sb);
3219 int utimensat_flags = dest_is_symlink ? AT_SYMLINK_NOFOLLOW : 0;
3220 if (utimensat (dst_dirfd, drelname, timespec, utimensat_flags) != 0)
3222 error (0, errno, _("preserving times for %s"), quoteaf (dst_name));
3223 if (x->require_preserve)
3224 return false;
3228 /* Avoid calling chown if we know it's not necessary. */
3229 if (!dest_is_symlink && x->preserve_ownership
3230 && (new_dst || !SAME_OWNER_AND_GROUP (src_sb, dst_sb)))
3232 switch (set_owner (x, dst_name, dst_dirfd, drelname, -1,
3233 &src_sb, new_dst, &dst_sb))
3235 case -1:
3236 return false;
3238 case 0:
3239 src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX);
3240 break;
3244 /* Set xattrs after ownership as changing owners will clear capabilities. */
3245 if (x->preserve_xattr && ! copy_attr (src_name, -1, dst_name, -1, x)
3246 && x->require_preserve_xattr)
3247 return false;
3249 /* The operations beyond this point may dereference a symlink. */
3250 if (dest_is_symlink)
3251 return delayed_ok;
3253 set_author (dst_name, -1, &src_sb);
3255 if (x->preserve_mode || x->move_mode)
3257 if (xcopy_acl (src_name, -1, dst_name, -1, src_mode) != 0
3258 && x->require_preserve)
3259 return false;
3261 else if (x->set_mode)
3263 if (xset_acl (dst_name, -1, x->mode) != 0)
3264 return false;
3266 else if (x->explicit_no_preserve_mode && new_dst)
3268 int default_permissions = S_ISDIR (src_mode) || S_ISSOCK (src_mode)
3269 ? S_IRWXUGO : MODE_RW_UGO;
3270 dst_mode = dst_sb.st_mode;
3271 if (S_ISDIR (src_mode)) /* Keep set-group-ID for directories. */
3272 default_permissions |= (dst_mode & S_ISGID);
3273 if (xset_acl (dst_name, -1, default_permissions & ~cached_umask ()) != 0)
3274 return false;
3276 else
3278 if (omitted_permissions)
3280 omitted_permissions &= ~ cached_umask ();
3282 if (omitted_permissions && !restore_dst_mode)
3284 /* Permissions were deliberately omitted when the file
3285 was created due to security concerns. See whether
3286 they need to be re-added now. It'd be faster to omit
3287 the lstat, but deducing the current destination mode
3288 is tricky in the presence of implementation-defined
3289 rules for special mode bits. */
3290 if (new_dst && (fstatat (dst_dirfd, drelname, &dst_sb,
3291 AT_SYMLINK_NOFOLLOW)
3292 != 0))
3294 error (0, errno, _("cannot stat %s"), quoteaf (dst_name));
3295 return false;
3297 dst_mode = dst_sb.st_mode;
3298 if (omitted_permissions & ~dst_mode)
3299 restore_dst_mode = true;
3303 if (restore_dst_mode)
3305 if (lchmodat (dst_dirfd, drelname, dst_mode | omitted_permissions)
3306 != 0)
3308 error (0, errno, _("preserving permissions for %s"),
3309 quoteaf (dst_name));
3310 if (x->require_preserve)
3311 return false;
3316 return delayed_ok;
3318 un_backup:
3320 if (x->preserve_security_context)
3321 restore_default_fscreatecon_or_die ();
3323 /* We have failed to create the destination file.
3324 If we've just added a dev/ino entry via the remember_copied
3325 call above (i.e., unless we've just failed to create a hard link),
3326 remove the entry associating the source dev/ino with the
3327 destination file name, so we don't try to 'preserve' a link
3328 to a file we didn't create. */
3329 if (earlier_file == nullptr)
3330 forget_created (src_sb.st_ino, src_sb.st_dev);
3332 if (dst_backup)
3334 char const *dst_relbackup = &dst_backup[dst_relname - dst_name];
3335 if (renameat (dst_dirfd, dst_relbackup, dst_dirfd, drelname) != 0)
3336 error (0, errno, _("cannot un-backup %s"), quoteaf (dst_name));
3337 else
3339 if (x->verbose)
3340 printf (_("%s -> %s (unbackup)\n"),
3341 quoteaf_n (0, dst_backup), quoteaf_n (1, dst_name));
3344 return false;
3347 static void
3348 valid_options (const struct cp_options *co)
3350 affirm (VALID_BACKUP_TYPE (co->backup_type));
3351 affirm (VALID_SPARSE_MODE (co->sparse_mode));
3352 affirm (VALID_REFLINK_MODE (co->reflink_mode));
3353 affirm (!(co->hard_link && co->symbolic_link));
3354 affirm (!
3355 (co->reflink_mode == REFLINK_ALWAYS
3356 && co->sparse_mode != SPARSE_AUTO));
3359 /* Copy the file SRC_NAME to the file DST_NAME aka DST_DIRFD+DST_RELNAME.
3360 If NONEXISTENT_DST is positive, DST_NAME does not exist even as a
3361 dangling symlink; if negative, it does not exist except possibly
3362 as a dangling symlink; if zero, its existence status is unknown.
3363 OPTIONS summarizes the command-line options.
3364 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
3365 same as) DST_NAME; otherwise, set clear it.
3366 If X->move_mode, set *RENAME_SUCCEEDED according to whether
3367 the source was simply renamed to the destination.
3368 Return true if successful. */
3370 extern bool
3371 copy (char const *src_name, char const *dst_name,
3372 int dst_dirfd, char const *dst_relname,
3373 int nonexistent_dst, const struct cp_options *options,
3374 bool *copy_into_self, bool *rename_succeeded)
3376 valid_options (options);
3378 /* Record the file names: they're used in case of error, when copying
3379 a directory into itself. I don't like to make these tools do *any*
3380 extra work in the common case when that work is solely to handle
3381 exceptional cases, but in this case, I don't see a way to derive the
3382 top level source and destination directory names where they're used.
3383 An alternative is to use COPY_INTO_SELF and print the diagnostic
3384 from every caller -- but I don't want to do that. */
3385 top_level_src_name = src_name;
3386 top_level_dst_name = dst_name;
3388 bool first_dir_created_per_command_line_arg = false;
3389 return copy_internal (src_name, dst_name, dst_dirfd, dst_relname,
3390 nonexistent_dst, nullptr, nullptr,
3391 options, true,
3392 &first_dir_created_per_command_line_arg,
3393 copy_into_self, rename_succeeded);
3396 /* Set *X to the default options for a value of type struct cp_options. */
3398 extern void
3399 cp_options_default (struct cp_options *x)
3401 memset (x, 0, sizeof *x);
3402 #ifdef PRIV_FILE_CHOWN
3404 priv_set_t *pset = priv_allocset ();
3405 if (!pset)
3406 xalloc_die ();
3407 if (getppriv (PRIV_EFFECTIVE, pset) == 0)
3409 x->chown_privileges = priv_ismember (pset, PRIV_FILE_CHOWN);
3410 x->owner_privileges = priv_ismember (pset, PRIV_FILE_OWNER);
3412 priv_freeset (pset);
3414 #else
3415 x->chown_privileges = x->owner_privileges = (geteuid () == ROOT_UID);
3416 #endif
3417 x->rename_errno = -1;
3420 /* Return true if it's OK for chown to fail, where errno is
3421 the error number that chown failed with and X is the copying
3422 option set. */
3424 extern bool
3425 chown_failure_ok (struct cp_options const *x)
3427 /* If non-root uses -p, it's ok if we can't preserve ownership.
3428 But root probably wants to know, e.g. if NFS disallows it,
3429 or if the target system doesn't support file ownership.
3431 Treat EACCES like EPERM and EINVAL to work around a bug in Linux
3432 CIFS <https://bugs.gnu.org/65599>. Although this means coreutils
3433 will ignore EACCES errors that it should report, problems should
3434 occur only when some other process is racing with coreutils and
3435 coreutils is not immune to races anyway. */
3437 return ((errno == EPERM || errno == EINVAL || errno == EACCES)
3438 && !x->chown_privileges);
3441 /* Similarly, return true if it's OK for chmod and similar operations
3442 to fail, where errno is the error number that chmod failed with and
3443 X is the copying option set. */
3445 static bool
3446 owner_failure_ok (struct cp_options const *x)
3448 return ((errno == EPERM || errno == EINVAL || errno == EACCES)
3449 && !x->owner_privileges);
3452 /* Return the user's umask, caching the result.
3454 FIXME: If the destination's parent directory has has a default ACL,
3455 some operating systems (e.g., GNU/Linux's "POSIX" ACLs) use that
3456 ACL's mask rather than the process umask. Currently, the callers
3457 of cached_umask incorrectly assume that this situation cannot occur. */
3458 extern mode_t
3459 cached_umask (void)
3461 static mode_t mask = (mode_t) -1;
3462 if (mask == (mode_t) -1)
3464 mask = umask (0);
3465 umask (mask);
3467 return mask;