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. */
21 #include <sys/ioctl.h>
22 #include <sys/types.h>
23 #include <selinux/selinux.h>
34 #include "alignalloc.h"
36 #include "backupfile.h"
37 #include "buffer-lcm.h"
38 #include "canonicalize.h"
45 #include "filenamecat.h"
46 #include "force-link.h"
47 #include "full-write.h"
49 #include "hash-triple.h"
50 #include "ignore-value.h"
51 #include "ioblksize.h"
53 #include "renameatu.h"
57 #include "stat-size.h"
58 #include "stat-time.h"
61 #include "write-any-file.h"
62 #include "areadlink.h"
67 # define USE_XATTR false
71 # include <attr/error_context.h>
72 # include <attr/libattr.h>
77 #if HAVE_LINUX_FALLOC_H
78 # include <linux/falloc.h>
81 /* See HAVE_FALLOCATE workaround when including this file. */
82 #ifdef HAVE_LINUX_FS_H
83 # include <linux/fs.h>
86 #if !defined FICLONE && defined __linux__
87 # define FICLONE _IOW (0x94, 9, int)
90 #if HAVE_FCLONEFILEAT && !USE_XATTR
91 # include <sys/clonefile.h>
98 #define SAME_OWNER(A, B) ((A).st_uid == (B).st_uid)
99 #define SAME_GROUP(A, B) ((A).st_gid == (B).st_gid)
100 #define SAME_OWNER_AND_GROUP(A, B) (SAME_OWNER (A, B) && SAME_GROUP (A, B))
102 /* LINK_FOLLOWS_SYMLINKS is tri-state; if it is -1, we don't know
103 how link() behaves, so assume we can't hardlink symlinks in that case. */
104 #if (defined HAVE_LINKAT && ! LINKAT_SYMLINK_NOTSUP) || ! LINK_FOLLOWS_SYMLINKS
105 # define CAN_HARDLINK_SYMLINKS 1
107 # define CAN_HARDLINK_SYMLINKS 0
112 struct dir_list
*parent
;
117 /* Initial size of the cp.dest_info hash table. */
118 #define DEST_INFO_INITIAL_CAPACITY 61
120 static bool copy_internal (char const *src_name
, char const *dst_name
,
121 int dst_dirfd
, char const *dst_relname
,
122 int nonexistent_dst
, struct stat
const *parent
,
123 struct dir_list
*ancestors
,
124 const struct cp_options
*x
,
125 bool command_line_arg
,
126 bool *first_dir_created_per_command_line_arg
,
127 bool *copy_into_self
,
128 bool *rename_succeeded
);
129 static bool owner_failure_ok (struct cp_options
const *x
);
131 /* Pointers to the file names: they're used in the diagnostic that is issued
132 when we detect the user is trying to copy a directory into itself. */
133 static char const *top_level_src_name
;
134 static char const *top_level_dst_name
;
142 COPY_DEBUG_EXTERNAL_INTERNAL
,
144 COPY_DEBUG_UNSUPPORTED
,
147 /* debug info about the last file copy. */
148 static struct copy_debug
150 enum copy_debug_val offload
;
151 enum copy_debug_val reflink
;
152 enum copy_debug_val sparse_detection
;
156 copy_debug_string (enum copy_debug_val debug_val
)
160 case COPY_DEBUG_NO
: return "no";
161 case COPY_DEBUG_YES
: return "yes";
162 case COPY_DEBUG_AVOIDED
: return "avoided";
163 case COPY_DEBUG_UNSUPPORTED
: return "unsupported";
164 default: return "unknown";
169 copy_debug_sparse_string (enum copy_debug_val debug_val
)
173 case COPY_DEBUG_NO
: return "no";
174 case COPY_DEBUG_YES
: return "zeros";
175 case COPY_DEBUG_EXTERNAL
: return "SEEK_HOLE";
176 case COPY_DEBUG_EXTERNAL_INTERNAL
: return "SEEK_HOLE + zeros";
177 default: return "unknown";
181 /* Print --debug output on standard output. */
183 emit_debug (const struct cp_options
*x
)
185 if (! x
->hard_link
&& ! x
->symbolic_link
&& x
->data_copy_required
)
186 printf ("copy offload: %s, reflink: %s, sparse detection: %s\n",
187 copy_debug_string (copy_debug
.offload
),
188 copy_debug_string (copy_debug
.reflink
),
189 copy_debug_sparse_string (copy_debug
.sparse_detection
));
192 #ifndef DEV_FD_MIGHT_BE_CHR
193 # define DEV_FD_MIGHT_BE_CHR false
196 /* Act like fstat (DIRFD, FILENAME, ST, FLAGS), except when following
197 symbolic links on Solaris-like systems, treat any character-special
198 device like /dev/fd/0 as if it were the file it is open on. */
200 follow_fstatat (int dirfd
, char const *filename
, struct stat
*st
, int flags
)
202 int result
= fstatat (dirfd
, filename
, st
, flags
);
204 if (DEV_FD_MIGHT_BE_CHR
&& result
== 0 && !(flags
& AT_SYMLINK_NOFOLLOW
)
205 && S_ISCHR (st
->st_mode
))
207 static dev_t stdin_rdev
;
208 static signed char stdin_rdev_status
;
209 if (stdin_rdev_status
== 0)
211 struct stat stdin_st
;
212 if (stat ("/dev/stdin", &stdin_st
) == 0 && S_ISCHR (stdin_st
.st_mode
)
213 && minor (stdin_st
.st_rdev
) == STDIN_FILENO
)
215 stdin_rdev
= stdin_st
.st_rdev
;
216 stdin_rdev_status
= 1;
219 stdin_rdev_status
= -1;
221 if (0 < stdin_rdev_status
&& major (stdin_rdev
) == major (st
->st_rdev
))
222 result
= fstat (minor (st
->st_rdev
), st
);
228 /* Attempt to punch a hole to avoid any permanent
229 speculative preallocation on file systems such as XFS.
230 Return values as per fallocate(2) except ENOSYS etc. are ignored. */
233 punch_hole (int fd
, off_t offset
, off_t length
)
236 /* +0 is to work around older <linux/fs.h> defining HAVE_FALLOCATE to empty. */
237 #if HAVE_FALLOCATE + 0
238 # if defined FALLOC_FL_PUNCH_HOLE && defined FALLOC_FL_KEEP_SIZE
239 ret
= fallocate (fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
241 if (ret
< 0 && (is_ENOTSUP (errno
) || errno
== ENOSYS
))
248 /* Create a hole at the end of a file,
249 avoiding preallocation if requested. */
252 create_hole (int fd
, char const *name
, bool punch_holes
, off_t size
)
254 off_t file_end
= lseek (fd
, size
, SEEK_CUR
);
258 error (0, errno
, _("cannot lseek %s"), quoteaf (name
));
262 /* Some file systems (like XFS) preallocate when write extending a file.
263 I.e., a previous write() may have preallocated extra space
264 that the seek above will not discard. A subsequent write() could
265 then make this allocation permanent. */
266 if (punch_holes
&& punch_hole (fd
, file_end
- size
, size
) < 0)
268 error (0, errno
, _("error deallocating %s"), quoteaf (name
));
276 /* Whether an errno value ERR, set by FICLONE or copy_file_range,
277 indicates that the copying operation has terminally failed, even
278 though it was invoked correctly (so that, e.g, EBADF cannot occur)
279 and even though !is_CLONENOTSUP (ERR). */
282 is_terminal_error (int err
)
284 return err
== EIO
|| err
== ENOMEM
|| err
== ENOSPC
|| err
== EDQUOT
;
287 /* Similarly, whether ERR indicates that the copying operation is not
288 supported or allowed for this file or process, even though the
289 operation was invoked correctly. */
292 is_CLONENOTSUP (int err
)
294 return err
== ENOSYS
|| err
== ENOTTY
|| is_ENOTSUP (err
)
295 || err
== EINVAL
|| err
== EBADF
296 || err
== EXDEV
|| err
== ETXTBSY
297 || err
== EPERM
|| err
== EACCES
;
301 /* Copy the regular file open on SRC_FD/SRC_NAME to DST_FD/DST_NAME,
302 honoring the MAKE_HOLES setting and using the BUF_SIZE-byte buffer
303 *ABUF for temporary storage, allocating it lazily if *ABUF is null.
304 Copy no more than MAX_N_READ bytes.
305 Return true upon successful completion;
306 print a diagnostic and return false upon error.
307 Note that for best results, BUF should be "well"-aligned.
308 Set *LAST_WRITE_MADE_HOLE to true if the final operation on
309 DEST_FD introduced a hole. Set *TOTAL_N_READ to the number of
312 sparse_copy (int src_fd
, int dest_fd
, char **abuf
, size_t buf_size
,
313 size_t hole_size
, bool punch_holes
, bool allow_reflink
,
314 char const *src_name
, char const *dst_name
,
315 uintmax_t max_n_read
, off_t
*total_n_read
,
316 bool *last_write_made_hole
)
318 *last_write_made_hole
= false;
321 if (copy_debug
.sparse_detection
== COPY_DEBUG_UNKNOWN
)
322 copy_debug
.sparse_detection
= hole_size
? COPY_DEBUG_YES
: COPY_DEBUG_NO
;
323 else if (hole_size
&& copy_debug
.sparse_detection
== COPY_DEBUG_EXTERNAL
)
324 copy_debug
.sparse_detection
= COPY_DEBUG_EXTERNAL_INTERNAL
;
326 /* If not looking for holes, use copy_file_range if functional,
327 but don't use if reflink disallowed as that may be implicit. */
328 if (!hole_size
&& allow_reflink
)
331 /* Copy at most COPY_MAX bytes at a time; this is min
332 (SSIZE_MAX, SIZE_MAX) truncated to a value that is
333 surely aligned well. */
334 ssize_t copy_max
= MIN (SSIZE_MAX
, SIZE_MAX
) >> 30 << 30;
335 ssize_t n_copied
= copy_file_range (src_fd
, nullptr, dest_fd
, nullptr,
336 MIN (max_n_read
, copy_max
), 0);
339 /* copy_file_range incorrectly returns 0 when reading from
340 the proc file system on the Linux kernel through at
341 least 5.6.19 (2020), so fall back on 'read' if the
342 input file seems empty. */
343 if (*total_n_read
== 0)
345 copy_debug
.offload
= COPY_DEBUG_YES
;
350 copy_debug
.offload
= COPY_DEBUG_UNSUPPORTED
;
352 /* Consider operation unsupported only if no data copied.
353 For example, EPERM could occur if copy_file_range not enabled
354 in seccomp filters, so retry with a standard copy. EPERM can
355 also occur for immutable files, but that would only be in the
356 edge case where the file is made immutable after creating,
357 in which case the (more accurate) error is still shown. */
358 if (*total_n_read
== 0 && is_CLONENOTSUP (errno
))
361 /* ENOENT was seen sometimes across CIFS shares, resulting in
362 no data being copied, but subsequent standard copies succeed. */
363 if (*total_n_read
== 0 && errno
== ENOENT
)
370 error (0, errno
, _("error copying %s to %s"),
371 quoteaf_n (0, src_name
), quoteaf_n (1, dst_name
));
375 copy_debug
.offload
= COPY_DEBUG_YES
;
376 max_n_read
-= n_copied
;
377 *total_n_read
+= n_copied
;
380 copy_debug
.offload
= COPY_DEBUG_AVOIDED
;
383 bool make_hole
= false;
389 *abuf
= xalignalloc (getpagesize (), buf_size
);
391 ssize_t n_read
= read (src_fd
, buf
, MIN (max_n_read
, buf_size
));
396 error (0, errno
, _("error reading %s"), quoteaf (src_name
));
401 max_n_read
-= n_read
;
402 *total_n_read
+= n_read
;
404 /* Loop over the input buffer in chunks of hole_size. */
405 size_t csize
= hole_size
? hole_size
: buf_size
;
411 bool prev_hole
= make_hole
;
412 csize
= MIN (csize
, n_read
);
414 if (hole_size
&& csize
)
415 make_hole
= is_nul (cbuf
, csize
);
417 bool transition
= (make_hole
!= prev_hole
) && psize
;
418 bool last_chunk
= (n_read
== csize
&& ! make_hole
) || ! csize
;
420 if (transition
|| last_chunk
)
427 if (full_write (dest_fd
, pbuf
, psize
) != psize
)
429 error (0, errno
, _("error writing %s"),
436 if (! create_hole (dest_fd
, dst_name
, punch_holes
, psize
))
446 n_read
= 0; /* Finished processing buffer. */
449 csize
= 0; /* Loop again to deal with last chunk. */
451 psize
= 0; /* Reset for next read loop. */
454 else /* Coalesce writes/seeks. */
456 if (ckd_add (&psize
, psize
, csize
))
458 error (0, 0, _("overflow reading %s"), quoteaf (src_name
));
467 *last_write_made_hole
= make_hole
;
469 /* It's tempting to break early here upon a short read from
470 a regular file. That would save the final read syscall
471 for each file. Unfortunately that doesn't work for
472 certain files in /proc or /sys with linux kernels. */
475 /* Ensure a trailing hole is created, so that subsequent
476 calls of sparse_copy() start at the correct offset. */
477 if (make_hole
&& ! create_hole (dest_fd
, dst_name
, punch_holes
, psize
))
483 /* Perform the O(1) btrfs clone operation, if possible.
484 Upon success, return 0. Otherwise, return -1 and set errno. */
486 clone_file (int dest_fd
, int src_fd
)
489 return ioctl (dest_fd
, FICLONE
, src_fd
);
498 /* Write N_BYTES zero bytes to file descriptor FD. Return true if successful.
499 Upon write failure, set errno and return false. */
501 write_zeros (int fd
, off_t n_bytes
)
504 static size_t nz
= IO_BUFSIZE
;
506 /* Attempt to use a relatively large calloc'd source buffer for
507 efficiency, but if that allocation fails, resort to a smaller
508 statically allocated one. */
509 if (zeros
== nullptr)
511 static char fallback
[1024];
512 zeros
= calloc (nz
, 1);
513 if (zeros
== nullptr)
516 nz
= sizeof fallback
;
522 size_t n
= MIN (nz
, n_bytes
);
523 if ((full_write (fd
, zeros
, n
)) != n
)
532 /* Perform an efficient extent copy, if possible. This avoids
533 the overhead of detecting holes in hole-introducing/preserving
534 copy, and thus makes copying sparse files much more efficient.
535 Copy from SRC_FD to DEST_FD, using *ABUF (of size BUF_SIZE) for a buffer.
536 Allocate *ABUF lazily if *ABUF is null.
537 Look for holes of size HOLE_SIZE in the input.
538 The input file is of size SRC_TOTAL_SIZE.
539 Use SPARSE_MODE to determine whether to create holes in the output.
540 SRC_NAME and DST_NAME are the input and output file names.
541 Return true if successful, false (with a diagnostic) otherwise. */
544 lseek_copy (int src_fd
, int dest_fd
, char **abuf
, size_t buf_size
,
545 size_t hole_size
, off_t ext_start
, off_t src_total_size
,
546 enum Sparse_type sparse_mode
,
548 char const *src_name
, char const *dst_name
)
550 off_t last_ext_start
= 0;
551 off_t last_ext_len
= 0;
553 bool wrote_hole_at_eof
= true;
555 copy_debug
.sparse_detection
= COPY_DEBUG_EXTERNAL
;
557 while (0 <= ext_start
)
559 off_t ext_end
= lseek (src_fd
, ext_start
, SEEK_HOLE
);
564 ext_end
= src_total_size
;
565 if (ext_end
<= ext_start
)
567 /* The input file grew; get its current size. */
568 src_total_size
= lseek (src_fd
, 0, SEEK_END
);
569 if (src_total_size
< 0)
572 /* If the input file shrank after growing, stop copying. */
573 if (src_total_size
<= ext_start
)
576 ext_end
= src_total_size
;
579 /* If the input file must have grown, increase its measured size. */
580 if (src_total_size
< ext_end
)
581 src_total_size
= ext_end
;
583 if (lseek (src_fd
, ext_start
, SEEK_SET
) < 0)
586 wrote_hole_at_eof
= false;
587 off_t ext_hole_size
= ext_start
- last_ext_start
- last_ext_len
;
591 if (sparse_mode
!= SPARSE_NEVER
)
593 if (! create_hole (dest_fd
, dst_name
,
594 sparse_mode
== SPARSE_ALWAYS
,
597 wrote_hole_at_eof
= true;
601 /* When not inducing holes and when there is a hole between
602 the end of the previous extent and the beginning of the
603 current one, write zeros to the destination file. */
604 if (! write_zeros (dest_fd
, ext_hole_size
))
606 error (0, errno
, _("%s: write failed"),
613 off_t ext_len
= ext_end
- ext_start
;
614 last_ext_start
= ext_start
;
615 last_ext_len
= ext_len
;
617 /* Copy this extent, looking for further opportunities to not
618 bother to write zeros if --sparse=always, since SEEK_HOLE
619 is conservative and may miss some holes. */
622 if ( ! sparse_copy (src_fd
, dest_fd
, abuf
, buf_size
,
623 sparse_mode
!= SPARSE_ALWAYS
? 0 : hole_size
,
624 true, allow_reflink
, src_name
, dst_name
,
625 ext_len
, &n_read
, &read_hole
))
628 dest_pos
= ext_start
+ n_read
;
630 wrote_hole_at_eof
= read_hole
;
631 if (n_read
< ext_len
)
633 /* The input file shrank. */
634 src_total_size
= dest_pos
;
638 ext_start
= lseek (src_fd
, dest_pos
, SEEK_DATA
);
639 if (ext_start
< 0 && errno
!= ENXIO
)
643 /* When the source file ends with a hole, we have to do a little more work,
644 since the above copied only up to and including the final extent.
645 In order to complete the copy, we may have to insert a hole or write
646 zeros in the destination corresponding to the source file's hole-at-EOF.
648 In addition, if the final extent was a block of zeros at EOF and we've
649 just converted them to a hole in the destination, we must call ftruncate
650 here in order to record the proper length in the destination. */
651 if ((dest_pos
< src_total_size
|| wrote_hole_at_eof
)
652 && ! (sparse_mode
== SPARSE_NEVER
653 ? write_zeros (dest_fd
, src_total_size
- dest_pos
)
654 : ftruncate (dest_fd
, src_total_size
) == 0))
656 error (0, errno
, _("failed to extend %s"), quoteaf (dst_name
));
660 if (sparse_mode
== SPARSE_ALWAYS
&& dest_pos
< src_total_size
661 && punch_hole (dest_fd
, dest_pos
, src_total_size
- dest_pos
) < 0)
663 error (0, errno
, _("error deallocating %s"), quoteaf (dst_name
));
670 error (0, errno
, _("cannot lseek %s"), quoteaf (src_name
));
675 /* FIXME: describe */
676 /* FIXME: rewrite this to use a hash table so we avoid the quadratic
677 performance hit that's probably noticeable only on trees deeper
678 than a few hundred levels. See use of active_dir_map in remove.c */
682 is_ancestor (const struct stat
*sb
, const struct dir_list
*ancestors
)
684 while (ancestors
!= 0)
686 if (ancestors
->ino
== sb
->st_ino
&& ancestors
->dev
== sb
->st_dev
)
688 ancestors
= ancestors
->parent
;
694 errno_unsupported (int err
)
696 return err
== ENOTSUP
|| err
== ENODATA
;
700 ATTRIBUTE_FORMAT ((printf
, 2, 3))
702 copy_attr_error (MAYBE_UNUSED
struct error_context
*ctx
,
703 char const *fmt
, ...)
705 if (!errno_unsupported (errno
))
710 /* use verror module to print error message */
712 verror (0, err
, fmt
, ap
);
717 ATTRIBUTE_FORMAT ((printf
, 2, 3))
719 copy_attr_allerror (MAYBE_UNUSED
struct error_context
*ctx
,
720 char const *fmt
, ...)
725 /* use verror module to print error message */
727 verror (0, err
, fmt
, ap
);
732 copy_attr_quote (MAYBE_UNUSED
struct error_context
*ctx
, char const *str
)
734 return quoteaf (str
);
738 copy_attr_free (MAYBE_UNUSED
struct error_context
*ctx
,
739 MAYBE_UNUSED
char const *str
)
743 /* Exclude SELinux extended attributes that are otherwise handled,
744 and are problematic to copy again. Also honor attributes
745 configured for exclusion in /etc/xattr.conf.
746 FIXME: Should we handle POSIX ACLs similarly?
747 Return zero to skip. */
749 check_selinux_attr (char const *name
, struct error_context
*ctx
)
751 return STRNCMP_LIT (name
, "security.selinux")
752 && attr_copy_check_permissions (name
, ctx
);
755 /* If positive SRC_FD and DST_FD descriptors are passed,
756 then copy by fd, otherwise copy by name. */
759 copy_attr (char const *src_path
, int src_fd
,
760 char const *dst_path
, int dst_fd
, struct cp_options
const *x
)
762 bool all_errors
= (!x
->data_copy_required
|| x
->require_preserve_xattr
);
763 bool some_errors
= (!all_errors
&& !x
->reduce_diagnostics
);
764 int (*check
) (char const *, struct error_context
*)
765 = (x
->preserve_security_context
|| x
->set_security_context
766 ? check_selinux_attr
: nullptr);
768 # if 4 < __GNUC__ + (8 <= __GNUC_MINOR__)
769 /* Pacify gcc -Wsuggest-attribute=format through at least GCC 13.2.1. */
770 # pragma GCC diagnostic push
771 # pragma GCC diagnostic ignored "-Wsuggest-attribute=format"
773 struct error_context
*ctx
774 = (all_errors
|| some_errors
775 ? (&(struct error_context
) {
776 .error
= all_errors
? copy_attr_allerror
: copy_attr_error
,
777 .quote
= copy_attr_quote
,
778 .quote_free
= copy_attr_free
781 # if 4 < __GNUC__ + (8 <= __GNUC_MINOR__)
782 # pragma GCC diagnostic pop
785 return ! (0 <= src_fd
&& 0 <= dst_fd
786 ? attr_copy_fd (src_path
, src_fd
, dst_path
, dst_fd
, check
, ctx
)
787 : attr_copy_file (src_path
, dst_path
, check
, ctx
));
789 #else /* USE_XATTR */
792 copy_attr (MAYBE_UNUSED
char const *src_path
,
793 MAYBE_UNUSED
int src_fd
,
794 MAYBE_UNUSED
char const *dst_path
,
795 MAYBE_UNUSED
int dst_fd
,
796 MAYBE_UNUSED
struct cp_options
const *x
)
800 #endif /* USE_XATTR */
802 /* Read the contents of the directory SRC_NAME_IN, and recursively
803 copy the contents to DST_NAME_IN aka DST_DIRFD+DST_RELNAME_IN.
804 NEW_DST is true if DST_NAME_IN is a directory
805 that was created previously in the recursion.
806 SRC_SB and ANCESTORS describe SRC_NAME_IN.
807 Set *COPY_INTO_SELF if SRC_NAME_IN is a parent of
808 (or the same as) DST_NAME_IN; otherwise, clear it.
809 Propagate *FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG from
810 caller to each invocation of copy_internal. Be careful to
811 pass the address of a temporary, and to update
812 *FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG only upon completion.
813 Return true if successful. */
816 copy_dir (char const *src_name_in
, char const *dst_name_in
,
817 int dst_dirfd
, char const *dst_relname_in
, bool new_dst
,
818 const struct stat
*src_sb
, struct dir_list
*ancestors
,
819 const struct cp_options
*x
,
820 bool *first_dir_created_per_command_line_arg
,
821 bool *copy_into_self
)
825 struct cp_options non_command_line_options
= *x
;
828 name_space
= savedir (src_name_in
, SAVEDIR_SORT_FASTREAD
);
829 if (name_space
== nullptr)
831 /* This diagnostic is a bit vague because savedir can fail in
832 several different ways. */
833 error (0, errno
, _("cannot access %s"), quoteaf (src_name_in
));
837 /* For cp's -H option, dereference command line arguments, but do not
838 dereference symlinks that are found via recursive traversal. */
839 if (x
->dereference
== DEREF_COMMAND_LINE_ARGUMENTS
)
840 non_command_line_options
.dereference
= DEREF_NEVER
;
842 bool new_first_dir_created
= false;
844 while (*namep
!= '\0')
846 bool local_copy_into_self
;
847 char *src_name
= file_name_concat (src_name_in
, namep
, nullptr);
848 char *dst_name
= file_name_concat (dst_name_in
, namep
, nullptr);
849 bool first_dir_created
= *first_dir_created_per_command_line_arg
;
850 bool rename_succeeded
;
852 ok
&= copy_internal (src_name
, dst_name
, dst_dirfd
,
853 dst_name
+ (dst_relname_in
- dst_name_in
),
855 ancestors
, &non_command_line_options
, false,
857 &local_copy_into_self
, &rename_succeeded
);
858 *copy_into_self
|= local_copy_into_self
;
863 /* If we're copying into self, there's no point in continuing,
864 and in fact, that would even infloop, now that we record only
865 the first created directory per command line argument. */
866 if (local_copy_into_self
)
869 new_first_dir_created
|= first_dir_created
;
870 namep
+= strlen (namep
) + 1;
873 *first_dir_created_per_command_line_arg
= new_first_dir_created
;
878 /* Change the file mode bits of the file identified by DESC or
879 DIRFD+NAME to MODE. Use DESC if DESC is valid and fchmod is
880 available, DIRFD+NAME otherwise. */
883 fchmod_or_lchmod (int desc
, int dirfd
, char const *name
, mode_t mode
)
887 return fchmod (desc
, mode
);
889 return lchmodat (dirfd
, name
, mode
);
892 /* Change the ownership of the file identified by DESC or
893 DIRFD+NAME to UID+GID. Use DESC if DESC is valid and fchown is
894 available, DIRFD+NAME otherwise. */
897 fchown_or_lchown (int desc
, int dirfd
, char const *name
, uid_t uid
, gid_t gid
)
901 return fchown (desc
, uid
, gid
);
903 return lchownat (dirfd
, name
, uid
, gid
);
906 /* Set the owner and owning group of DEST_DESC to the st_uid and
907 st_gid fields of SRC_SB. If DEST_DESC is undefined (-1), set
908 the owner and owning group of DST_NAME aka DST_DIRFD+DST_RELNAME
909 instead; for safety prefer lchownat since no
910 symbolic links should be involved. DEST_DESC must
911 refer to the same file as DST_NAME if defined.
912 Upon failure to set both UID and GID, try to set only the GID.
913 NEW_DST is true if the file was newly created; otherwise,
914 DST_SB is the status of the destination.
915 Return 1 if the initial syscall succeeds, 0 if it fails but it's OK
916 not to preserve ownership, -1 otherwise. */
919 set_owner (const struct cp_options
*x
, char const *dst_name
,
920 int dst_dirfd
, char const *dst_relname
, int dest_desc
,
921 struct stat
const *src_sb
, bool new_dst
,
922 struct stat
const *dst_sb
)
924 uid_t uid
= src_sb
->st_uid
;
925 gid_t gid
= src_sb
->st_gid
;
927 /* Naively changing the ownership of an already-existing file before
928 changing its permissions would create a window of vulnerability if
929 the file's old permissions are too generous for the new owner and
930 group. Avoid the window by first changing to a restrictive
931 temporary mode if necessary. */
933 if (!new_dst
&& (x
->preserve_mode
|| x
->move_mode
|| x
->set_mode
))
935 mode_t old_mode
= dst_sb
->st_mode
;
937 (x
->preserve_mode
|| x
->move_mode
? src_sb
->st_mode
: x
->mode
);
938 mode_t restrictive_temp_mode
= old_mode
& new_mode
& S_IRWXU
;
941 || (old_mode
& CHMOD_MODE_BITS
942 & (~new_mode
| S_ISUID
| S_ISGID
| S_ISVTX
)))
943 && qset_acl (dst_name
, dest_desc
, restrictive_temp_mode
) != 0)
945 if (! owner_failure_ok (x
))
946 error (0, errno
, _("clearing permissions for %s"),
948 return -x
->require_preserve
;
952 if (fchown_or_lchown (dest_desc
, dst_dirfd
, dst_relname
, uid
, gid
) == 0)
955 /* The ownership change failed. If the failure merely means we lack
956 privileges to change owner+group, try to change just the group
957 and ignore any failure of this. Otherwise, report an error. */
958 if (chown_failure_ok (x
))
959 ignore_value (fchown_or_lchown (dest_desc
, dst_dirfd
, dst_relname
,
963 error (0, errno
, _("failed to preserve ownership for %s"),
965 if (x
->require_preserve
)
972 /* Set the st_author field of DEST_DESC to the st_author field of
973 SRC_SB. If DEST_DESC is undefined (-1), set the st_author field
974 of DST_NAME instead. DEST_DESC must refer to the same file as
975 DST_NAME if defined. */
978 set_author (char const *dst_name
, int dest_desc
, const struct stat
*src_sb
)
980 #if HAVE_STRUCT_STAT_ST_AUTHOR
981 /* FIXME: Modify the following code so that it does not
982 follow symbolic links. */
984 /* Preserve the st_author field. */
985 file_t file
= (dest_desc
< 0
986 ? file_name_lookup (dst_name
, 0, 0)
987 : getdport (dest_desc
));
988 if (file
== MACH_PORT_NULL
)
989 error (0, errno
, _("failed to lookup file %s"), quoteaf (dst_name
));
992 error_t err
= file_chauthor (file
, src_sb
->st_author
);
994 error (0, err
, _("failed to preserve authorship for %s"),
996 mach_port_deallocate (mach_task_self (), file
);
1005 /* Set the default security context for the process. New files will
1006 have this security context set. Also existing files can have their
1007 context adjusted based on this process context, by
1008 set_file_security_ctx() called with PROCESS_LOCAL=true.
1009 This should be called before files are created so there is no race
1010 where a file may be present without an appropriate security context.
1011 Based on CP_OPTIONS, diagnose warnings and fail when appropriate.
1012 Return FALSE on failure, TRUE on success. */
1015 set_process_security_ctx (char const *src_name
, char const *dst_name
,
1016 mode_t mode
, bool new_dst
, const struct cp_options
*x
)
1018 if (x
->preserve_security_context
)
1020 /* Set the default context for the process to match the source. */
1021 bool all_errors
= !x
->data_copy_required
|| x
->require_preserve_context
;
1022 bool some_errors
= !all_errors
&& !x
->reduce_diagnostics
;
1025 if (0 <= lgetfilecon_raw (src_name
, &con_raw
))
1027 if (setfscreatecon_raw (con_raw
) < 0)
1029 if (all_errors
|| (some_errors
&& !errno_unsupported (errno
)))
1031 _("failed to set default file creation context to %s"),
1033 if (x
->require_preserve_context
)
1043 if (all_errors
|| (some_errors
&& !errno_unsupported (errno
)))
1046 _("failed to get security context of %s"),
1047 quoteaf (src_name
));
1049 if (x
->require_preserve_context
)
1053 else if (x
->set_security_context
)
1055 /* With -Z, adjust the default context for the process
1056 to have the type component adjusted as per the destination path. */
1057 if (new_dst
&& defaultcon (x
->set_security_context
, dst_name
, mode
) < 0
1058 && ! ignorable_ctx_err (errno
))
1061 _("failed to set default file creation context for %s"),
1062 quoteaf (dst_name
));
1069 /* Reset the security context of DST_NAME, to that already set
1070 as the process default if !X->set_security_context. Otherwise
1071 adjust the type component of DST_NAME's security context as
1072 per the system default for that path. Issue warnings upon
1073 failure, when allowed by various settings in X.
1074 Return false on failure, true on success. */
1077 set_file_security_ctx (char const *dst_name
,
1078 bool recurse
, const struct cp_options
*x
)
1080 bool all_errors
= (!x
->data_copy_required
1081 || x
->require_preserve_context
);
1082 bool some_errors
= !all_errors
&& !x
->reduce_diagnostics
;
1084 if (! restorecon (x
->set_security_context
, dst_name
, recurse
))
1086 if (all_errors
|| (some_errors
&& !errno_unsupported (errno
)))
1087 error (0, errno
, _("failed to set the security context of %s"),
1088 quoteaf_n (0, dst_name
));
1095 #ifndef HAVE_STRUCT_STAT_ST_BLOCKS
1096 # define HAVE_STRUCT_STAT_ST_BLOCKS 0
1099 /* Type of scan being done on the input when looking for sparseness. */
1102 /* An error was found when determining scantype. */
1105 /* No fancy scanning; just read and write. */
1108 /* Read and examine data looking for zero blocks; useful when
1109 attempting to create sparse output. */
1112 /* lseek information is available. */
1116 /* Result of infer_scantype. */
1117 union scan_inference
1119 /* Used if infer_scantype returns LSEEK_SCANTYPE. This is the
1120 offset of the first data block, or -1 if the file has no data. */
1124 /* Return how to scan a file with descriptor FD and stat buffer SB.
1125 *SCAN_INFERENCE is set to a valid value if returning LSEEK_SCANTYPE. */
1126 static enum scantype
1127 infer_scantype (int fd
, struct stat
const *sb
,
1128 union scan_inference
*scan_inference
)
1130 scan_inference
->ext_start
= -1; /* avoid -Wmaybe-uninitialized */
1132 /* Only attempt SEEK_HOLE if this heuristic
1133 suggests the file is sparse. */
1134 if (! (HAVE_STRUCT_STAT_ST_BLOCKS
1135 && S_ISREG (sb
->st_mode
)
1136 && STP_NBLOCKS (sb
) < sb
->st_size
/ ST_NBLOCKSIZE
))
1137 return PLAIN_SCANTYPE
;
1140 off_t ext_start
= lseek (fd
, 0, SEEK_DATA
);
1141 if (0 <= ext_start
|| errno
== ENXIO
)
1143 scan_inference
->ext_start
= ext_start
;
1144 return LSEEK_SCANTYPE
;
1146 else if (errno
!= EINVAL
&& !is_ENOTSUP (errno
))
1147 return ERROR_SCANTYPE
;
1150 return ZERO_SCANTYPE
;
1153 #if HAVE_FCLONEFILEAT && !USE_XATTR
1154 # include <sys/acl.h>
1155 /* Return true if FD has a nontrivial ACL. */
1159 /* Every platform with fclonefileat (macOS 10.12 or later) also has
1161 bool has_acl
= false;
1162 acl_t acl
= acl_get_fd_np (fd
, ACL_TYPE_EXTENDED
);
1166 has_acl
= 0 <= acl_get_entry (acl
, ACL_FIRST_ENTRY
, &ace
);
1173 /* Handle failure from FICLONE or fclonefileat.
1174 Return FALSE if it's a terminal failure for this file. */
1177 handle_clone_fail (int dst_dirfd
, char const *dst_relname
,
1178 char const *src_name
, char const *dst_name
,
1179 int dest_desc
, bool new_dst
, enum Reflink_type reflink_mode
)
1181 /* When the clone operation fails, report failure only with errno values
1182 known to mean trouble when the clone is supported and called properly.
1183 Do not report failure merely because !is_CLONENOTSUP (errno),
1184 as systems may yield oddball errno values here with FICLONE,
1185 and is_CLONENOTSUP is not appropriate for fclonefileat. */
1186 bool report_failure
= is_terminal_error (errno
);
1188 if (reflink_mode
== REFLINK_ALWAYS
|| report_failure
)
1189 error (0, errno
, _("failed to clone %s from %s"),
1190 quoteaf_n (0, dst_name
), quoteaf_n (1, src_name
));
1192 /* Remove the destination if cp --reflink=always created it
1193 but cloned no data. */
1194 if (new_dst
/* currently not for fclonefileat(). */
1195 && reflink_mode
== REFLINK_ALWAYS
1196 && ((! report_failure
) || lseek (dest_desc
, 0, SEEK_END
) == 0)
1197 && unlinkat (dst_dirfd
, dst_relname
, 0) != 0 && errno
!= ENOENT
)
1198 error (0, errno
, _("cannot remove %s"), quoteaf (dst_name
));
1200 if (! report_failure
)
1201 copy_debug
.reflink
= COPY_DEBUG_UNSUPPORTED
;
1203 if (reflink_mode
== REFLINK_ALWAYS
|| report_failure
)
1210 /* Copy a regular file from SRC_NAME to DST_NAME aka DST_DIRFD+DST_RELNAME.
1211 If the source file contains holes, copies holes and blocks of zeros
1212 in the source file as holes in the destination file.
1213 (Holes are read as zeroes by the 'read' system call.)
1214 When creating the destination, use DST_MODE & ~OMITTED_PERMISSIONS
1215 as the third argument in the call to open, adding
1216 OMITTED_PERMISSIONS after copying as needed.
1217 X provides many option settings.
1218 Return true if successful.
1219 *NEW_DST is initially as in copy_internal.
1220 If successful, set *NEW_DST to true if the destination file was created and
1221 to false otherwise; if unsuccessful, perhaps set *NEW_DST to some value.
1222 SRC_SB is the result of calling follow_fstatat on SRC_NAME;
1223 it might be updated by calling fstat again on the same file,
1224 to give it slightly more up-to-date contents. */
1227 copy_reg (char const *src_name
, char const *dst_name
,
1228 int dst_dirfd
, char const *dst_relname
,
1229 const struct cp_options
*x
,
1230 mode_t dst_mode
, mode_t omitted_permissions
, bool *new_dst
,
1231 struct stat
*src_sb
)
1233 char *buf
= nullptr;
1237 mode_t extra_permissions
;
1239 struct stat src_open_sb
;
1240 union scan_inference scan_inference
;
1241 bool return_val
= true;
1242 bool data_copy_required
= x
->data_copy_required
;
1243 bool preserve_xattr
= USE_XATTR
& x
->preserve_xattr
;
1245 copy_debug
.offload
= COPY_DEBUG_UNKNOWN
;
1246 copy_debug
.reflink
= x
->reflink_mode
? COPY_DEBUG_UNKNOWN
: COPY_DEBUG_NO
;
1247 copy_debug
.sparse_detection
= COPY_DEBUG_UNKNOWN
;
1249 source_desc
= open (src_name
,
1250 (O_RDONLY
| O_BINARY
1251 | (x
->dereference
== DEREF_NEVER
? O_NOFOLLOW
: 0)));
1252 if (source_desc
< 0)
1254 error (0, errno
, _("cannot open %s for reading"), quoteaf (src_name
));
1258 if (fstat (source_desc
, &src_open_sb
) != 0)
1260 error (0, errno
, _("cannot fstat %s"), quoteaf (src_name
));
1262 goto close_src_desc
;
1265 /* Compare the source dev/ino from the open file to the incoming,
1266 saved ones obtained via a previous call to stat. */
1267 if (! psame_inode (src_sb
, &src_open_sb
))
1270 _("skipping file %s, as it was replaced while being copied"),
1271 quoteaf (src_name
));
1273 goto close_src_desc
;
1276 /* Might as well tell the caller about the latest version of the
1277 source file status, since we have it already. */
1278 *src_sb
= src_open_sb
;
1279 mode_t src_mode
= src_sb
->st_mode
;
1281 /* The semantics of the following open calls are mandated
1282 by the specs for both cp and mv. */
1286 O_WRONLY
| O_BINARY
| (data_copy_required
? O_TRUNC
: 0);
1287 dest_desc
= openat (dst_dirfd
, dst_relname
, open_flags
);
1290 /* When using cp --preserve=context to copy to an existing destination,
1291 reset the context as per the default context, which has already been
1292 set according to the src.
1293 When using the mutually exclusive -Z option, then adjust the type of
1294 the existing context according to the system default for the dest.
1295 Note we set the context here, _after_ the file is opened, lest the
1296 new context disallow that. */
1298 && (x
->set_security_context
|| x
->preserve_security_context
))
1300 if (! set_file_security_ctx (dst_name
, false, x
))
1302 if (x
->require_preserve_context
)
1305 goto close_src_and_dst_desc
;
1310 if (dest_desc
< 0 && dest_errno
!= ENOENT
1311 && x
->unlink_dest_after_failed_open
)
1313 if (unlinkat (dst_dirfd
, dst_relname
, 0) == 0)
1316 printf (_("removed %s\n"), quoteaf (dst_name
));
1318 else if (errno
!= ENOENT
)
1320 error (0, errno
, _("cannot remove %s"), quoteaf (dst_name
));
1322 goto close_src_desc
;
1325 dest_errno
= ENOENT
;
1328 if (dest_desc
< 0 && dest_errno
== ENOENT
)
1330 /* Ensure there is no race where a file may be left without
1331 an appropriate security context. */
1332 if (x
->set_security_context
)
1334 if (! set_process_security_ctx (src_name
, dst_name
, dst_mode
,
1338 goto close_src_desc
;
1342 /* Tell caller that the destination file is created. */
1349 #if HAVE_FCLONEFILEAT && !USE_XATTR
1351 # define CLONE_ACL 0 /* Added in macOS 12.6. */
1353 # ifndef CLONE_NOOWNERCOPY
1354 # define CLONE_NOOWNERCOPY 0 /* Added in macOS 10.13. */
1356 /* Try fclonefileat if copying data in reflink mode.
1357 Use CLONE_NOFOLLOW to avoid security issues that could occur
1358 if writing through dangling symlinks. Although the circa
1359 2023 macOS documentation doesn't say so, CLONE_NOFOLLOW
1360 affects the destination file too. */
1361 if (data_copy_required
&& x
->reflink_mode
1362 && (CLONE_NOOWNERCOPY
|| x
->preserve_ownership
))
1364 /* Try fclonefileat so long as it won't create the
1365 destination with unwanted permissions, which could lead
1366 to a security race. */
1367 mode_t cloned_mode_bits
= S_ISVTX
| S_IRWXUGO
;
1368 mode_t cloned_mode
= src_mode
& cloned_mode_bits
;
1370 = (x
->preserve_mode
? src_mode
& CHMOD_MODE_BITS
1371 : x
->set_mode
? x
->mode
1372 : ((x
->explicit_no_preserve_mode
? MODE_RW_UGO
: dst_mode
)
1373 & ~ cached_umask ()));
1374 if (! (cloned_mode
& ~desired_mode
))
1378 | (x
->preserve_mode
? CLONE_ACL
: 0)
1379 | (x
->preserve_ownership
? 0 : CLONE_NOOWNERCOPY
));
1380 int s
= fclonefileat (source_desc
, dst_dirfd
, dst_relname
,
1382 if (s
!= 0 && (fc_flags
& CLONE_ACL
) && errno
== EINVAL
)
1384 fc_flags
&= ~CLONE_ACL
;
1385 s
= fclonefileat (source_desc
, dst_dirfd
, dst_relname
,
1390 copy_debug
.reflink
= COPY_DEBUG_YES
;
1392 /* Update the clone's timestamps and permissions
1395 if (!x
->preserve_timestamps
)
1397 struct timespec timespec
[2];
1398 timespec
[0].tv_nsec
= timespec
[1].tv_nsec
= UTIME_NOW
;
1399 if (utimensat (dst_dirfd
, dst_relname
, timespec
,
1400 AT_SYMLINK_NOFOLLOW
)
1403 error (0, errno
, _("updating times for %s"),
1404 quoteaf (dst_name
));
1406 goto close_src_desc
;
1410 extra_permissions
= desired_mode
& ~cloned_mode
;
1411 if (!extra_permissions
1412 && (!x
->preserve_mode
|| (fc_flags
& CLONE_ACL
)
1413 || !fd_has_acl (source_desc
)))
1415 goto close_src_desc
;
1418 /* Either some desired permissions were not cloned,
1419 or ACLs were not cloned despite that being requested. */
1420 omitted_permissions
= 0;
1424 if (! handle_clone_fail (dst_dirfd
, dst_relname
, src_name
,
1426 -1, false /* We didn't create dst */,
1430 goto close_src_desc
;
1434 copy_debug
.reflink
= COPY_DEBUG_AVOIDED
;
1436 else if (data_copy_required
&& x
->reflink_mode
)
1438 if (! CLONE_NOOWNERCOPY
)
1439 copy_debug
.reflink
= COPY_DEBUG_AVOIDED
;
1443 /* To allow copying xattrs on read-only files, create with u+w.
1444 This satisfies an inode permission check done by
1445 xattr_permission in fs/xattr.c of the GNU/Linux kernel. */
1447 ((dst_mode
& ~omitted_permissions
)
1448 | (preserve_xattr
&& !x
->owner_privileges
? S_IWUSR
: 0));
1449 extra_permissions
= open_mode
& ~dst_mode
; /* either 0 or S_IWUSR */
1451 int open_flags
= O_WRONLY
| O_CREAT
| O_BINARY
;
1452 dest_desc
= openat (dst_dirfd
, dst_relname
, open_flags
| O_EXCL
,
1456 /* When trying to copy through a dangling destination symlink,
1457 the above open fails with EEXIST. If that happens, and
1458 readlinkat shows that it is a symlink, then we
1459 have a problem: trying to resolve this dangling symlink to
1460 a directory/destination-entry pair is fundamentally racy,
1461 so punt. If x->open_dangling_dest_symlink is set (cp sets
1462 that when POSIXLY_CORRECT is set in the environment), simply
1463 call open again, but without O_EXCL (potentially dangerous).
1464 If not, fail with a diagnostic. These shenanigans are necessary
1465 only when copying, i.e., not in move_mode. */
1466 if (dest_desc
< 0 && dest_errno
== EEXIST
&& ! x
->move_mode
)
1469 if (0 <= readlinkat (dst_dirfd
, dst_relname
, dummy
, sizeof dummy
))
1471 if (x
->open_dangling_dest_symlink
)
1473 dest_desc
= openat (dst_dirfd
, dst_relname
,
1474 open_flags
, open_mode
);
1479 error (0, 0, _("not writing through dangling symlink %s"),
1480 quoteaf (dst_name
));
1482 goto close_src_desc
;
1487 /* Improve quality of diagnostic when a nonexistent dst_name
1488 ends in a slash and open fails with errno == EISDIR. */
1489 if (dest_desc
< 0 && dest_errno
== EISDIR
1490 && *dst_name
&& dst_name
[strlen (dst_name
) - 1] == '/')
1491 dest_errno
= ENOTDIR
;
1495 omitted_permissions
= extra_permissions
= 0;
1500 error (0, dest_errno
, _("cannot create regular file %s"),
1501 quoteaf (dst_name
));
1503 goto close_src_desc
;
1506 /* --attributes-only overrides --reflink. */
1507 if (data_copy_required
&& x
->reflink_mode
)
1509 if (clone_file (dest_desc
, source_desc
) == 0)
1511 data_copy_required
= false;
1512 copy_debug
.reflink
= COPY_DEBUG_YES
;
1516 if (! handle_clone_fail (dst_dirfd
, dst_relname
, src_name
, dst_name
,
1517 dest_desc
, *new_dst
, x
->reflink_mode
))
1520 goto close_src_and_dst_desc
;
1525 if (! (data_copy_required
| x
->preserve_ownership
| extra_permissions
))
1527 else if (fstat (dest_desc
, &sb
) != 0)
1529 error (0, errno
, _("cannot fstat %s"), quoteaf (dst_name
));
1531 goto close_src_and_dst_desc
;
1534 /* If extra permissions needed for copy_xattr didn't happen (e.g.,
1535 due to umask) chmod to add them temporarily; if that fails give
1536 up with extra permissions, letting copy_attr fail later. */
1537 mode_t temporary_mode
= sb
.st_mode
| extra_permissions
;
1538 if (temporary_mode
!= sb
.st_mode
1539 && (fchmod_or_lchmod (dest_desc
, dst_dirfd
, dst_relname
, temporary_mode
)
1541 extra_permissions
= 0;
1543 if (data_copy_required
)
1545 /* Choose a suitable buffer size; it may be adjusted later. */
1546 size_t buf_size
= io_blksize (&sb
);
1547 size_t hole_size
= STP_BLKSIZE (&sb
);
1549 /* Deal with sparse files. */
1550 enum scantype scantype
= infer_scantype (source_desc
, &src_open_sb
,
1552 if (scantype
== ERROR_SCANTYPE
)
1554 error (0, errno
, _("cannot lseek %s"), quoteaf (src_name
));
1556 goto close_src_and_dst_desc
;
1559 = (S_ISREG (sb
.st_mode
)
1560 && (x
->sparse_mode
== SPARSE_ALWAYS
1561 || (x
->sparse_mode
== SPARSE_AUTO
1562 && scantype
!= PLAIN_SCANTYPE
)));
1564 fdadvise (source_desc
, 0, 0, FADVISE_SEQUENTIAL
);
1566 /* If not making a sparse file, try to use a more-efficient
1570 /* Compute the least common multiple of the input and output
1571 buffer sizes, adjusting for outlandish values.
1572 Note we read in multiples of the reported block size
1573 to support (unusual) devices that have this constraint. */
1574 size_t blcm_max
= MIN (SIZE_MAX
, SSIZE_MAX
);
1575 size_t blcm
= buffer_lcm (io_blksize (&src_open_sb
), buf_size
,
1578 /* Do not bother with a buffer larger than the input file, plus one
1579 byte to make sure the file has not grown while reading it. */
1580 if (S_ISREG (src_open_sb
.st_mode
) && src_open_sb
.st_size
< buf_size
)
1581 buf_size
= src_open_sb
.st_size
+ 1;
1583 /* However, stick with a block size that is a positive multiple of
1584 blcm, overriding the above adjustments. Watch out for
1586 buf_size
+= blcm
- 1;
1587 buf_size
-= buf_size
% blcm
;
1588 if (buf_size
== 0 || blcm_max
< buf_size
)
1593 bool wrote_hole_at_eof
= false;
1596 scantype
== LSEEK_SCANTYPE
1597 ? lseek_copy (source_desc
, dest_desc
, &buf
, buf_size
, hole_size
,
1598 scan_inference
.ext_start
, src_open_sb
.st_size
,
1599 make_holes
? x
->sparse_mode
: SPARSE_NEVER
,
1600 x
->reflink_mode
!= REFLINK_NEVER
,
1604 sparse_copy (source_desc
, dest_desc
, &buf
, buf_size
,
1605 make_holes
? hole_size
: 0,
1606 x
->sparse_mode
== SPARSE_ALWAYS
,
1607 x
->reflink_mode
!= REFLINK_NEVER
,
1608 src_name
, dst_name
, UINTMAX_MAX
, &n_read
,
1609 &wrote_hole_at_eof
)))
1612 goto close_src_and_dst_desc
;
1614 else if (wrote_hole_at_eof
&& ftruncate (dest_desc
, n_read
) < 0)
1616 error (0, errno
, _("failed to extend %s"), quoteaf (dst_name
));
1618 goto close_src_and_dst_desc
;
1622 if (x
->preserve_timestamps
)
1624 struct timespec timespec
[2];
1625 timespec
[0] = get_stat_atime (src_sb
);
1626 timespec
[1] = get_stat_mtime (src_sb
);
1628 if (fdutimensat (dest_desc
, dst_dirfd
, dst_relname
, timespec
, 0) != 0)
1630 error (0, errno
, _("preserving times for %s"), quoteaf (dst_name
));
1631 if (x
->require_preserve
)
1634 goto close_src_and_dst_desc
;
1639 /* Set ownership before xattrs as changing owners will
1640 clear capabilities. */
1641 if (x
->preserve_ownership
&& ! SAME_OWNER_AND_GROUP (*src_sb
, sb
))
1643 switch (set_owner (x
, dst_name
, dst_dirfd
, dst_relname
, dest_desc
,
1644 src_sb
, *new_dst
, &sb
))
1648 goto close_src_and_dst_desc
;
1651 src_mode
&= ~ (S_ISUID
| S_ISGID
| S_ISVTX
);
1658 if (!copy_attr (src_name
, source_desc
, dst_name
, dest_desc
, x
)
1659 && x
->require_preserve_xattr
)
1663 set_author (dst_name
, dest_desc
, src_sb
);
1665 #if HAVE_FCLONEFILEAT && !USE_XATTR
1668 if (x
->preserve_mode
|| x
->move_mode
)
1670 if (copy_acl (src_name
, source_desc
, dst_name
, dest_desc
, src_mode
) != 0
1671 && x
->require_preserve
)
1674 else if (x
->set_mode
)
1676 if (set_acl (dst_name
, dest_desc
, x
->mode
) != 0)
1679 else if (x
->explicit_no_preserve_mode
&& *new_dst
)
1681 if (set_acl (dst_name
, dest_desc
, MODE_RW_UGO
& ~cached_umask ()) != 0)
1684 else if (omitted_permissions
| extra_permissions
)
1686 omitted_permissions
&= ~ cached_umask ();
1687 if ((omitted_permissions
| extra_permissions
)
1688 && (fchmod_or_lchmod (dest_desc
, dst_dirfd
, dst_relname
,
1689 dst_mode
& ~ cached_umask ())
1692 error (0, errno
, _("preserving permissions for %s"),
1693 quoteaf (dst_name
));
1694 if (x
->require_preserve
)
1700 goto close_src_desc
;
1702 close_src_and_dst_desc
:
1703 if (close (dest_desc
) < 0)
1705 error (0, errno
, _("failed to close %s"), quoteaf (dst_name
));
1709 if (close (source_desc
) < 0)
1711 error (0, errno
, _("failed to close %s"), quoteaf (src_name
));
1715 /* Output debug info for data copying operations. */
1723 /* Return whether it's OK that two files are the "same" by some measure.
1724 The first file is SRC_NAME and has status SRC_SB.
1725 The second is DST_DIRFD+DST_RELNAME and has status DST_SB.
1726 The copying options are X. The goal is to avoid
1727 making the 'copy' operation remove both copies of the file
1728 in that case, while still allowing the user to e.g., move or
1729 copy a regular file onto a symlink that points to it.
1730 Try to minimize the cost of this function in the common case.
1731 Set *RETURN_NOW if we've determined that the caller has no more
1732 work to do and should return successfully, right away. */
1735 same_file_ok (char const *src_name
, struct stat
const *src_sb
,
1736 int dst_dirfd
, char const *dst_relname
, struct stat
const *dst_sb
,
1737 const struct cp_options
*x
, bool *return_now
)
1739 const struct stat
*src_sb_link
;
1740 const struct stat
*dst_sb_link
;
1741 struct stat tmp_dst_sb
;
1742 struct stat tmp_src_sb
;
1745 bool same
= psame_inode (src_sb
, dst_sb
);
1747 *return_now
= false;
1749 /* FIXME: this should (at the very least) be moved into the following
1750 if-block. More likely, it should be removed, because it inhibits
1751 making backups. But removing it will result in a change in behavior
1752 that will probably have to be documented -- and tests will have to
1754 if (same
&& x
->hard_link
)
1760 if (x
->dereference
== DEREF_NEVER
)
1764 /* If both the source and destination files are symlinks (and we'll
1765 know this here IFF preserving symlinks), then it's usually ok
1766 when they are distinct. */
1767 if (S_ISLNK (src_sb
->st_mode
) && S_ISLNK (dst_sb
->st_mode
))
1769 bool sn
= same_nameat (AT_FDCWD
, src_name
, dst_dirfd
, dst_relname
);
1772 /* It's fine when we're making any type of backup. */
1773 if (x
->backup_type
!= no_backups
)
1776 /* Here we have two symlinks that are hard-linked together,
1777 and we're not making backups. In this unusual case, simply
1778 returning true would lead to mv calling "rename(A,B)",
1779 which would do nothing and return 0. */
1783 return ! x
->move_mode
;
1790 src_sb_link
= src_sb
;
1791 dst_sb_link
= dst_sb
;
1798 if (fstatat (dst_dirfd
, dst_relname
, &tmp_dst_sb
,
1799 AT_SYMLINK_NOFOLLOW
) != 0
1800 || lstat (src_name
, &tmp_src_sb
) != 0)
1803 src_sb_link
= &tmp_src_sb
;
1804 dst_sb_link
= &tmp_dst_sb
;
1806 same_link
= psame_inode (src_sb_link
, dst_sb_link
);
1808 /* If both are symlinks, then it's ok, but only if the destination
1809 will be unlinked before being opened. This is like the test
1810 above, but with the addition of the unlink_dest_before_opening
1811 conjunct because otherwise, with two symlinks to the same target,
1812 we'd end up truncating the source file. */
1813 if (S_ISLNK (src_sb_link
->st_mode
) && S_ISLNK (dst_sb_link
->st_mode
)
1814 && x
->unlink_dest_before_opening
)
1818 /* The backup code ensures there's a copy, so it's usually ok to
1819 remove any destination file. One exception is when both
1820 source and destination are the same directory entry. In that
1821 case, moving the destination file aside (in making the backup)
1822 would also rename the source file and result in an error. */
1823 if (x
->backup_type
!= no_backups
)
1827 /* In copy mode when dereferencing symlinks, if the source is a
1828 symlink and the dest is not, then backing up the destination
1829 (moving it aside) would make it a dangling symlink, and the
1830 subsequent attempt to open it in copy_reg would fail with
1831 a misleading diagnostic. Avoid that by returning zero in
1832 that case so the caller can make cp (or mv when it has to
1833 resort to reading the source file) fail now. */
1835 /* FIXME-note: even with the following kludge, we can still provoke
1836 the offending diagnostic. It's just a little harder to do :-)
1837 $ rm -f a b c; touch c; ln -s c b; ln -s b a; cp -b a b
1838 cp: cannot open 'a' for reading: No such file or directory
1839 That's misleading, since a subsequent 'ls' shows that 'a'
1841 One solution would be to open the source file *before* moving
1842 aside the destination, but that'd involve a big rewrite. */
1844 && x
->dereference
!= DEREF_NEVER
1845 && S_ISLNK (src_sb_link
->st_mode
)
1846 && ! S_ISLNK (dst_sb_link
->st_mode
))
1852 /* FIXME: What about case insensitive file systems ? */
1853 return ! same_nameat (AT_FDCWD
, src_name
, dst_dirfd
, dst_relname
);
1857 /* FIXME: use or remove */
1859 /* If we're making a backup, we'll detect the problem case in
1860 copy_reg because SRC_NAME will no longer exist. Allowing
1861 the test to be deferred lets cp do some useful things.
1862 But when creating hardlinks and SRC_NAME is a symlink
1863 but DST_RELNAME is not we must test anyway. */
1865 || !S_ISLNK (src_sb_link
->st_mode
)
1866 || S_ISLNK (dst_sb_link
->st_mode
))
1869 if (x
->dereference
!= DEREF_NEVER
)
1873 if (x
->move_mode
|| x
->unlink_dest_before_opening
)
1875 /* They may refer to the same file if we're in move mode and the
1876 target is a symlink. That is ok, since we remove any existing
1877 destination file before opening it -- via 'rename' if they're on
1878 the same file system, via unlinkat otherwise. */
1879 if (S_ISLNK (dst_sb_link
->st_mode
))
1882 /* It's not ok if they're distinct hard links to the same file as
1883 this causes a race condition and we may lose data in this case. */
1885 && 1 < dst_sb_link
->st_nlink
1886 && ! same_nameat (AT_FDCWD
, src_name
, dst_dirfd
, dst_relname
))
1887 return ! x
->move_mode
;
1890 /* If neither is a symlink, then it's ok as long as they aren't
1891 hard links to the same file. */
1892 if (!S_ISLNK (src_sb_link
->st_mode
) && !S_ISLNK (dst_sb_link
->st_mode
))
1894 if (!psame_inode (src_sb_link
, dst_sb_link
))
1897 /* If they are the same file, it's ok if we're making hard links. */
1905 /* At this point, it is normally an error (data loss) to move a symlink
1906 onto its referent, but in at least one narrow case, it is not:
1908 1) src is a symlink,
1909 2) dest has a link count of 2 or more and
1910 3) dest and the referent of src are not the same directory entry,
1911 then it's ok, since while we'll lose one of those hard links,
1912 src will still point to a remaining link.
1913 Note that technically, condition #3 obviates condition #2, but we
1914 retain the 1 < st_nlink condition because that means fewer invocations
1915 of the more expensive #3.
1918 $ touch f && ln f l && ln -s f s
1920 -rw-------. 2 0 Jan 4 22:46 f
1921 -rw-------. 2 0 Jan 4 22:46 l
1922 lrwxrwxrwx. 1 1 Jan 4 22:46 s -> f
1923 this must fail: mv s f
1924 this must succeed: mv s l */
1926 && S_ISLNK (src_sb
->st_mode
)
1927 && 1 < dst_sb_link
->st_nlink
)
1929 char *abs_src
= canonicalize_file_name (src_name
);
1932 bool result
= ! same_nameat (AT_FDCWD
, abs_src
,
1933 dst_dirfd
, dst_relname
);
1939 /* It's ok to recreate a destination symlink. */
1940 if (x
->symbolic_link
&& S_ISLNK (dst_sb_link
->st_mode
))
1943 if (x
->dereference
== DEREF_NEVER
)
1945 if ( ! S_ISLNK (src_sb_link
->st_mode
))
1946 tmp_src_sb
= *src_sb_link
;
1947 else if (stat (src_name
, &tmp_src_sb
) != 0)
1950 if ( ! S_ISLNK (dst_sb_link
->st_mode
))
1951 tmp_dst_sb
= *dst_sb_link
;
1952 else if (fstatat (dst_dirfd
, dst_relname
, &tmp_dst_sb
, 0) != 0)
1955 if (!psame_inode (&tmp_src_sb
, &tmp_dst_sb
))
1960 /* It's ok to attempt to hardlink the same file,
1961 and return early if not replacing a symlink.
1962 Note we need to return early to avoid a later
1963 unlink() of DST (when SRC is a symlink). */
1964 *return_now
= ! S_ISLNK (dst_sb_link
->st_mode
);
1972 /* Return whether DST_DIRFD+DST_RELNAME, with mode MODE,
1973 is writable in the sense of 'mv'.
1974 Always consider a symbolic link to be writable. */
1976 writable_destination (int dst_dirfd
, char const *dst_relname
, mode_t mode
)
1978 return (S_ISLNK (mode
)
1979 || can_write_any_file ()
1980 || faccessat (dst_dirfd
, dst_relname
, W_OK
, AT_EACCESS
) == 0);
1984 overwrite_ok (struct cp_options
const *x
, char const *dst_name
,
1985 int dst_dirfd
, char const *dst_relname
,
1986 struct stat
const *dst_sb
)
1988 if (! writable_destination (dst_dirfd
, dst_relname
, dst_sb
->st_mode
))
1990 char perms
[12]; /* "-rwxrwxrwx " ls-style modes. */
1991 strmode (dst_sb
->st_mode
, perms
);
1994 (x
->move_mode
|| x
->unlink_dest_before_opening
1995 || x
->unlink_dest_after_failed_open
)
1996 ? _("%s: replace %s, overriding mode %04lo (%s)? ")
1997 : _("%s: unwritable %s (mode %04lo, %s); try anyway? "),
1998 program_name
, quoteaf (dst_name
),
1999 (unsigned long int) (dst_sb
->st_mode
& CHMOD_MODE_BITS
),
2004 fprintf (stderr
, _("%s: overwrite %s? "),
2005 program_name
, quoteaf (dst_name
));
2011 /* Initialize the hash table implementing a set of F_triple entries
2012 corresponding to destination files. */
2014 dest_info_init (struct cp_options
*x
)
2017 = hash_initialize (DEST_INFO_INITIAL_CAPACITY
,
2026 /* Initialize the hash table implementing a set of F_triple entries
2027 corresponding to source files listed on the command line. */
2029 src_info_init (struct cp_options
*x
)
2032 /* Note that we use triple_hash_no_name here.
2033 Contrast with the use of triple_hash above.
2034 That is necessary because a source file may be specified
2035 in many different ways. We want to warn about this
2041 = hash_initialize (DEST_INFO_INITIAL_CAPACITY
,
2043 triple_hash_no_name
,
2050 /* When effecting a move (e.g., for mv(1)), and given the name DST_NAME
2051 aka DST_DIRFD+DST_RELNAME
2052 of the destination and a corresponding stat buffer, DST_SB, return
2053 true if the logical 'move' operation should _not_ proceed.
2054 Otherwise, return false.
2055 Depending on options specified in X, this code may issue an
2056 interactive prompt asking whether it's ok to overwrite DST_NAME. */
2058 abandon_move (const struct cp_options
*x
,
2059 char const *dst_name
,
2060 int dst_dirfd
, char const *dst_relname
,
2061 struct stat
const *dst_sb
)
2063 affirm (x
->move_mode
);
2064 return (x
->interactive
== I_ALWAYS_NO
2065 || x
->interactive
== I_ALWAYS_SKIP
2066 || ((x
->interactive
== I_ASK_USER
2067 || (x
->interactive
== I_UNSPECIFIED
2069 && ! writable_destination (dst_dirfd
, dst_relname
,
2071 && ! overwrite_ok (x
, dst_name
, dst_dirfd
, dst_relname
, dst_sb
)));
2074 /* Print --verbose output on standard output, e.g. 'new' -> 'old'.
2075 If BACKUP_DST_NAME is non-null, then also indicate that it is
2076 the name of a backup file. */
2078 emit_verbose (char const *src
, char const *dst
, char const *backup_dst_name
)
2080 printf ("%s -> %s", quoteaf_n (0, src
), quoteaf_n (1, dst
));
2081 if (backup_dst_name
)
2082 printf (_(" (backup: %s)"), quoteaf (backup_dst_name
));
2086 /* A wrapper around "setfscreatecon (nullptr)" that exits upon failure. */
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. */
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. */
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,
2128 char *a_src_name
= nullptr;
2130 src_name
= a_src_name
= subst_suffix (dst_name
, dst_relname
,
2132 error (0, err
, _("cannot create hard link %s to %s"),
2133 quoteaf_n (0, dst_name
), quoteaf_n (1, src_name
));
2137 if (err
< 0 && verbose
)
2138 printf (_("removed %s\n"), quoteaf (dst_name
));
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. */
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. */
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
)))
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);
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. */
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
)
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
: ".";
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
;
2224 if (rename_errno
< 0)
2225 rename_errno
= (renameatu (AT_FDCWD
, src_name
, dst_dirfd
, drelname
,
2227 ? RENAME_EXCHANGE
: RENAME_NOREPLACE
))
2229 *rename_succeeded
= rename_errno
== 0;
2230 nonexistent_dst
= *rename_succeeded
&& !x
->exchange
;
2233 if (rename_errno
== 0
2235 : rename_errno
!= EEXIST
2236 || (x
->interactive
!= I_ALWAYS_NO
&& x
->interactive
!= I_ALWAYS_SKIP
))
2238 char const *name
= rename_errno
== 0 ? dst_name
: src_name
;
2239 int dirfd
= rename_errno
== 0 ? dst_dirfd
: AT_FDCWD
;
2240 char const *relname
= rename_errno
== 0 ? drelname
: src_name
;
2242 = x
->dereference
== DEREF_NEVER
? AT_SYMLINK_NOFOLLOW
: 0;
2243 if (follow_fstatat (dirfd
, relname
, &src_sb
, fstatat_flags
) != 0)
2245 error (0, errno
, _("cannot stat %s"), quoteaf (name
));
2249 src_mode
= src_sb
.st_mode
;
2251 if (S_ISDIR (src_mode
) && !x
->recursive
&& !x
->exchange
)
2253 error (0, 0, ! x
->install_mode
/* cp */
2254 ? _("-r not specified; omitting directory %s")
2255 : _("omitting directory %s"),
2256 quoteaf (src_name
));
2262 #if defined lint && (defined __clang__ || defined __COVERITY__)
2263 affirm (x
->move_mode
);
2264 memset (&src_sb
, 0, sizeof src_sb
);
2268 /* Detect the case in which the same source file appears more than
2269 once on the command line and no backup option has been selected.
2270 If so, simply warn and don't copy it the second time.
2271 This check is enabled only if x->src_info is non-null. */
2272 if (command_line_arg
&& x
->src_info
)
2274 if ( ! S_ISDIR (src_mode
)
2275 && x
->backup_type
== no_backups
2276 && seen_file (x
->src_info
, src_name
, &src_sb
))
2278 error (0, 0, _("warning: source file %s specified more than once"),
2279 quoteaf (src_name
));
2283 record_file (x
->src_info
, src_name
, &src_sb
);
2286 bool dereference
= should_dereference (x
, command_line_arg
);
2288 /* Whether the destination is (or was) known to be new, updated as
2289 more info comes in. This may become true if the destination is a
2290 dangling symlink, in contexts where dangling symlinks should be
2291 treated the same as nonexistent files. */
2292 bool new_dst
= 0 < nonexistent_dst
;
2294 if (! new_dst
&& ! x
->exchange
)
2296 /* Normally, fill in DST_SB or set NEW_DST so that later code
2297 can use DST_SB if NEW_DST is false. However, don't bother
2298 doing this when rename_errno == EEXIST and X->interactive is
2299 I_ALWAYS_NO or I_ALWAYS_SKIP, something that can happen only
2300 with mv in which case x->update must be false which means
2301 that even if !NEW_DST the move will be abandoned without
2302 looking at DST_SB. */
2303 if (! (rename_errno
== EEXIST
2304 && (x
->interactive
== I_ALWAYS_NO
2305 || x
->interactive
== I_ALWAYS_SKIP
)))
2307 /* Regular files can be created by writing through symbolic
2308 links, but other files cannot. So use stat on the
2309 destination when copying a regular file, and lstat otherwise.
2310 However, if we intend to unlink or remove the destination
2311 first, use lstat, since a copy won't actually be made to the
2312 destination in that case. */
2314 = ((! S_ISREG (src_mode
)
2315 && (! x
->copy_as_regular
2316 || (S_ISDIR (src_mode
) && !x
->keep_directory_symlink
)
2317 || S_ISLNK (src_mode
)))
2318 || x
->move_mode
|| x
->symbolic_link
|| x
->hard_link
2319 || x
->backup_type
!= no_backups
2320 || x
->unlink_dest_before_opening
);
2321 if (!use_lstat
&& nonexistent_dst
< 0)
2323 else if (0 <= follow_fstatat (dst_dirfd
, drelname
, &dst_sb
,
2324 use_lstat
? AT_SYMLINK_NOFOLLOW
: 0))
2326 have_dst_lstat
= use_lstat
;
2327 rename_errno
= EEXIST
;
2329 else if (errno
== ENOENT
)
2331 else if (errno
== ELOOP
&& !use_lstat
2332 && x
->unlink_dest_after_failed_open
)
2334 /* cp -f's destination might be a symlink loop.
2335 Leave new_dst=false so that we try to unlink later. */
2339 error (0, errno
, _("cannot stat %s"), quoteaf (dst_name
));
2344 if (rename_errno
== EEXIST
)
2346 bool return_now
= false;
2347 bool return_val
= true;
2348 bool skipped
= false;
2350 if ((x
->interactive
!= I_ALWAYS_NO
&& x
->interactive
!= I_ALWAYS_SKIP
)
2351 && ! same_file_ok (src_name
, &src_sb
, dst_dirfd
, drelname
,
2352 &dst_sb
, x
, &return_now
))
2354 error (0, 0, _("%s and %s are the same file"),
2355 quoteaf_n (0, src_name
), quoteaf_n (1, dst_name
));
2359 if (x
->update
&& !S_ISDIR (src_mode
))
2361 /* When preserving timestamps (but not moving within a file
2362 system), don't worry if the destination timestamp is
2363 less than the source merely because of timestamp
2365 int options
= ((x
->preserve_timestamps
2367 && dst_sb
.st_dev
== src_sb
.st_dev
))
2368 ? UTIMECMP_TRUNCATE_SOURCE
2371 if (0 <= utimecmpat (dst_dirfd
, dst_relname
, &dst_sb
,
2374 /* We're using --update and the destination is not older
2375 than the source, so do not copy or move. Pretend the
2376 rename succeeded, so the caller (if it's mv) doesn't
2377 end up removing the source file. */
2378 if (rename_succeeded
)
2379 *rename_succeeded
= true;
2381 /* However, we still must record that we've processed
2382 this src/dest pair, in case this source file is
2383 hard-linked to another one. In that case, we'll use
2384 the mapping information to link the corresponding
2385 destination names. */
2386 earlier_file
= remember_copied (dst_relname
, src_sb
.st_ino
,
2390 /* Note we currently replace DST_NAME unconditionally,
2391 even if it was a newer separate file. */
2392 if (! create_hard_link (nullptr, dst_dirfd
, earlier_file
,
2393 dst_name
, dst_dirfd
, dst_relname
,
2395 x
->verbose
, dereference
))
2406 /* When there is an existing destination file, we may end up
2407 returning early, and hence not copying/moving the file.
2408 This may be due to an interactive 'negative' reply to the
2409 prompt about the existing file. It may also be due to the
2410 use of the --no-clobber option.
2412 cp and mv treat -i and -f differently. */
2415 if (abandon_move (x
, dst_name
, dst_dirfd
, drelname
, &dst_sb
))
2417 /* Pretend the rename succeeded, so the caller (mv)
2418 doesn't end up removing the source file. */
2419 if (rename_succeeded
)
2420 *rename_succeeded
= true;
2423 return_val
= x
->interactive
== I_ALWAYS_SKIP
;
2428 if (! S_ISDIR (src_mode
)
2429 && (x
->interactive
== I_ALWAYS_NO
2430 || x
->interactive
== I_ALWAYS_SKIP
2431 || (x
->interactive
== I_ASK_USER
2432 && ! overwrite_ok (x
, dst_name
, dst_dirfd
,
2433 dst_relname
, &dst_sb
))))
2436 return_val
= x
->interactive
== I_ALWAYS_SKIP
;
2443 if (x
->interactive
== I_ALWAYS_NO
)
2444 error (0, 0, _("not replacing %s"), quoteaf (dst_name
));
2446 printf (_("skipped %s\n"), quoteaf (dst_name
));
2454 /* Copying a directory onto a non-directory, or vice versa,
2455 is ok only with --backup. */
2456 if (!S_ISDIR (src_mode
) != !S_ISDIR (dst_sb
.st_mode
)
2457 && x
->backup_type
== no_backups
)
2460 _(S_ISDIR (src_mode
)
2461 ? ("cannot overwrite non-directory %s "
2462 "with directory %s")
2463 : ("cannot overwrite directory %s "
2464 "with non-directory %s")),
2465 quoteaf_n (0, dst_name
), quoteaf_n (1, src_name
));
2469 /* Don't let the user destroy their data, even if they try hard:
2470 This mv command must fail (likewise for cp):
2471 rm -rf a b c; mkdir a b c; touch a/f b/f; mv a/f b/f c
2472 Otherwise, the contents of b/f would be lost.
2473 In the case of 'cp', b/f would be lost if the user simulated
2474 a move using cp and rm.
2475 Note that it works fine if you use --backup=numbered. */
2476 if (!S_ISDIR (dst_sb
.st_mode
) && command_line_arg
2477 && x
->backup_type
!= numbered_backups
2478 && seen_file (x
->dest_info
, dst_relname
, &dst_sb
))
2481 _("will not overwrite just-created %s with %s"),
2482 quoteaf_n (0, dst_name
), quoteaf_n (1, src_name
));
2486 char const *srcbase
;
2487 if (x
->backup_type
!= no_backups
2488 /* Don't try to back up a destination if the last
2489 component of src_name is "." or "..". */
2490 && ! dot_or_dotdot (srcbase
= last_component (src_name
))
2491 /* Create a backup of each destination directory in move mode,
2492 but not in copy mode. FIXME: it might make sense to add an
2493 option to suppress backup creation also for move mode.
2494 That would let one use mv to merge new content into an
2495 existing hierarchy. */
2496 && (x
->move_mode
|| ! S_ISDIR (dst_sb
.st_mode
)))
2498 /* Fail if creating the backup file would likely destroy
2499 the source file. Otherwise, the commands:
2500 cd /tmp; rm -f a a~; : > a; echo A > a~; cp --b=simple a~ a
2501 would leave two zero-length files: a and a~. */
2502 if (x
->backup_type
!= numbered_backups
2503 && source_is_dst_backup (srcbase
, &src_sb
,
2504 dst_dirfd
, dst_relname
))
2508 ? _("backing up %s might destroy source; %s not moved")
2509 : _("backing up %s might destroy source; %s not copied"));
2511 quoteaf_n (0, dst_name
),
2512 quoteaf_n (1, src_name
));
2516 char *tmp_backup
= backup_file_rename (dst_dirfd
, dst_relname
,
2520 Using alloca for a file name that may be arbitrarily
2521 long is not recommended. In fact, even forming such a name
2522 should be discouraged. Eventually, this code will be rewritten
2523 to use fts, so using alloca here will be less of a problem. */
2526 idx_t dirlen
= dst_relname
- dst_name
;
2527 idx_t backupsize
= strlen (tmp_backup
) + 1;
2528 dst_backup
= alloca (dirlen
+ backupsize
);
2529 memcpy (mempcpy (dst_backup
, dst_name
, dirlen
),
2530 tmp_backup
, backupsize
);
2533 else if (errno
!= ENOENT
)
2535 error (0, errno
, _("cannot backup %s"), quoteaf (dst_name
));
2540 else if (! S_ISDIR (dst_sb
.st_mode
)
2541 /* Never unlink dst_name when in move mode. */
2543 && (x
->unlink_dest_before_opening
2544 || (x
->data_copy_required
2545 && ((x
->preserve_links
&& 1 < dst_sb
.st_nlink
)
2546 || (x
->dereference
== DEREF_NEVER
2547 && ! S_ISREG (src_sb
.st_mode
))))
2550 if (unlinkat (dst_dirfd
, dst_relname
, 0) != 0 && errno
!= ENOENT
)
2552 error (0, errno
, _("cannot remove %s"), quoteaf (dst_name
));
2557 printf (_("removed %s\n"), quoteaf (dst_name
));
2562 /* Ensure we don't try to copy through a symlink that was
2563 created by a prior call to this function. */
2564 if (command_line_arg
2567 && x
->backup_type
== no_backups
)
2569 /* If we did not follow symlinks above, good: use that data.
2570 Otherwise, use AT_SYMLINK_NOFOLLOW, in case dst_name is a symlink. */
2571 struct stat tmp_buf
;
2572 struct stat
*dst_lstat_sb
2573 = (have_dst_lstat
? &dst_sb
2574 : fstatat (dst_dirfd
, drelname
, &tmp_buf
, AT_SYMLINK_NOFOLLOW
) < 0
2575 ? nullptr : &tmp_buf
);
2577 /* Never copy through a symlink we've just created. */
2579 && S_ISLNK (dst_lstat_sb
->st_mode
)
2580 && seen_file (x
->dest_info
, dst_relname
, dst_lstat_sb
))
2583 _("will not copy %s through just-created symlink %s"),
2584 quoteaf_n (0, src_name
), quoteaf_n (1, dst_name
));
2589 /* If the source is a directory, we don't always create the destination
2590 directory. So --verbose should not announce anything until we're
2591 sure we'll create a directory. Also don't announce yet when moving
2592 so we can distinguish renames versus copies. */
2593 if (x
->verbose
&& !x
->move_mode
&& !S_ISDIR (src_mode
))
2594 emit_verbose (src_name
, dst_name
, dst_backup
);
2596 /* Associate the destination file name with the source device and inode
2597 so that if we encounter a matching dev/ino pair in the source tree
2598 we can arrange to create a hard link between the corresponding names
2599 in the destination tree.
2601 When using the --link (-l) option, there is no need to take special
2602 measures, because (barring race conditions) files that are hard-linked
2603 in the source tree will also be hard-linked in the destination tree.
2605 Sometimes, when preserving links, we have to record dev/ino even
2606 though st_nlink == 1:
2607 - when in move_mode, since we may be moving a group of N hard-linked
2608 files (via two or more command line arguments) to a different
2609 partition; the links may be distributed among the command line
2610 arguments (possibly hierarchies) so that the link count of
2611 the final, once-linked source file is reduced to 1 when it is
2612 considered below. But in this case (for mv) we don't need to
2613 incur the expense of recording the dev/ino => name mapping; all we
2614 really need is a lookup, to see if the dev/ino pair has already
2616 - when using -H and processing a command line argument;
2617 that command line argument could be a symlink pointing to another
2618 command line argument. With 'cp -H --preserve=link', we hard-link
2619 those two destination files.
2620 - likewise for -L except that it applies to all files, not just
2621 command line arguments.
2623 Also, with --recursive, record dev/ino of each command-line directory.
2624 We'll use that info to detect this problem: cp -R dir dir. */
2626 if (rename_errno
== 0 || x
->exchange
)
2627 earlier_file
= nullptr;
2628 else if (x
->recursive
&& S_ISDIR (src_mode
))
2630 if (command_line_arg
)
2631 earlier_file
= remember_copied (dst_relname
,
2632 src_sb
.st_ino
, src_sb
.st_dev
);
2634 earlier_file
= src_to_dest_lookup (src_sb
.st_ino
, src_sb
.st_dev
);
2636 else if (x
->move_mode
&& src_sb
.st_nlink
== 1)
2638 earlier_file
= src_to_dest_lookup (src_sb
.st_ino
, src_sb
.st_dev
);
2640 else if (x
->preserve_links
2642 && (1 < src_sb
.st_nlink
2643 || (command_line_arg
2644 && x
->dereference
== DEREF_COMMAND_LINE_ARGUMENTS
)
2645 || x
->dereference
== DEREF_ALWAYS
))
2647 earlier_file
= remember_copied (dst_relname
,
2648 src_sb
.st_ino
, src_sb
.st_dev
);
2651 /* Did we copy this inode somewhere else (in this command line argument)
2652 and therefore this is a second hard link to the inode? */
2656 /* Avoid damaging the destination file system by refusing to preserve
2657 hard-linked directories (which are found at least in Netapp snapshot
2659 if (S_ISDIR (src_mode
))
2661 /* If src_name and earlier_file refer to the same directory entry,
2662 then warn about copying a directory into itself. */
2663 if (same_nameat (AT_FDCWD
, src_name
, dst_dirfd
, earlier_file
))
2665 error (0, 0, _("cannot copy a directory, %s, into itself, %s"),
2666 quoteaf_n (0, top_level_src_name
),
2667 quoteaf_n (1, top_level_dst_name
));
2668 *copy_into_self
= true;
2671 else if (same_nameat (dst_dirfd
, dst_relname
,
2672 dst_dirfd
, earlier_file
))
2674 error (0, 0, _("warning: source directory %s "
2675 "specified more than once"),
2676 quoteaf (top_level_src_name
));
2677 /* In move mode, if a previous rename succeeded, then
2678 we won't be in this path as the source is missing. If the
2679 rename previously failed, then that has been handled, so
2680 pretend this attempt succeeded so the source isn't removed. */
2681 if (x
->move_mode
&& rename_succeeded
)
2682 *rename_succeeded
= true;
2683 /* We only do backups in move mode, and for non directories.
2684 So just ignore this repeated entry. */
2687 else if (x
->dereference
== DEREF_ALWAYS
2688 || (command_line_arg
2689 && x
->dereference
== DEREF_COMMAND_LINE_ARGUMENTS
))
2691 /* This happens when e.g., encountering a directory for the
2692 second or subsequent time via symlinks when cp is invoked
2693 with -R and -L. E.g.,
2694 rm -rf a b c d; mkdir a b c d; ln -s ../c a; ln -s ../c b;
2700 char *earlier
= subst_suffix (dst_name
, dst_relname
,
2702 error (0, 0, _("will not create hard link %s to directory %s"),
2703 quoteaf_n (0, dst_name
), quoteaf_n (1, earlier
));
2710 if (! create_hard_link (nullptr, dst_dirfd
, earlier_file
,
2711 dst_name
, dst_dirfd
, dst_relname
,
2712 true, x
->verbose
, dereference
))
2721 if (rename_errno
== EEXIST
&& !x
->exchange
)
2722 rename_errno
= (renameat (AT_FDCWD
, src_name
, dst_dirfd
, drelname
) == 0
2725 if (rename_errno
== 0)
2729 printf (_("renamed "));
2730 emit_verbose (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
);
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. */
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
2809 char const *quoted_dst_name
= quoteaf_n (1, dst_name
);
2811 error (0, rename_errno
, _("cannot exchange %s and %s"),
2812 quoteaf_n (0, src_name
), quoted_dst_name
);
2814 switch (rename_errno
)
2816 case EDQUOT
: case EEXIST
: case EISDIR
: case EMLINK
:
2817 case ENOSPC
: case ETXTBSY
:
2818 #if ENOTEMPTY != EEXIST
2821 /* The destination must be the problem. Don't mention
2822 the source as that is more likely to confuse the user
2824 error (0, rename_errno
, _("cannot overwrite %s"),
2829 error (0, rename_errno
, _("cannot move %s to %s"),
2830 quoteaf_n (0, src_name
), quoted_dst_name
);
2833 forget_created (src_sb
.st_ino
, src_sb
.st_dev
);
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)
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
);
2855 if (x
->verbose
&& !S_ISDIR (src_mode
))
2857 printf (_("copied "));
2858 emit_verbose (src_name
, dst_name
, dst_backup
);
2863 /* If the ownership might change, or if it is a directory (whose
2864 special mode bits may change after the directory is created),
2865 omit some permissions at first, so unauthorized users cannot nip
2866 in before the file is ready. */
2867 dst_mode_bits
= (x
->set_mode
? x
->mode
: src_mode
) & CHMOD_MODE_BITS
;
2868 omitted_permissions
=
2870 & (x
->preserve_ownership
? S_IRWXG
| S_IRWXO
2871 : S_ISDIR (src_mode
) ? S_IWGRP
| S_IWOTH
2876 /* If required, set the default security context for new files.
2877 Also for existing files this is used as a reference
2878 when copying the context with --preserve=context.
2879 FIXME: Do we need to consider dst_mode_bits here? */
2880 if (! set_process_security_ctx (src_name
, dst_name
, src_mode
, new_dst
, x
))
2883 if (S_ISDIR (src_mode
))
2885 struct dir_list
*dir
;
2887 /* If this directory has been copied before during the
2888 recursion, there is a symbolic link to an ancestor
2889 directory of the symbolic link. It is impossible to
2890 continue to copy this, unless we've got an infinite file system. */
2892 if (is_ancestor (&src_sb
, ancestors
))
2894 error (0, 0, _("cannot copy cyclic symbolic link %s"),
2895 quoteaf (src_name
));
2899 /* Insert the current directory in the list of parents. */
2901 dir
= alloca (sizeof *dir
);
2902 dir
->parent
= ancestors
;
2903 dir
->ino
= src_sb
.st_ino
;
2904 dir
->dev
= src_sb
.st_dev
;
2906 if (new_dst
|| !S_ISDIR (dst_sb
.st_mode
))
2908 /* POSIX says mkdir's behavior is implementation-defined when
2909 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
2910 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
2911 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
2912 mode_t mode
= dst_mode_bits
& ~omitted_permissions
;
2913 if (mkdirat (dst_dirfd
, drelname
, mode
) != 0)
2915 error (0, errno
, _("cannot create directory %s"),
2916 quoteaf (dst_name
));
2920 /* We need search and write permissions to the new directory
2921 for writing the directory's contents. Check if these
2922 permissions are there. */
2924 if (fstatat (dst_dirfd
, drelname
, &dst_sb
, AT_SYMLINK_NOFOLLOW
) != 0)
2926 error (0, errno
, _("cannot stat %s"), quoteaf (dst_name
));
2929 else if ((dst_sb
.st_mode
& S_IRWXU
) != S_IRWXU
)
2931 /* Make the new directory searchable and writable. */
2933 dst_mode
= dst_sb
.st_mode
;
2934 restore_dst_mode
= true;
2936 if (lchmodat (dst_dirfd
, drelname
, dst_mode
| S_IRWXU
) != 0)
2938 error (0, errno
, _("setting permissions for %s"),
2939 quoteaf (dst_name
));
2944 /* Record the created directory's inode and device numbers into
2945 the search structure, so that we can avoid copying it again.
2946 Do this only for the first directory that is created for each
2947 source command line argument. */
2948 if (!*first_dir_created_per_command_line_arg
)
2950 remember_copied (dst_relname
, dst_sb
.st_ino
, dst_sb
.st_dev
);
2951 *first_dir_created_per_command_line_arg
= true;
2957 printf (_("created directory %s\n"), quoteaf (dst_name
));
2959 emit_verbose (src_name
, dst_name
, nullptr);
2964 omitted_permissions
= 0;
2966 /* For directories, the process global context could be reset for
2967 descendants, so use it to set the context for existing dirs here.
2968 This will also give earlier indication of failure to set ctx. */
2969 if (x
->set_security_context
|| x
->preserve_security_context
)
2970 if (! set_file_security_ctx (dst_name
, false, x
))
2972 if (x
->require_preserve_context
)
2977 /* Decide whether to copy the contents of the directory. */
2978 if (x
->one_file_system
&& parent
&& parent
->st_dev
!= src_sb
.st_dev
)
2980 /* Here, we are crossing a file system boundary and cp's -x option
2981 is in effect: so don't copy the contents of this directory. */
2985 /* Copy the contents of the directory. Don't just return if
2986 this fails -- otherwise, the failure to read a single file
2987 in a source directory would cause the containing destination
2988 directory not to have owner/perms set properly. */
2989 delayed_ok
= copy_dir (src_name
, dst_name
, dst_dirfd
, dst_relname
,
2990 new_dst
, &src_sb
, dir
, x
,
2991 first_dir_created_per_command_line_arg
,
2995 else if (x
->symbolic_link
)
2997 dest_is_symlink
= true;
2998 if (*src_name
!= '/')
3000 /* Check that DST_NAME denotes a file in the current directory. */
3002 struct stat dst_parent_sb
;
3004 bool in_current_dir
;
3006 dst_parent
= dir_name (dst_relname
);
3008 in_current_dir
= ((dst_dirfd
== AT_FDCWD
&& STREQ (".", dst_parent
))
3009 /* If either stat call fails, it's ok not to report
3010 the failure and say dst_name is in the current
3011 directory. Other things will fail later. */
3012 || stat (".", &dot_sb
) != 0
3013 || (fstatat (dst_dirfd
, dst_parent
, &dst_parent_sb
,
3015 || psame_inode (&dot_sb
, &dst_parent_sb
));
3018 if (! in_current_dir
)
3021 _("%s: can make relative symbolic links only in current directory"),
3027 int err
= force_symlinkat (src_name
, dst_dirfd
, dst_relname
,
3028 x
->unlink_dest_after_failed_open
, -1);
3031 error (0, err
, _("cannot create symbolic link %s to %s"),
3032 quoteaf_n (0, dst_name
), quoteaf_n (1, src_name
));
3037 /* POSIX 2008 states that it is implementation-defined whether
3038 link() on a symlink creates a hard-link to the symlink, or only
3039 to the referent (effectively dereferencing the symlink) (POSIX
3040 2001 required the latter behavior, although many systems provided
3041 the former). Yet cp, invoked with '--link --no-dereference',
3042 should not follow the link. We can approximate the desired
3043 behavior by skipping this hard-link creating block and instead
3044 copying the symlink, via the 'S_ISLNK'- copying code below.
3046 Note gnulib's linkat module, guarantees that the symlink is not
3047 dereferenced. However its emulation currently doesn't maintain
3048 timestamps or ownership so we only call it when we know the
3049 emulation will not be needed. */
3050 else if (x
->hard_link
3051 && !(! CAN_HARDLINK_SYMLINKS
&& S_ISLNK (src_mode
)
3052 && x
->dereference
== DEREF_NEVER
))
3054 bool replace
= (x
->unlink_dest_after_failed_open
3055 || x
->interactive
== I_ASK_USER
);
3056 if (! create_hard_link (src_name
, AT_FDCWD
, src_name
,
3057 dst_name
, dst_dirfd
, dst_relname
,
3058 replace
, false, dereference
))
3061 else if (S_ISREG (src_mode
)
3062 || (x
->copy_as_regular
&& !S_ISLNK (src_mode
)))
3064 copied_as_regular
= true;
3065 /* POSIX says the permission bits of the source file must be
3066 used as the 3rd argument in the open call. Historical
3067 practice passed all the source mode bits to 'open', but the extra
3068 bits were ignored, so it should be the same either way.
3070 This call uses DST_MODE_BITS, not SRC_MODE. These are
3071 normally the same, and the exception (where x->set_mode) is
3072 used only by 'install', which POSIX does not specify and
3073 where DST_MODE_BITS is what's wanted. */
3074 if (! copy_reg (src_name
, dst_name
, dst_dirfd
, dst_relname
,
3075 x
, dst_mode_bits
& S_IRWXUGO
,
3076 omitted_permissions
, &new_dst
, &src_sb
))
3079 else if (S_ISFIFO (src_mode
))
3081 /* Use mknodat, rather than mkfifoat, because the former preserves
3082 the special mode bits of a fifo on Solaris 10, while mkfifoat
3083 does not. But fall back on mkfifoat, because on some BSD systems,
3084 mknodat always fails when asked to create a FIFO. */
3085 mode_t mode
= src_mode
& ~omitted_permissions
;
3086 if (mknodat (dst_dirfd
, dst_relname
, mode
, 0) != 0)
3087 if (mkfifoat (dst_dirfd
, dst_relname
, mode
& ~S_IFIFO
) != 0)
3089 error (0, errno
, _("cannot create fifo %s"), quoteaf (dst_name
));
3093 else if (S_ISBLK (src_mode
) || S_ISCHR (src_mode
) || S_ISSOCK (src_mode
))
3095 mode_t mode
= src_mode
& ~omitted_permissions
;
3096 if (mknodat (dst_dirfd
, dst_relname
, mode
, src_sb
.st_rdev
) != 0)
3098 error (0, errno
, _("cannot create special file %s"),
3099 quoteaf (dst_name
));
3103 else if (S_ISLNK (src_mode
))
3105 char *src_link_val
= areadlink_with_size (src_name
, src_sb
.st_size
);
3106 dest_is_symlink
= true;
3107 if (src_link_val
== nullptr)
3109 error (0, errno
, _("cannot read symbolic link %s"),
3110 quoteaf (src_name
));
3114 int symlink_err
= force_symlinkat (src_link_val
, dst_dirfd
, dst_relname
,
3115 x
->unlink_dest_after_failed_open
, -1);
3116 if (0 < symlink_err
&& x
->update
&& !new_dst
&& S_ISLNK (dst_sb
.st_mode
)
3117 && dst_sb
.st_size
== strlen (src_link_val
))
3119 /* See if the destination is already the desired symlink.
3120 FIXME: This behavior isn't documented, and seems wrong
3121 in some cases, e.g., if the destination symlink has the
3122 wrong ownership, permissions, or timestamps. */
3123 char *dest_link_val
=
3124 areadlinkat_with_size (dst_dirfd
, dst_relname
, dst_sb
.st_size
);
3127 if (STREQ (dest_link_val
, src_link_val
))
3129 free (dest_link_val
);
3132 free (src_link_val
);
3133 if (0 < symlink_err
)
3135 error (0, symlink_err
, _("cannot create symbolic link %s"),
3136 quoteaf (dst_name
));
3140 if (x
->preserve_security_context
)
3141 restore_default_fscreatecon_or_die ();
3143 if (x
->preserve_ownership
)
3145 /* Preserve the owner and group of the just-'copied'
3146 symbolic link, if possible. */
3148 && (lchownat (dst_dirfd
, dst_relname
,
3149 src_sb
.st_uid
, src_sb
.st_gid
)
3151 && ! chown_failure_ok (x
))
3153 error (0, errno
, _("failed to preserve ownership for %s"),
3155 if (x
->require_preserve
)
3160 /* Can't preserve ownership of symlinks.
3161 FIXME: maybe give a warning or even error for symlinks
3162 in directories with the sticky bit set -- there, not
3163 preserving owner/group is a potential security problem. */
3169 error (0, 0, _("%s has unknown file type"), quoteaf (src_name
));
3173 /* With -Z or --preserve=context, set the context for existing files.
3174 Note this is done already for copy_reg() for reasons described therein. */
3175 if (!new_dst
&& !x
->copy_as_regular
&& !S_ISDIR (src_mode
)
3176 && (x
->set_security_context
|| x
->preserve_security_context
))
3178 if (! set_file_security_ctx (dst_name
, false, x
))
3180 if (x
->require_preserve_context
)
3185 if (command_line_arg
&& x
->dest_info
)
3187 /* Now that the destination file is very likely to exist,
3188 add its info to the set. */
3190 if (fstatat (dst_dirfd
, drelname
, &sb
, AT_SYMLINK_NOFOLLOW
) == 0)
3191 record_file (x
->dest_info
, dst_relname
, &sb
);
3194 /* If we've just created a hard-link due to cp's --link option,
3196 if (x
->hard_link
&& ! S_ISDIR (src_mode
)
3197 && !(! CAN_HARDLINK_SYMLINKS
&& S_ISLNK (src_mode
)
3198 && x
->dereference
== DEREF_NEVER
))
3201 if (copied_as_regular
)
3204 /* POSIX says that 'cp -p' must restore the following:
3206 - setuid, setgid bits
3208 If it fails to restore any of those, we may give a warning but
3209 the destination must not be removed.
3210 FIXME: implement the above. */
3212 /* Adjust the times (and if possible, ownership) for the copy.
3213 chown turns off set[ug]id bits for non-root,
3214 so do the chmod last. */
3216 if (x
->preserve_timestamps
)
3218 struct timespec timespec
[2];
3219 timespec
[0] = get_stat_atime (&src_sb
);
3220 timespec
[1] = get_stat_mtime (&src_sb
);
3222 int utimensat_flags
= dest_is_symlink
? AT_SYMLINK_NOFOLLOW
: 0;
3223 if (utimensat (dst_dirfd
, drelname
, timespec
, utimensat_flags
) != 0)
3225 error (0, errno
, _("preserving times for %s"), quoteaf (dst_name
));
3226 if (x
->require_preserve
)
3231 /* Avoid calling chown if we know it's not necessary. */
3232 if (!dest_is_symlink
&& x
->preserve_ownership
3233 && (new_dst
|| !SAME_OWNER_AND_GROUP (src_sb
, dst_sb
)))
3235 switch (set_owner (x
, dst_name
, dst_dirfd
, drelname
, -1,
3236 &src_sb
, new_dst
, &dst_sb
))
3242 src_mode
&= ~ (S_ISUID
| S_ISGID
| S_ISVTX
);
3247 /* Set xattrs after ownership as changing owners will clear capabilities. */
3248 if (x
->preserve_xattr
&& ! copy_attr (src_name
, -1, dst_name
, -1, x
)
3249 && x
->require_preserve_xattr
)
3252 /* The operations beyond this point may dereference a symlink. */
3253 if (dest_is_symlink
)
3256 set_author (dst_name
, -1, &src_sb
);
3258 if (x
->preserve_mode
|| x
->move_mode
)
3260 if (copy_acl (src_name
, -1, dst_name
, -1, src_mode
) != 0
3261 && x
->require_preserve
)
3264 else if (x
->set_mode
)
3266 if (set_acl (dst_name
, -1, x
->mode
) != 0)
3269 else if (x
->explicit_no_preserve_mode
&& new_dst
)
3271 int default_permissions
= S_ISDIR (src_mode
) || S_ISSOCK (src_mode
)
3272 ? S_IRWXUGO
: MODE_RW_UGO
;
3273 if (set_acl (dst_name
, -1, default_permissions
& ~cached_umask ()) != 0)
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
)
3294 error (0, errno
, _("cannot stat %s"), quoteaf (dst_name
));
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
)
3308 error (0, errno
, _("preserving permissions for %s"),
3309 quoteaf (dst_name
));
3310 if (x
->require_preserve
)
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
);
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
));
3340 printf (_("%s -> %s (unbackup)\n"),
3341 quoteaf_n (0, dst_backup
), quoteaf_n (1, dst_name
));
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
));
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. */
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,
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. */
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 ();
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
);
3415 x
->chown_privileges
= x
->owner_privileges
= (geteuid () == ROOT_UID
);
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
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. */
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. */
3461 static mode_t mask
= (mode_t
) -1;
3462 if (mask
== (mode_t
) -1)