1 /* copy.c -- core functions for copying files and directories
2 Copyright (C) 1989-2023 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. */
20 #include <stdckdint.h>
22 #include <sys/ioctl.h>
23 #include <sys/types.h>
24 #include <selinux/selinux.h>
35 #include "alignalloc.h"
37 #include "backupfile.h"
38 #include "buffer-lcm.h"
39 #include "canonicalize.h"
46 #include "filenamecat.h"
47 #include "force-link.h"
48 #include "full-write.h"
50 #include "hash-triple.h"
51 #include "ignore-value.h"
52 #include "ioblksize.h"
54 #include "renameatu.h"
58 #include "stat-size.h"
59 #include "stat-time.h"
62 #include "write-any-file.h"
63 #include "areadlink.h"
68 # define USE_XATTR false
72 # include <attr/error_context.h>
73 # include <attr/libattr.h>
78 #if HAVE_LINUX_FALLOC_H
79 # include <linux/falloc.h>
82 /* See HAVE_FALLOCATE workaround when including this file. */
83 #ifdef HAVE_LINUX_FS_H
84 # include <linux/fs.h>
87 #if !defined FICLONE && defined __linux__
88 # define FICLONE _IOW (0x94, 9, int)
91 #if HAVE_FCLONEFILEAT && !USE_XATTR
92 # include <sys/clonefile.h>
99 #define SAME_OWNER(A, B) ((A).st_uid == (B).st_uid)
100 #define SAME_GROUP(A, B) ((A).st_gid == (B).st_gid)
101 #define SAME_OWNER_AND_GROUP(A, B) (SAME_OWNER (A, B) && SAME_GROUP (A, B))
103 /* LINK_FOLLOWS_SYMLINKS is tri-state; if it is -1, we don't know
104 how link() behaves, so assume we can't hardlink symlinks in that case. */
105 #if (defined HAVE_LINKAT && ! LINKAT_SYMLINK_NOTSUP) || ! LINK_FOLLOWS_SYMLINKS
106 # define CAN_HARDLINK_SYMLINKS 1
108 # define CAN_HARDLINK_SYMLINKS 0
113 struct dir_list
*parent
;
118 /* Initial size of the cp.dest_info hash table. */
119 #define DEST_INFO_INITIAL_CAPACITY 61
121 static bool copy_internal (char const *src_name
, char const *dst_name
,
122 int dst_dirfd
, char const *dst_relname
,
123 int nonexistent_dst
, struct stat
const *parent
,
124 struct dir_list
*ancestors
,
125 const struct cp_options
*x
,
126 bool command_line_arg
,
127 bool *first_dir_created_per_command_line_arg
,
128 bool *copy_into_self
,
129 bool *rename_succeeded
);
130 static bool owner_failure_ok (struct cp_options
const *x
);
132 /* Pointers to the file names: they're used in the diagnostic that is issued
133 when we detect the user is trying to copy a directory into itself. */
134 static char const *top_level_src_name
;
135 static char const *top_level_dst_name
;
143 COPY_DEBUG_EXTERNAL_INTERNAL
,
145 COPY_DEBUG_UNSUPPORTED
,
148 /* debug info about the last file copy. */
149 static struct copy_debug
151 enum copy_debug_val offload
;
152 enum copy_debug_val reflink
;
153 enum copy_debug_val sparse_detection
;
157 copy_debug_string (enum copy_debug_val debug_val
)
161 case COPY_DEBUG_NO
: return "no";
162 case COPY_DEBUG_YES
: return "yes";
163 case COPY_DEBUG_AVOIDED
: return "avoided";
164 case COPY_DEBUG_UNSUPPORTED
: return "unsupported";
165 default: return "unknown";
170 copy_debug_sparse_string (enum copy_debug_val debug_val
)
174 case COPY_DEBUG_NO
: return "no";
175 case COPY_DEBUG_YES
: return "zeros";
176 case COPY_DEBUG_EXTERNAL
: return "SEEK_HOLE";
177 case COPY_DEBUG_EXTERNAL_INTERNAL
: return "SEEK_HOLE + zeros";
178 default: return "unknown";
182 /* Print --debug output on standard output. */
184 emit_debug (const struct cp_options
*x
)
186 if (! x
->hard_link
&& ! x
->symbolic_link
&& x
->data_copy_required
)
187 printf ("copy offload: %s, reflink: %s, sparse detection: %s\n",
188 copy_debug_string (copy_debug
.offload
),
189 copy_debug_string (copy_debug
.reflink
),
190 copy_debug_sparse_string (copy_debug
.sparse_detection
));
193 #ifndef DEV_FD_MIGHT_BE_CHR
194 # define DEV_FD_MIGHT_BE_CHR false
197 /* Act like fstat (DIRFD, FILENAME, ST, FLAGS), except when following
198 symbolic links on Solaris-like systems, treat any character-special
199 device like /dev/fd/0 as if it were the file it is open on. */
201 follow_fstatat (int dirfd
, char const *filename
, struct stat
*st
, int flags
)
203 int result
= fstatat (dirfd
, filename
, st
, flags
);
205 if (DEV_FD_MIGHT_BE_CHR
&& result
== 0 && !(flags
& AT_SYMLINK_NOFOLLOW
)
206 && S_ISCHR (st
->st_mode
))
208 static dev_t stdin_rdev
;
209 static signed char stdin_rdev_status
;
210 if (stdin_rdev_status
== 0)
212 struct stat stdin_st
;
213 if (stat ("/dev/stdin", &stdin_st
) == 0 && S_ISCHR (stdin_st
.st_mode
)
214 && minor (stdin_st
.st_rdev
) == STDIN_FILENO
)
216 stdin_rdev
= stdin_st
.st_rdev
;
217 stdin_rdev_status
= 1;
220 stdin_rdev_status
= -1;
222 if (0 < stdin_rdev_status
&& major (stdin_rdev
) == major (st
->st_rdev
))
223 result
= fstat (minor (st
->st_rdev
), st
);
229 /* Attempt to punch a hole to avoid any permanent
230 speculative preallocation on file systems such as XFS.
231 Return values as per fallocate(2) except ENOSYS etc. are ignored. */
234 punch_hole (int fd
, off_t offset
, off_t length
)
237 /* +0 is to work around older <linux/fs.h> defining HAVE_FALLOCATE to empty. */
238 #if HAVE_FALLOCATE + 0
239 # if defined FALLOC_FL_PUNCH_HOLE && defined FALLOC_FL_KEEP_SIZE
240 ret
= fallocate (fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
242 if (ret
< 0 && (is_ENOTSUP (errno
) || errno
== ENOSYS
))
249 /* Create a hole at the end of a file,
250 avoiding preallocation if requested. */
253 create_hole (int fd
, char const *name
, bool punch_holes
, off_t size
)
255 off_t file_end
= lseek (fd
, size
, SEEK_CUR
);
259 error (0, errno
, _("cannot lseek %s"), quoteaf (name
));
263 /* Some file systems (like XFS) preallocate when write extending a file.
264 I.e., a previous write() may have preallocated extra space
265 that the seek above will not discard. A subsequent write() could
266 then make this allocation permanent. */
267 if (punch_holes
&& punch_hole (fd
, file_end
- size
, size
) < 0)
269 error (0, errno
, _("error deallocating %s"), quoteaf (name
));
277 /* Whether an errno value ERR, set by FICLONE or copy_file_range,
278 indicates that the copying operation has terminally failed, even
279 though it was invoked correctly (so that, e.g, EBADF cannot occur)
280 and even though !is_CLONENOTSUP (ERR). */
283 is_terminal_error (int err
)
285 return err
== EIO
|| err
== ENOMEM
|| err
== ENOSPC
|| err
== EDQUOT
;
288 /* Similarly, whether ERR indicates that the copying operation is not
289 supported or allowed for this file or process, even though the
290 operation was invoked correctly. */
293 is_CLONENOTSUP (int err
)
295 return err
== ENOSYS
|| err
== ENOTTY
|| is_ENOTSUP (err
)
296 || err
== EINVAL
|| err
== EBADF
297 || err
== EXDEV
|| err
== ETXTBSY
298 || err
== EPERM
|| err
== EACCES
;
302 /* Copy the regular file open on SRC_FD/SRC_NAME to DST_FD/DST_NAME,
303 honoring the MAKE_HOLES setting and using the BUF_SIZE-byte buffer
304 *ABUF for temporary storage, allocating it lazily if *ABUF is null.
305 Copy no more than MAX_N_READ bytes.
306 Return true upon successful completion;
307 print a diagnostic and return false upon error.
308 Note that for best results, BUF should be "well"-aligned.
309 Set *LAST_WRITE_MADE_HOLE to true if the final operation on
310 DEST_FD introduced a hole. Set *TOTAL_N_READ to the number of
313 sparse_copy (int src_fd
, int dest_fd
, char **abuf
, size_t buf_size
,
314 size_t hole_size
, bool punch_holes
, bool allow_reflink
,
315 char const *src_name
, char const *dst_name
,
316 uintmax_t max_n_read
, off_t
*total_n_read
,
317 bool *last_write_made_hole
)
319 *last_write_made_hole
= false;
322 if (copy_debug
.sparse_detection
== COPY_DEBUG_UNKNOWN
)
323 copy_debug
.sparse_detection
= hole_size
? COPY_DEBUG_YES
: COPY_DEBUG_NO
;
324 else if (hole_size
&& copy_debug
.sparse_detection
== COPY_DEBUG_EXTERNAL
)
325 copy_debug
.sparse_detection
= COPY_DEBUG_EXTERNAL_INTERNAL
;
327 /* If not looking for holes, use copy_file_range if functional,
328 but don't use if reflink disallowed as that may be implicit. */
329 if (!hole_size
&& allow_reflink
)
332 /* Copy at most COPY_MAX bytes at a time; this is min
333 (SSIZE_MAX, SIZE_MAX) truncated to a value that is
334 surely aligned well. */
335 ssize_t copy_max
= MIN (SSIZE_MAX
, SIZE_MAX
) >> 30 << 30;
336 ssize_t n_copied
= copy_file_range (src_fd
, nullptr, dest_fd
, nullptr,
337 MIN (max_n_read
, copy_max
), 0);
340 /* copy_file_range incorrectly returns 0 when reading from
341 the proc file system on the Linux kernel through at
342 least 5.6.19 (2020), so fall back on 'read' if the
343 input file seems empty. */
344 if (*total_n_read
== 0)
346 copy_debug
.offload
= COPY_DEBUG_YES
;
351 copy_debug
.offload
= COPY_DEBUG_UNSUPPORTED
;
353 /* Consider operation unsupported only if no data copied.
354 For example, EPERM could occur if copy_file_range not enabled
355 in seccomp filters, so retry with a standard copy. EPERM can
356 also occur for immutable files, but that would only be in the
357 edge case where the file is made immutable after creating,
358 in which case the (more accurate) error is still shown. */
359 if (*total_n_read
== 0 && is_CLONENOTSUP (errno
))
362 /* ENOENT was seen sometimes across CIFS shares, resulting in
363 no data being copied, but subsequent standard copies succeed. */
364 if (*total_n_read
== 0 && errno
== ENOENT
)
371 error (0, errno
, _("error copying %s to %s"),
372 quoteaf_n (0, src_name
), quoteaf_n (1, dst_name
));
376 copy_debug
.offload
= COPY_DEBUG_YES
;
377 max_n_read
-= n_copied
;
378 *total_n_read
+= n_copied
;
381 copy_debug
.offload
= COPY_DEBUG_AVOIDED
;
384 bool make_hole
= false;
390 *abuf
= xalignalloc (getpagesize (), buf_size
);
392 ssize_t n_read
= read (src_fd
, buf
, MIN (max_n_read
, buf_size
));
397 error (0, errno
, _("error reading %s"), quoteaf (src_name
));
402 max_n_read
-= n_read
;
403 *total_n_read
+= n_read
;
405 /* Loop over the input buffer in chunks of hole_size. */
406 size_t csize
= hole_size
? hole_size
: buf_size
;
412 bool prev_hole
= make_hole
;
413 csize
= MIN (csize
, n_read
);
415 if (hole_size
&& csize
)
416 make_hole
= is_nul (cbuf
, csize
);
418 bool transition
= (make_hole
!= prev_hole
) && psize
;
419 bool last_chunk
= (n_read
== csize
&& ! make_hole
) || ! csize
;
421 if (transition
|| last_chunk
)
428 if (full_write (dest_fd
, pbuf
, psize
) != psize
)
430 error (0, errno
, _("error writing %s"),
437 if (! create_hole (dest_fd
, dst_name
, punch_holes
, psize
))
447 n_read
= 0; /* Finished processing buffer. */
450 csize
= 0; /* Loop again to deal with last chunk. */
452 psize
= 0; /* Reset for next read loop. */
455 else /* Coalesce writes/seeks. */
457 if (ckd_add (&psize
, psize
, csize
))
459 error (0, 0, _("overflow reading %s"), quoteaf (src_name
));
468 *last_write_made_hole
= make_hole
;
470 /* It's tempting to break early here upon a short read from
471 a regular file. That would save the final read syscall
472 for each file. Unfortunately that doesn't work for
473 certain files in /proc or /sys with linux kernels. */
476 /* Ensure a trailing hole is created, so that subsequent
477 calls of sparse_copy() start at the correct offset. */
478 if (make_hole
&& ! create_hole (dest_fd
, dst_name
, punch_holes
, psize
))
484 /* Perform the O(1) btrfs clone operation, if possible.
485 Upon success, return 0. Otherwise, return -1 and set errno. */
487 clone_file (int dest_fd
, int src_fd
)
490 return ioctl (dest_fd
, FICLONE
, src_fd
);
499 /* Write N_BYTES zero bytes to file descriptor FD. Return true if successful.
500 Upon write failure, set errno and return false. */
502 write_zeros (int fd
, off_t n_bytes
)
505 static size_t nz
= IO_BUFSIZE
;
507 /* Attempt to use a relatively large calloc'd source buffer for
508 efficiency, but if that allocation fails, resort to a smaller
509 statically allocated one. */
510 if (zeros
== nullptr)
512 static char fallback
[1024];
513 zeros
= calloc (nz
, 1);
514 if (zeros
== nullptr)
517 nz
= sizeof fallback
;
523 size_t n
= MIN (nz
, n_bytes
);
524 if ((full_write (fd
, zeros
, n
)) != n
)
533 /* Perform an efficient extent copy, if possible. This avoids
534 the overhead of detecting holes in hole-introducing/preserving
535 copy, and thus makes copying sparse files much more efficient.
536 Copy from SRC_FD to DEST_FD, using *ABUF (of size BUF_SIZE) for a buffer.
537 Allocate *ABUF lazily if *ABUF is null.
538 Look for holes of size HOLE_SIZE in the input.
539 The input file is of size SRC_TOTAL_SIZE.
540 Use SPARSE_MODE to determine whether to create holes in the output.
541 SRC_NAME and DST_NAME are the input and output file names.
542 Return true if successful, false (with a diagnostic) otherwise. */
545 lseek_copy (int src_fd
, int dest_fd
, char **abuf
, size_t buf_size
,
546 size_t hole_size
, off_t ext_start
, off_t src_total_size
,
547 enum Sparse_type sparse_mode
,
549 char const *src_name
, char const *dst_name
)
551 off_t last_ext_start
= 0;
552 off_t last_ext_len
= 0;
554 bool wrote_hole_at_eof
= true;
556 copy_debug
.sparse_detection
= COPY_DEBUG_EXTERNAL
;
558 while (0 <= ext_start
)
560 off_t ext_end
= lseek (src_fd
, ext_start
, SEEK_HOLE
);
565 ext_end
= src_total_size
;
566 if (ext_end
<= ext_start
)
568 /* The input file grew; get its current size. */
569 src_total_size
= lseek (src_fd
, 0, SEEK_END
);
570 if (src_total_size
< 0)
573 /* If the input file shrank after growing, stop copying. */
574 if (src_total_size
<= ext_start
)
577 ext_end
= src_total_size
;
580 /* If the input file must have grown, increase its measured size. */
581 if (src_total_size
< ext_end
)
582 src_total_size
= ext_end
;
584 if (lseek (src_fd
, ext_start
, SEEK_SET
) < 0)
587 wrote_hole_at_eof
= false;
588 off_t ext_hole_size
= ext_start
- last_ext_start
- last_ext_len
;
592 if (sparse_mode
!= SPARSE_NEVER
)
594 if (! create_hole (dest_fd
, dst_name
,
595 sparse_mode
== SPARSE_ALWAYS
,
598 wrote_hole_at_eof
= true;
602 /* When not inducing holes and when there is a hole between
603 the end of the previous extent and the beginning of the
604 current one, write zeros to the destination file. */
605 if (! write_zeros (dest_fd
, ext_hole_size
))
607 error (0, errno
, _("%s: write failed"),
614 off_t ext_len
= ext_end
- ext_start
;
615 last_ext_start
= ext_start
;
616 last_ext_len
= ext_len
;
618 /* Copy this extent, looking for further opportunities to not
619 bother to write zeros if --sparse=always, since SEEK_HOLE
620 is conservative and may miss some holes. */
623 if ( ! sparse_copy (src_fd
, dest_fd
, abuf
, buf_size
,
624 sparse_mode
!= SPARSE_ALWAYS
? 0 : hole_size
,
625 true, allow_reflink
, src_name
, dst_name
,
626 ext_len
, &n_read
, &read_hole
))
629 dest_pos
= ext_start
+ n_read
;
631 wrote_hole_at_eof
= read_hole
;
632 if (n_read
< ext_len
)
634 /* The input file shrank. */
635 src_total_size
= dest_pos
;
639 ext_start
= lseek (src_fd
, dest_pos
, SEEK_DATA
);
640 if (ext_start
< 0 && errno
!= ENXIO
)
644 /* When the source file ends with a hole, we have to do a little more work,
645 since the above copied only up to and including the final extent.
646 In order to complete the copy, we may have to insert a hole or write
647 zeros in the destination corresponding to the source file's hole-at-EOF.
649 In addition, if the final extent was a block of zeros at EOF and we've
650 just converted them to a hole in the destination, we must call ftruncate
651 here in order to record the proper length in the destination. */
652 if ((dest_pos
< src_total_size
|| wrote_hole_at_eof
)
653 && ! (sparse_mode
== SPARSE_NEVER
654 ? write_zeros (dest_fd
, src_total_size
- dest_pos
)
655 : ftruncate (dest_fd
, src_total_size
) == 0))
657 error (0, errno
, _("failed to extend %s"), quoteaf (dst_name
));
661 if (sparse_mode
== SPARSE_ALWAYS
&& dest_pos
< src_total_size
662 && punch_hole (dest_fd
, dest_pos
, src_total_size
- dest_pos
) < 0)
664 error (0, errno
, _("error deallocating %s"), quoteaf (dst_name
));
671 error (0, errno
, _("cannot lseek %s"), quoteaf (src_name
));
676 /* FIXME: describe */
677 /* FIXME: rewrite this to use a hash table so we avoid the quadratic
678 performance hit that's probably noticeable only on trees deeper
679 than a few hundred levels. See use of active_dir_map in remove.c */
683 is_ancestor (const struct stat
*sb
, const struct dir_list
*ancestors
)
685 while (ancestors
!= 0)
687 if (ancestors
->ino
== sb
->st_ino
&& ancestors
->dev
== sb
->st_dev
)
689 ancestors
= ancestors
->parent
;
695 errno_unsupported (int err
)
697 return err
== ENOTSUP
|| err
== ENODATA
;
701 ATTRIBUTE_FORMAT ((printf
, 2, 3))
703 copy_attr_error (MAYBE_UNUSED
struct error_context
*ctx
,
704 char const *fmt
, ...)
706 if (!errno_unsupported (errno
))
711 /* use verror module to print error message */
713 verror (0, err
, fmt
, ap
);
718 ATTRIBUTE_FORMAT ((printf
, 2, 3))
720 copy_attr_allerror (MAYBE_UNUSED
struct error_context
*ctx
,
721 char const *fmt
, ...)
726 /* use verror module to print error message */
728 verror (0, err
, fmt
, ap
);
733 copy_attr_quote (MAYBE_UNUSED
struct error_context
*ctx
, char const *str
)
735 return quoteaf (str
);
739 copy_attr_free (MAYBE_UNUSED
struct error_context
*ctx
,
740 MAYBE_UNUSED
char const *str
)
744 /* Exclude SELinux extended attributes that are otherwise handled,
745 and are problematic to copy again. Also honor attributes
746 configured for exclusion in /etc/xattr.conf.
747 FIXME: Should we handle POSIX ACLs similarly?
748 Return zero to skip. */
750 check_selinux_attr (char const *name
, struct error_context
*ctx
)
752 return STRNCMP_LIT (name
, "security.selinux")
753 && attr_copy_check_permissions (name
, ctx
);
756 /* If positive SRC_FD and DST_FD descriptors are passed,
757 then copy by fd, otherwise copy by name. */
760 copy_attr (char const *src_path
, int src_fd
,
761 char const *dst_path
, int dst_fd
, struct cp_options
const *x
)
763 bool all_errors
= (!x
->data_copy_required
|| x
->require_preserve_xattr
);
764 bool some_errors
= (!all_errors
&& !x
->reduce_diagnostics
);
765 int (*check
) (char const *, struct error_context
*)
766 = (x
->preserve_security_context
|| x
->set_security_context
767 ? check_selinux_attr
: nullptr);
769 # if 4 < __GNUC__ + (8 <= __GNUC_MINOR__)
770 /* Pacify gcc -Wsuggest-attribute=format through at least GCC 11.2.1. */
771 # pragma GCC diagnostic push
772 # pragma GCC diagnostic ignored "-Wsuggest-attribute=format"
774 struct error_context
*ctx
775 = (all_errors
|| some_errors
776 ? (&(struct error_context
) {
777 .error
= all_errors
? copy_attr_allerror
: copy_attr_error
,
778 .quote
= copy_attr_quote
,
779 .quote_free
= copy_attr_free
782 # if 4 < __GNUC__ + (8 <= __GNUC_MINOR__)
783 # pragma GCC diagnostic pop
786 return ! (0 <= src_fd
&& 0 <= dst_fd
787 ? attr_copy_fd (src_path
, src_fd
, dst_path
, dst_fd
, check
, ctx
)
788 : attr_copy_file (src_path
, dst_path
, check
, ctx
));
790 #else /* USE_XATTR */
793 copy_attr (MAYBE_UNUSED
char const *src_path
,
794 MAYBE_UNUSED
int src_fd
,
795 MAYBE_UNUSED
char const *dst_path
,
796 MAYBE_UNUSED
int dst_fd
,
797 MAYBE_UNUSED
struct cp_options
const *x
)
801 #endif /* USE_XATTR */
803 /* Read the contents of the directory SRC_NAME_IN, and recursively
804 copy the contents to DST_NAME_IN aka DST_DIRFD+DST_RELNAME_IN.
805 NEW_DST is true if DST_NAME_IN is a directory
806 that was created previously in the recursion.
807 SRC_SB and ANCESTORS describe SRC_NAME_IN.
808 Set *COPY_INTO_SELF if SRC_NAME_IN is a parent of
809 (or the same as) DST_NAME_IN; otherwise, clear it.
810 Propagate *FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG from
811 caller to each invocation of copy_internal. Be careful to
812 pass the address of a temporary, and to update
813 *FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG only upon completion.
814 Return true if successful. */
817 copy_dir (char const *src_name_in
, char const *dst_name_in
,
818 int dst_dirfd
, char const *dst_relname_in
, bool new_dst
,
819 const struct stat
*src_sb
, struct dir_list
*ancestors
,
820 const struct cp_options
*x
,
821 bool *first_dir_created_per_command_line_arg
,
822 bool *copy_into_self
)
826 struct cp_options non_command_line_options
= *x
;
829 name_space
= savedir (src_name_in
, SAVEDIR_SORT_FASTREAD
);
830 if (name_space
== nullptr)
832 /* This diagnostic is a bit vague because savedir can fail in
833 several different ways. */
834 error (0, errno
, _("cannot access %s"), quoteaf (src_name_in
));
838 /* For cp's -H option, dereference command line arguments, but do not
839 dereference symlinks that are found via recursive traversal. */
840 if (x
->dereference
== DEREF_COMMAND_LINE_ARGUMENTS
)
841 non_command_line_options
.dereference
= DEREF_NEVER
;
843 bool new_first_dir_created
= false;
845 while (*namep
!= '\0')
847 bool local_copy_into_self
;
848 char *src_name
= file_name_concat (src_name_in
, namep
, nullptr);
849 char *dst_name
= file_name_concat (dst_name_in
, namep
, nullptr);
850 bool first_dir_created
= *first_dir_created_per_command_line_arg
;
851 bool rename_succeeded
;
853 ok
&= copy_internal (src_name
, dst_name
, dst_dirfd
,
854 dst_name
+ (dst_relname_in
- dst_name_in
),
856 ancestors
, &non_command_line_options
, false,
858 &local_copy_into_self
, &rename_succeeded
);
859 *copy_into_self
|= local_copy_into_self
;
864 /* If we're copying into self, there's no point in continuing,
865 and in fact, that would even infloop, now that we record only
866 the first created directory per command line argument. */
867 if (local_copy_into_self
)
870 new_first_dir_created
|= first_dir_created
;
871 namep
+= strlen (namep
) + 1;
874 *first_dir_created_per_command_line_arg
= new_first_dir_created
;
879 /* Change the file mode bits of the file identified by DESC or
880 DIRFD+NAME to MODE. Use DESC if DESC is valid and fchmod is
881 available, DIRFD+NAME otherwise. */
884 fchmod_or_lchmod (int desc
, int dirfd
, char const *name
, mode_t mode
)
888 return fchmod (desc
, mode
);
890 return lchmodat (dirfd
, name
, mode
);
893 /* Change the ownership of the file identified by DESC or
894 DIRFD+NAME to UID+GID. Use DESC if DESC is valid and fchown is
895 available, DIRFD+NAME otherwise. */
898 fchown_or_lchown (int desc
, int dirfd
, char const *name
, uid_t uid
, gid_t gid
)
902 return fchown (desc
, uid
, gid
);
904 return lchownat (dirfd
, name
, uid
, gid
);
907 /* Set the owner and owning group of DEST_DESC to the st_uid and
908 st_gid fields of SRC_SB. If DEST_DESC is undefined (-1), set
909 the owner and owning group of DST_NAME aka DST_DIRFD+DST_RELNAME
910 instead; for safety prefer lchownat since no
911 symbolic links should be involved. DEST_DESC must
912 refer to the same file as DST_NAME if defined.
913 Upon failure to set both UID and GID, try to set only the GID.
914 NEW_DST is true if the file was newly created; otherwise,
915 DST_SB is the status of the destination.
916 Return 1 if the initial syscall succeeds, 0 if it fails but it's OK
917 not to preserve ownership, -1 otherwise. */
920 set_owner (const struct cp_options
*x
, char const *dst_name
,
921 int dst_dirfd
, char const *dst_relname
, int dest_desc
,
922 struct stat
const *src_sb
, bool new_dst
,
923 struct stat
const *dst_sb
)
925 uid_t uid
= src_sb
->st_uid
;
926 gid_t gid
= src_sb
->st_gid
;
928 /* Naively changing the ownership of an already-existing file before
929 changing its permissions would create a window of vulnerability if
930 the file's old permissions are too generous for the new owner and
931 group. Avoid the window by first changing to a restrictive
932 temporary mode if necessary. */
934 if (!new_dst
&& (x
->preserve_mode
|| x
->move_mode
|| x
->set_mode
))
936 mode_t old_mode
= dst_sb
->st_mode
;
938 (x
->preserve_mode
|| x
->move_mode
? src_sb
->st_mode
: x
->mode
);
939 mode_t restrictive_temp_mode
= old_mode
& new_mode
& S_IRWXU
;
942 || (old_mode
& CHMOD_MODE_BITS
943 & (~new_mode
| S_ISUID
| S_ISGID
| S_ISVTX
)))
944 && qset_acl (dst_name
, dest_desc
, restrictive_temp_mode
) != 0)
946 if (! owner_failure_ok (x
))
947 error (0, errno
, _("clearing permissions for %s"),
949 return -x
->require_preserve
;
953 if (fchown_or_lchown (dest_desc
, dst_dirfd
, dst_relname
, uid
, gid
) == 0)
956 /* The ownership change failed. If the failure merely means we lack
957 privileges to change owner+group, try to change just the group
958 and ignore any failure of this. Otherwise, report an error. */
959 if (chown_failure_ok (x
))
960 ignore_value (fchown_or_lchown (dest_desc
, dst_dirfd
, dst_relname
,
964 error (0, errno
, _("failed to preserve ownership for %s"),
966 if (x
->require_preserve
)
973 /* Set the st_author field of DEST_DESC to the st_author field of
974 SRC_SB. If DEST_DESC is undefined (-1), set the st_author field
975 of DST_NAME instead. DEST_DESC must refer to the same file as
976 DST_NAME if defined. */
979 set_author (char const *dst_name
, int dest_desc
, const struct stat
*src_sb
)
981 #if HAVE_STRUCT_STAT_ST_AUTHOR
982 /* FIXME: Modify the following code so that it does not
983 follow symbolic links. */
985 /* Preserve the st_author field. */
986 file_t file
= (dest_desc
< 0
987 ? file_name_lookup (dst_name
, 0, 0)
988 : getdport (dest_desc
));
989 if (file
== MACH_PORT_NULL
)
990 error (0, errno
, _("failed to lookup file %s"), quoteaf (dst_name
));
993 error_t err
= file_chauthor (file
, src_sb
->st_author
);
995 error (0, err
, _("failed to preserve authorship for %s"),
997 mach_port_deallocate (mach_task_self (), file
);
1006 /* Set the default security context for the process. New files will
1007 have this security context set. Also existing files can have their
1008 context adjusted based on this process context, by
1009 set_file_security_ctx() called with PROCESS_LOCAL=true.
1010 This should be called before files are created so there is no race
1011 where a file may be present without an appropriate security context.
1012 Based on CP_OPTIONS, diagnose warnings and fail when appropriate.
1013 Return FALSE on failure, TRUE on success. */
1016 set_process_security_ctx (char const *src_name
, char const *dst_name
,
1017 mode_t mode
, bool new_dst
, const struct cp_options
*x
)
1019 if (x
->preserve_security_context
)
1021 /* Set the default context for the process to match the source. */
1022 bool all_errors
= !x
->data_copy_required
|| x
->require_preserve_context
;
1023 bool some_errors
= !all_errors
&& !x
->reduce_diagnostics
;
1026 if (0 <= lgetfilecon (src_name
, &con
))
1028 if (setfscreatecon (con
) < 0)
1030 if (all_errors
|| (some_errors
&& !errno_unsupported (errno
)))
1032 _("failed to set default file creation context to %s"),
1034 if (x
->require_preserve_context
)
1044 if (all_errors
|| (some_errors
&& !errno_unsupported (errno
)))
1047 _("failed to get security context of %s"),
1048 quoteaf (src_name
));
1050 if (x
->require_preserve_context
)
1054 else if (x
->set_security_context
)
1056 /* With -Z, adjust the default context for the process
1057 to have the type component adjusted as per the destination path. */
1058 if (new_dst
&& defaultcon (x
->set_security_context
, dst_name
, mode
) < 0
1059 && ! ignorable_ctx_err (errno
))
1062 _("failed to set default file creation context for %s"),
1063 quoteaf (dst_name
));
1070 /* Reset the security context of DST_NAME, to that already set
1071 as the process default if !X->set_security_context. Otherwise
1072 adjust the type component of DST_NAME's security context as
1073 per the system default for that path. Issue warnings upon
1074 failure, when allowed by various settings in X.
1075 Return false on failure, true on success. */
1078 set_file_security_ctx (char const *dst_name
,
1079 bool recurse
, const struct cp_options
*x
)
1081 bool all_errors
= (!x
->data_copy_required
1082 || x
->require_preserve_context
);
1083 bool some_errors
= !all_errors
&& !x
->reduce_diagnostics
;
1085 if (! restorecon (x
->set_security_context
, dst_name
, recurse
))
1087 if (all_errors
|| (some_errors
&& !errno_unsupported (errno
)))
1088 error (0, errno
, _("failed to set the security context of %s"),
1089 quoteaf_n (0, dst_name
));
1096 #ifndef HAVE_STRUCT_STAT_ST_BLOCKS
1097 # define HAVE_STRUCT_STAT_ST_BLOCKS 0
1100 /* Type of scan being done on the input when looking for sparseness. */
1103 /* An error was found when determining scantype. */
1106 /* No fancy scanning; just read and write. */
1109 /* Read and examine data looking for zero blocks; useful when
1110 attempting to create sparse output. */
1113 /* lseek information is available. */
1117 /* Result of infer_scantype. */
1118 union scan_inference
1120 /* Used if infer_scantype returns LSEEK_SCANTYPE. This is the
1121 offset of the first data block, or -1 if the file has no data. */
1125 /* Return how to scan a file with descriptor FD and stat buffer SB.
1126 *SCAN_INFERENCE is set to a valid value if returning LSEEK_SCANTYPE. */
1127 static enum scantype
1128 infer_scantype (int fd
, struct stat
const *sb
,
1129 union scan_inference
*scan_inference
)
1131 scan_inference
->ext_start
= -1; /* avoid -Wmaybe-uninitialized */
1133 /* Only attempt SEEK_HOLE if this heuristic
1134 suggests the file is sparse. */
1135 if (! (HAVE_STRUCT_STAT_ST_BLOCKS
1136 && S_ISREG (sb
->st_mode
)
1137 && STP_NBLOCKS (sb
) < sb
->st_size
/ ST_NBLOCKSIZE
))
1138 return PLAIN_SCANTYPE
;
1141 off_t ext_start
= lseek (fd
, 0, SEEK_DATA
);
1142 if (0 <= ext_start
|| errno
== ENXIO
)
1144 scan_inference
->ext_start
= ext_start
;
1145 return LSEEK_SCANTYPE
;
1147 else if (errno
!= EINVAL
&& !is_ENOTSUP (errno
))
1148 return ERROR_SCANTYPE
;
1151 return ZERO_SCANTYPE
;
1154 #if HAVE_FCLONEFILEAT && !USE_XATTR
1155 # include <sys/acl.h>
1156 /* Return true if FD has a nontrivial ACL. */
1160 /* Every platform with fclonefileat (macOS 10.12 or later) also has
1162 bool has_acl
= false;
1163 acl_t acl
= acl_get_fd_np (fd
, ACL_TYPE_EXTENDED
);
1167 has_acl
= 0 <= acl_get_entry (acl
, ACL_FIRST_ENTRY
, &ace
);
1174 /* Handle failure from FICLONE or fclonefileat.
1175 Return FALSE if it's a terminal failure for this file. */
1178 handle_clone_fail (int dst_dirfd
, char const *dst_relname
,
1179 char const *src_name
, char const *dst_name
,
1180 int dest_desc
, bool new_dst
, enum Reflink_type reflink_mode
)
1182 /* When the clone operation fails, report failure only with errno values
1183 known to mean trouble when the clone is supported and called properly.
1184 Do not report failure merely because !is_CLONENOTSUP (errno),
1185 as systems may yield oddball errno values here with FICLONE,
1186 and is_CLONENOTSUP is not appropriate for fclonefileat. */
1187 bool report_failure
= is_terminal_error (errno
);
1189 if (reflink_mode
== REFLINK_ALWAYS
|| report_failure
)
1190 error (0, errno
, _("failed to clone %s from %s"),
1191 quoteaf_n (0, dst_name
), quoteaf_n (1, src_name
));
1193 /* Remove the destination if cp --reflink=always created it
1194 but cloned no data. */
1195 if (new_dst
/* currently not for fclonefileat(). */
1196 && reflink_mode
== REFLINK_ALWAYS
1197 && ((! report_failure
) || lseek (dest_desc
, 0, SEEK_END
) == 0)
1198 && unlinkat (dst_dirfd
, dst_relname
, 0) != 0 && errno
!= ENOENT
)
1199 error (0, errno
, _("cannot remove %s"), quoteaf (dst_name
));
1201 if (! report_failure
)
1202 copy_debug
.reflink
= COPY_DEBUG_UNSUPPORTED
;
1204 if (reflink_mode
== REFLINK_ALWAYS
|| report_failure
)
1211 /* Copy a regular file from SRC_NAME to DST_NAME aka DST_DIRFD+DST_RELNAME.
1212 If the source file contains holes, copies holes and blocks of zeros
1213 in the source file as holes in the destination file.
1214 (Holes are read as zeroes by the 'read' system call.)
1215 When creating the destination, use DST_MODE & ~OMITTED_PERMISSIONS
1216 as the third argument in the call to open, adding
1217 OMITTED_PERMISSIONS after copying as needed.
1218 X provides many option settings.
1219 Return true if successful.
1220 *NEW_DST is initially as in copy_internal.
1221 If successful, set *NEW_DST to true if the destination file was created and
1222 to false otherwise; if unsuccessful, perhaps set *NEW_DST to some value.
1223 SRC_SB is the result of calling follow_fstatat on SRC_NAME;
1224 it might be updated by calling fstat again on the same file,
1225 to give it slightly more up-to-date contents. */
1228 copy_reg (char const *src_name
, char const *dst_name
,
1229 int dst_dirfd
, char const *dst_relname
,
1230 const struct cp_options
*x
,
1231 mode_t dst_mode
, mode_t omitted_permissions
, bool *new_dst
,
1232 struct stat
*src_sb
)
1234 char *buf
= nullptr;
1238 mode_t extra_permissions
;
1240 struct stat src_open_sb
;
1241 union scan_inference scan_inference
;
1242 bool return_val
= true;
1243 bool data_copy_required
= x
->data_copy_required
;
1244 bool preserve_xattr
= USE_XATTR
& x
->preserve_xattr
;
1246 copy_debug
.offload
= COPY_DEBUG_UNKNOWN
;
1247 copy_debug
.reflink
= x
->reflink_mode
? COPY_DEBUG_UNKNOWN
: COPY_DEBUG_NO
;
1248 copy_debug
.sparse_detection
= COPY_DEBUG_UNKNOWN
;
1250 source_desc
= open (src_name
,
1251 (O_RDONLY
| O_BINARY
1252 | (x
->dereference
== DEREF_NEVER
? O_NOFOLLOW
: 0)));
1253 if (source_desc
< 0)
1255 error (0, errno
, _("cannot open %s for reading"), quoteaf (src_name
));
1259 if (fstat (source_desc
, &src_open_sb
) != 0)
1261 error (0, errno
, _("cannot fstat %s"), quoteaf (src_name
));
1263 goto close_src_desc
;
1266 /* Compare the source dev/ino from the open file to the incoming,
1267 saved ones obtained via a previous call to stat. */
1268 if (! psame_inode (src_sb
, &src_open_sb
))
1271 _("skipping file %s, as it was replaced while being copied"),
1272 quoteaf (src_name
));
1274 goto close_src_desc
;
1277 /* Might as well tell the caller about the latest version of the
1278 source file status, since we have it already. */
1279 *src_sb
= src_open_sb
;
1280 mode_t src_mode
= src_sb
->st_mode
;
1282 /* The semantics of the following open calls are mandated
1283 by the specs for both cp and mv. */
1287 O_WRONLY
| O_BINARY
| (data_copy_required
? O_TRUNC
: 0);
1288 dest_desc
= openat (dst_dirfd
, dst_relname
, open_flags
);
1291 /* When using cp --preserve=context to copy to an existing destination,
1292 reset the context as per the default context, which has already been
1293 set according to the src.
1294 When using the mutually exclusive -Z option, then adjust the type of
1295 the existing context according to the system default for the dest.
1296 Note we set the context here, _after_ the file is opened, lest the
1297 new context disallow that. */
1299 && (x
->set_security_context
|| x
->preserve_security_context
))
1301 if (! set_file_security_ctx (dst_name
, false, x
))
1303 if (x
->require_preserve_context
)
1306 goto close_src_and_dst_desc
;
1311 if (dest_desc
< 0 && dest_errno
!= ENOENT
1312 && x
->unlink_dest_after_failed_open
)
1314 if (unlinkat (dst_dirfd
, dst_relname
, 0) == 0)
1317 printf (_("removed %s\n"), quoteaf (dst_name
));
1319 else if (errno
!= ENOENT
)
1321 error (0, errno
, _("cannot remove %s"), quoteaf (dst_name
));
1323 goto close_src_desc
;
1326 dest_errno
= ENOENT
;
1329 if (dest_desc
< 0 && dest_errno
== ENOENT
)
1331 /* Ensure there is no race where a file may be left without
1332 an appropriate security context. */
1333 if (x
->set_security_context
)
1335 if (! set_process_security_ctx (src_name
, dst_name
, dst_mode
,
1339 goto close_src_desc
;
1343 /* Tell caller that the destination file is created. */
1350 #if HAVE_FCLONEFILEAT && !USE_XATTR
1352 # define CLONE_ACL 0 /* Added in macOS 12.6. */
1354 # ifndef CLONE_NOOWNERCOPY
1355 # define CLONE_NOOWNERCOPY 0 /* Added in macOS 10.13. */
1357 /* Try fclonefileat if copying data in reflink mode.
1358 Use CLONE_NOFOLLOW to avoid security issues that could occur
1359 if writing through dangling symlinks. Although the circa
1360 2023 macOS documentation doesn't say so, CLONE_NOFOLLOW
1361 affects the destination file too. */
1362 if (data_copy_required
&& x
->reflink_mode
1363 && (CLONE_NOOWNERCOPY
|| x
->preserve_ownership
))
1365 /* Try fclonefileat so long as it won't create the
1366 destination with unwanted permissions, which could lead
1367 to a security race. */
1368 mode_t cloned_mode_bits
= S_ISVTX
| S_IRWXUGO
;
1369 mode_t cloned_mode
= src_mode
& cloned_mode_bits
;
1371 = (x
->preserve_mode
? src_mode
& CHMOD_MODE_BITS
1372 : x
->set_mode
? x
->mode
1373 : ((x
->explicit_no_preserve_mode
? MODE_RW_UGO
: dst_mode
)
1374 & ~ cached_umask ()));
1375 if (! (cloned_mode
& ~desired_mode
))
1379 | (x
->preserve_mode
? CLONE_ACL
: 0)
1380 | (x
->preserve_ownership
? 0 : CLONE_NOOWNERCOPY
));
1381 int s
= fclonefileat (source_desc
, dst_dirfd
, dst_relname
,
1383 if (s
!= 0 && (fc_flags
& CLONE_ACL
) && errno
== EINVAL
)
1385 fc_flags
&= ~CLONE_ACL
;
1386 s
= fclonefileat (source_desc
, dst_dirfd
, dst_relname
,
1391 copy_debug
.reflink
= COPY_DEBUG_YES
;
1393 /* Update the clone's timestamps and permissions
1396 if (!x
->preserve_timestamps
)
1398 struct timespec timespec
[2];
1399 timespec
[0].tv_nsec
= timespec
[1].tv_nsec
= UTIME_NOW
;
1400 if (utimensat (dst_dirfd
, dst_relname
, timespec
,
1401 AT_SYMLINK_NOFOLLOW
)
1404 error (0, errno
, _("updating times for %s"),
1405 quoteaf (dst_name
));
1407 goto close_src_desc
;
1411 extra_permissions
= desired_mode
& ~cloned_mode
;
1412 if (!extra_permissions
1413 && (!x
->preserve_mode
|| (fc_flags
& CLONE_ACL
)
1414 || !fd_has_acl (source_desc
)))
1416 goto close_src_desc
;
1419 /* Either some desired permissions were not cloned,
1420 or ACLs were not cloned despite that being requested. */
1421 omitted_permissions
= 0;
1425 if (! handle_clone_fail (dst_dirfd
, dst_relname
, src_name
,
1427 -1, false /* We didn't create dst */,
1431 goto close_src_desc
;
1435 copy_debug
.reflink
= COPY_DEBUG_AVOIDED
;
1437 else if (data_copy_required
&& x
->reflink_mode
)
1439 if (! CLONE_NOOWNERCOPY
)
1440 copy_debug
.reflink
= COPY_DEBUG_AVOIDED
;
1444 /* To allow copying xattrs on read-only files, create with u+w.
1445 This satisfies an inode permission check done by
1446 xattr_permission in fs/xattr.c of the GNU/Linux kernel. */
1448 ((dst_mode
& ~omitted_permissions
)
1449 | (preserve_xattr
&& !x
->owner_privileges
? S_IWUSR
: 0));
1450 extra_permissions
= open_mode
& ~dst_mode
; /* either 0 or S_IWUSR */
1452 int open_flags
= O_WRONLY
| O_CREAT
| O_BINARY
;
1453 dest_desc
= openat (dst_dirfd
, dst_relname
, open_flags
| O_EXCL
,
1457 /* When trying to copy through a dangling destination symlink,
1458 the above open fails with EEXIST. If that happens, and
1459 readlinkat shows that it is a symlink, then we
1460 have a problem: trying to resolve this dangling symlink to
1461 a directory/destination-entry pair is fundamentally racy,
1462 so punt. If x->open_dangling_dest_symlink is set (cp sets
1463 that when POSIXLY_CORRECT is set in the environment), simply
1464 call open again, but without O_EXCL (potentially dangerous).
1465 If not, fail with a diagnostic. These shenanigans are necessary
1466 only when copying, i.e., not in move_mode. */
1467 if (dest_desc
< 0 && dest_errno
== EEXIST
&& ! x
->move_mode
)
1470 if (0 <= readlinkat (dst_dirfd
, dst_relname
, dummy
, sizeof dummy
))
1472 if (x
->open_dangling_dest_symlink
)
1474 dest_desc
= openat (dst_dirfd
, dst_relname
,
1475 open_flags
, open_mode
);
1480 error (0, 0, _("not writing through dangling symlink %s"),
1481 quoteaf (dst_name
));
1483 goto close_src_desc
;
1488 /* Improve quality of diagnostic when a nonexistent dst_name
1489 ends in a slash and open fails with errno == EISDIR. */
1490 if (dest_desc
< 0 && dest_errno
== EISDIR
1491 && *dst_name
&& dst_name
[strlen (dst_name
) - 1] == '/')
1492 dest_errno
= ENOTDIR
;
1496 omitted_permissions
= extra_permissions
= 0;
1501 error (0, dest_errno
, _("cannot create regular file %s"),
1502 quoteaf (dst_name
));
1504 goto close_src_desc
;
1507 /* --attributes-only overrides --reflink. */
1508 if (data_copy_required
&& x
->reflink_mode
)
1510 if (clone_file (dest_desc
, source_desc
) == 0)
1512 data_copy_required
= false;
1513 copy_debug
.reflink
= COPY_DEBUG_YES
;
1517 if (! handle_clone_fail (dst_dirfd
, dst_relname
, src_name
, dst_name
,
1518 dest_desc
, *new_dst
, x
->reflink_mode
))
1521 goto close_src_and_dst_desc
;
1526 if (! (data_copy_required
| x
->preserve_ownership
| extra_permissions
))
1528 else if (fstat (dest_desc
, &sb
) != 0)
1530 error (0, errno
, _("cannot fstat %s"), quoteaf (dst_name
));
1532 goto close_src_and_dst_desc
;
1535 /* If extra permissions needed for copy_xattr didn't happen (e.g.,
1536 due to umask) chmod to add them temporarily; if that fails give
1537 up with extra permissions, letting copy_attr fail later. */
1538 mode_t temporary_mode
= sb
.st_mode
| extra_permissions
;
1539 if (temporary_mode
!= sb
.st_mode
1540 && (fchmod_or_lchmod (dest_desc
, dst_dirfd
, dst_relname
, temporary_mode
)
1542 extra_permissions
= 0;
1544 if (data_copy_required
)
1546 /* Choose a suitable buffer size; it may be adjusted later. */
1547 size_t buf_size
= io_blksize (&sb
);
1548 size_t hole_size
= STP_BLKSIZE (&sb
);
1550 /* Deal with sparse files. */
1551 enum scantype scantype
= infer_scantype (source_desc
, &src_open_sb
,
1553 if (scantype
== ERROR_SCANTYPE
)
1555 error (0, errno
, _("cannot lseek %s"), quoteaf (src_name
));
1557 goto close_src_and_dst_desc
;
1560 = (S_ISREG (sb
.st_mode
)
1561 && (x
->sparse_mode
== SPARSE_ALWAYS
1562 || (x
->sparse_mode
== SPARSE_AUTO
1563 && scantype
!= PLAIN_SCANTYPE
)));
1565 fdadvise (source_desc
, 0, 0, FADVISE_SEQUENTIAL
);
1567 /* If not making a sparse file, try to use a more-efficient
1571 /* Compute the least common multiple of the input and output
1572 buffer sizes, adjusting for outlandish values.
1573 Note we read in multiples of the reported block size
1574 to support (unusual) devices that have this constraint. */
1575 size_t blcm_max
= MIN (SIZE_MAX
, SSIZE_MAX
);
1576 size_t blcm
= buffer_lcm (io_blksize (&src_open_sb
), buf_size
,
1579 /* Do not bother with a buffer larger than the input file, plus one
1580 byte to make sure the file has not grown while reading it. */
1581 if (S_ISREG (src_open_sb
.st_mode
) && src_open_sb
.st_size
< buf_size
)
1582 buf_size
= src_open_sb
.st_size
+ 1;
1584 /* However, stick with a block size that is a positive multiple of
1585 blcm, overriding the above adjustments. Watch out for
1587 buf_size
+= blcm
- 1;
1588 buf_size
-= buf_size
% blcm
;
1589 if (buf_size
== 0 || blcm_max
< buf_size
)
1594 bool wrote_hole_at_eof
= false;
1597 scantype
== LSEEK_SCANTYPE
1598 ? lseek_copy (source_desc
, dest_desc
, &buf
, buf_size
, hole_size
,
1599 scan_inference
.ext_start
, src_open_sb
.st_size
,
1600 make_holes
? x
->sparse_mode
: SPARSE_NEVER
,
1601 x
->reflink_mode
!= REFLINK_NEVER
,
1605 sparse_copy (source_desc
, dest_desc
, &buf
, buf_size
,
1606 make_holes
? hole_size
: 0,
1607 x
->sparse_mode
== SPARSE_ALWAYS
,
1608 x
->reflink_mode
!= REFLINK_NEVER
,
1609 src_name
, dst_name
, UINTMAX_MAX
, &n_read
,
1610 &wrote_hole_at_eof
)))
1613 goto close_src_and_dst_desc
;
1615 else if (wrote_hole_at_eof
&& ftruncate (dest_desc
, n_read
) < 0)
1617 error (0, errno
, _("failed to extend %s"), quoteaf (dst_name
));
1619 goto close_src_and_dst_desc
;
1623 if (x
->preserve_timestamps
)
1625 struct timespec timespec
[2];
1626 timespec
[0] = get_stat_atime (src_sb
);
1627 timespec
[1] = get_stat_mtime (src_sb
);
1629 if (fdutimensat (dest_desc
, dst_dirfd
, dst_relname
, timespec
, 0) != 0)
1631 error (0, errno
, _("preserving times for %s"), quoteaf (dst_name
));
1632 if (x
->require_preserve
)
1635 goto close_src_and_dst_desc
;
1640 /* Set ownership before xattrs as changing owners will
1641 clear capabilities. */
1642 if (x
->preserve_ownership
&& ! SAME_OWNER_AND_GROUP (*src_sb
, sb
))
1644 switch (set_owner (x
, dst_name
, dst_dirfd
, dst_relname
, dest_desc
,
1645 src_sb
, *new_dst
, &sb
))
1649 goto close_src_and_dst_desc
;
1652 src_mode
&= ~ (S_ISUID
| S_ISGID
| S_ISVTX
);
1659 if (!copy_attr (src_name
, source_desc
, dst_name
, dest_desc
, x
)
1660 && x
->require_preserve_xattr
)
1664 set_author (dst_name
, dest_desc
, src_sb
);
1666 #if HAVE_FCLONEFILEAT && !USE_XATTR
1669 if (x
->preserve_mode
|| x
->move_mode
)
1671 if (copy_acl (src_name
, source_desc
, dst_name
, dest_desc
, src_mode
) != 0
1672 && x
->require_preserve
)
1675 else if (x
->set_mode
)
1677 if (set_acl (dst_name
, dest_desc
, x
->mode
) != 0)
1680 else if (x
->explicit_no_preserve_mode
&& *new_dst
)
1682 if (set_acl (dst_name
, dest_desc
, MODE_RW_UGO
& ~cached_umask ()) != 0)
1685 else if (omitted_permissions
| extra_permissions
)
1687 omitted_permissions
&= ~ cached_umask ();
1688 if ((omitted_permissions
| extra_permissions
)
1689 && (fchmod_or_lchmod (dest_desc
, dst_dirfd
, dst_relname
,
1690 dst_mode
& ~ cached_umask ())
1693 error (0, errno
, _("preserving permissions for %s"),
1694 quoteaf (dst_name
));
1695 if (x
->require_preserve
)
1701 goto close_src_desc
;
1703 close_src_and_dst_desc
:
1704 if (close (dest_desc
) < 0)
1706 error (0, errno
, _("failed to close %s"), quoteaf (dst_name
));
1710 if (close (source_desc
) < 0)
1712 error (0, errno
, _("failed to close %s"), quoteaf (src_name
));
1716 /* Output debug info for data copying operations. */
1724 /* Return whether it's OK that two files are the "same" by some measure.
1725 The first file is SRC_NAME and has status SRC_SB.
1726 The second is DST_DIRFD+DST_RELNAME and has status DST_SB.
1727 The copying options are X. The goal is to avoid
1728 making the 'copy' operation remove both copies of the file
1729 in that case, while still allowing the user to e.g., move or
1730 copy a regular file onto a symlink that points to it.
1731 Try to minimize the cost of this function in the common case.
1732 Set *RETURN_NOW if we've determined that the caller has no more
1733 work to do and should return successfully, right away. */
1736 same_file_ok (char const *src_name
, struct stat
const *src_sb
,
1737 int dst_dirfd
, char const *dst_relname
, struct stat
const *dst_sb
,
1738 const struct cp_options
*x
, bool *return_now
)
1740 const struct stat
*src_sb_link
;
1741 const struct stat
*dst_sb_link
;
1742 struct stat tmp_dst_sb
;
1743 struct stat tmp_src_sb
;
1746 bool same
= psame_inode (src_sb
, dst_sb
);
1748 *return_now
= false;
1750 /* FIXME: this should (at the very least) be moved into the following
1751 if-block. More likely, it should be removed, because it inhibits
1752 making backups. But removing it will result in a change in behavior
1753 that will probably have to be documented -- and tests will have to
1755 if (same
&& x
->hard_link
)
1761 if (x
->dereference
== DEREF_NEVER
)
1765 /* If both the source and destination files are symlinks (and we'll
1766 know this here IFF preserving symlinks), then it's usually ok
1767 when they are distinct. */
1768 if (S_ISLNK (src_sb
->st_mode
) && S_ISLNK (dst_sb
->st_mode
))
1770 bool sn
= same_nameat (AT_FDCWD
, src_name
, dst_dirfd
, dst_relname
);
1773 /* It's fine when we're making any type of backup. */
1774 if (x
->backup_type
!= no_backups
)
1777 /* Here we have two symlinks that are hard-linked together,
1778 and we're not making backups. In this unusual case, simply
1779 returning true would lead to mv calling "rename(A,B)",
1780 which would do nothing and return 0. */
1784 return ! x
->move_mode
;
1791 src_sb_link
= src_sb
;
1792 dst_sb_link
= dst_sb
;
1799 if (fstatat (dst_dirfd
, dst_relname
, &tmp_dst_sb
,
1800 AT_SYMLINK_NOFOLLOW
) != 0
1801 || lstat (src_name
, &tmp_src_sb
) != 0)
1804 src_sb_link
= &tmp_src_sb
;
1805 dst_sb_link
= &tmp_dst_sb
;
1807 same_link
= psame_inode (src_sb_link
, dst_sb_link
);
1809 /* If both are symlinks, then it's ok, but only if the destination
1810 will be unlinked before being opened. This is like the test
1811 above, but with the addition of the unlink_dest_before_opening
1812 conjunct because otherwise, with two symlinks to the same target,
1813 we'd end up truncating the source file. */
1814 if (S_ISLNK (src_sb_link
->st_mode
) && S_ISLNK (dst_sb_link
->st_mode
)
1815 && x
->unlink_dest_before_opening
)
1819 /* The backup code ensures there's a copy, so it's usually ok to
1820 remove any destination file. One exception is when both
1821 source and destination are the same directory entry. In that
1822 case, moving the destination file aside (in making the backup)
1823 would also rename the source file and result in an error. */
1824 if (x
->backup_type
!= no_backups
)
1828 /* In copy mode when dereferencing symlinks, if the source is a
1829 symlink and the dest is not, then backing up the destination
1830 (moving it aside) would make it a dangling symlink, and the
1831 subsequent attempt to open it in copy_reg would fail with
1832 a misleading diagnostic. Avoid that by returning zero in
1833 that case so the caller can make cp (or mv when it has to
1834 resort to reading the source file) fail now. */
1836 /* FIXME-note: even with the following kludge, we can still provoke
1837 the offending diagnostic. It's just a little harder to do :-)
1838 $ rm -f a b c; touch c; ln -s c b; ln -s b a; cp -b a b
1839 cp: cannot open 'a' for reading: No such file or directory
1840 That's misleading, since a subsequent 'ls' shows that 'a'
1842 One solution would be to open the source file *before* moving
1843 aside the destination, but that'd involve a big rewrite. */
1845 && x
->dereference
!= DEREF_NEVER
1846 && S_ISLNK (src_sb_link
->st_mode
)
1847 && ! S_ISLNK (dst_sb_link
->st_mode
))
1853 /* FIXME: What about case insensitive file systems ? */
1854 return ! same_nameat (AT_FDCWD
, src_name
, dst_dirfd
, dst_relname
);
1858 /* FIXME: use or remove */
1860 /* If we're making a backup, we'll detect the problem case in
1861 copy_reg because SRC_NAME will no longer exist. Allowing
1862 the test to be deferred lets cp do some useful things.
1863 But when creating hardlinks and SRC_NAME is a symlink
1864 but DST_RELNAME is not we must test anyway. */
1866 || !S_ISLNK (src_sb_link
->st_mode
)
1867 || S_ISLNK (dst_sb_link
->st_mode
))
1870 if (x
->dereference
!= DEREF_NEVER
)
1874 if (x
->move_mode
|| x
->unlink_dest_before_opening
)
1876 /* They may refer to the same file if we're in move mode and the
1877 target is a symlink. That is ok, since we remove any existing
1878 destination file before opening it -- via 'rename' if they're on
1879 the same file system, via unlinkat otherwise. */
1880 if (S_ISLNK (dst_sb_link
->st_mode
))
1883 /* It's not ok if they're distinct hard links to the same file as
1884 this causes a race condition and we may lose data in this case. */
1886 && 1 < dst_sb_link
->st_nlink
1887 && ! same_nameat (AT_FDCWD
, src_name
, dst_dirfd
, dst_relname
))
1888 return ! x
->move_mode
;
1891 /* If neither is a symlink, then it's ok as long as they aren't
1892 hard links to the same file. */
1893 if (!S_ISLNK (src_sb_link
->st_mode
) && !S_ISLNK (dst_sb_link
->st_mode
))
1895 if (!psame_inode (src_sb_link
, dst_sb_link
))
1898 /* If they are the same file, it's ok if we're making hard links. */
1906 /* At this point, it is normally an error (data loss) to move a symlink
1907 onto its referent, but in at least one narrow case, it is not:
1909 1) src is a symlink,
1910 2) dest has a link count of 2 or more and
1911 3) dest and the referent of src are not the same directory entry,
1912 then it's ok, since while we'll lose one of those hard links,
1913 src will still point to a remaining link.
1914 Note that technically, condition #3 obviates condition #2, but we
1915 retain the 1 < st_nlink condition because that means fewer invocations
1916 of the more expensive #3.
1919 $ touch f && ln f l && ln -s f s
1921 -rw-------. 2 0 Jan 4 22:46 f
1922 -rw-------. 2 0 Jan 4 22:46 l
1923 lrwxrwxrwx. 1 1 Jan 4 22:46 s -> f
1924 this must fail: mv s f
1925 this must succeed: mv s l */
1927 && S_ISLNK (src_sb
->st_mode
)
1928 && 1 < dst_sb_link
->st_nlink
)
1930 char *abs_src
= canonicalize_file_name (src_name
);
1933 bool result
= ! same_nameat (AT_FDCWD
, abs_src
,
1934 dst_dirfd
, dst_relname
);
1940 /* It's ok to recreate a destination symlink. */
1941 if (x
->symbolic_link
&& S_ISLNK (dst_sb_link
->st_mode
))
1944 if (x
->dereference
== DEREF_NEVER
)
1946 if ( ! S_ISLNK (src_sb_link
->st_mode
))
1947 tmp_src_sb
= *src_sb_link
;
1948 else if (stat (src_name
, &tmp_src_sb
) != 0)
1951 if ( ! S_ISLNK (dst_sb_link
->st_mode
))
1952 tmp_dst_sb
= *dst_sb_link
;
1953 else if (fstatat (dst_dirfd
, dst_relname
, &tmp_dst_sb
, 0) != 0)
1956 if (!psame_inode (&tmp_src_sb
, &tmp_dst_sb
))
1961 /* It's ok to attempt to hardlink the same file,
1962 and return early if not replacing a symlink.
1963 Note we need to return early to avoid a later
1964 unlink() of DST (when SRC is a symlink). */
1965 *return_now
= ! S_ISLNK (dst_sb_link
->st_mode
);
1973 /* Return whether DST_DIRFD+DST_RELNAME, with mode MODE,
1974 is writable in the sense of 'mv'.
1975 Always consider a symbolic link to be writable. */
1977 writable_destination (int dst_dirfd
, char const *dst_relname
, mode_t mode
)
1979 return (S_ISLNK (mode
)
1980 || can_write_any_file ()
1981 || faccessat (dst_dirfd
, dst_relname
, W_OK
, AT_EACCESS
) == 0);
1985 overwrite_ok (struct cp_options
const *x
, char const *dst_name
,
1986 int dst_dirfd
, char const *dst_relname
,
1987 struct stat
const *dst_sb
)
1989 if (! writable_destination (dst_dirfd
, dst_relname
, dst_sb
->st_mode
))
1991 char perms
[12]; /* "-rwxrwxrwx " ls-style modes. */
1992 strmode (dst_sb
->st_mode
, perms
);
1995 (x
->move_mode
|| x
->unlink_dest_before_opening
1996 || x
->unlink_dest_after_failed_open
)
1997 ? _("%s: replace %s, overriding mode %04lo (%s)? ")
1998 : _("%s: unwritable %s (mode %04lo, %s); try anyway? "),
1999 program_name
, quoteaf (dst_name
),
2000 (unsigned long int) (dst_sb
->st_mode
& CHMOD_MODE_BITS
),
2005 fprintf (stderr
, _("%s: overwrite %s? "),
2006 program_name
, quoteaf (dst_name
));
2012 /* Initialize the hash table implementing a set of F_triple entries
2013 corresponding to destination files. */
2015 dest_info_init (struct cp_options
*x
)
2018 = hash_initialize (DEST_INFO_INITIAL_CAPACITY
,
2027 /* Initialize the hash table implementing a set of F_triple entries
2028 corresponding to source files listed on the command line. */
2030 src_info_init (struct cp_options
*x
)
2033 /* Note that we use triple_hash_no_name here.
2034 Contrast with the use of triple_hash above.
2035 That is necessary because a source file may be specified
2036 in many different ways. We want to warn about this
2042 = hash_initialize (DEST_INFO_INITIAL_CAPACITY
,
2044 triple_hash_no_name
,
2051 /* When effecting a move (e.g., for mv(1)), and given the name DST_NAME
2052 aka DST_DIRFD+DST_RELNAME
2053 of the destination and a corresponding stat buffer, DST_SB, return
2054 true if the logical 'move' operation should _not_ proceed.
2055 Otherwise, return false.
2056 Depending on options specified in X, this code may issue an
2057 interactive prompt asking whether it's ok to overwrite DST_NAME. */
2059 abandon_move (const struct cp_options
*x
,
2060 char const *dst_name
,
2061 int dst_dirfd
, char const *dst_relname
,
2062 struct stat
const *dst_sb
)
2064 affirm (x
->move_mode
);
2065 return (x
->interactive
== I_ALWAYS_NO
2066 || x
->interactive
== I_ALWAYS_SKIP
2067 || ((x
->interactive
== I_ASK_USER
2068 || (x
->interactive
== I_UNSPECIFIED
2070 && ! writable_destination (dst_dirfd
, dst_relname
,
2072 && ! overwrite_ok (x
, dst_name
, dst_dirfd
, dst_relname
, dst_sb
)));
2075 /* Print --verbose output on standard output, e.g. 'new' -> 'old'.
2076 If BACKUP_DST_NAME is non-null, then also indicate that it is
2077 the name of a backup file. */
2079 emit_verbose (char const *src
, char const *dst
, char const *backup_dst_name
)
2081 printf ("%s -> %s", quoteaf_n (0, src
), quoteaf_n (1, dst
));
2082 if (backup_dst_name
)
2083 printf (_(" (backup: %s)"), quoteaf (backup_dst_name
));
2087 /* A wrapper around "setfscreatecon (nullptr)" that exits upon failure. */
2089 restore_default_fscreatecon_or_die (void)
2091 if (setfscreatecon (nullptr) != 0)
2092 error (EXIT_FAILURE
, errno
,
2093 _("failed to restore the default file creation context"));
2096 /* Return a newly-allocated string that is like STR
2097 except replace its suffix SUFFIX with NEWSUFFIX. */
2099 subst_suffix (char const *str
, char const *suffix
, char const *newsuffix
)
2101 idx_t prefixlen
= suffix
- str
;
2102 idx_t newsuffixsize
= strlen (newsuffix
) + 1;
2103 char *r
= ximalloc (prefixlen
+ newsuffixsize
);
2104 memcpy (r
+ prefixlen
, newsuffix
, newsuffixsize
);
2105 return memcpy (r
, str
, prefixlen
);
2108 /* Create a hard link to SRC_NAME aka SRC_DIRFD+SRC_RELNAME;
2109 the new link is at DST_NAME aka DST_DIRFD+DST_RELNAME.
2110 A null SRC_NAME stands for the file whose name is like DST_NAME
2111 except with DST_RELNAME replaced with SRC_RELNAME.
2112 Honor the REPLACE, VERBOSE and DEREFERENCE settings.
2113 Return true upon success. Otherwise, diagnose the
2114 failure and return false. If SRC_NAME is a symbolic link, then it will not
2115 be followed unless DEREFERENCE is true.
2116 If the system doesn't support hard links to symbolic links, then DST_NAME
2117 will be created as a symbolic link to SRC_NAME. */
2119 create_hard_link (char const *src_name
, int src_dirfd
, char const *src_relname
,
2120 char const *dst_name
, int dst_dirfd
, char const *dst_relname
,
2121 bool replace
, bool verbose
, bool dereference
)
2123 int err
= force_linkat (src_dirfd
, src_relname
, dst_dirfd
, dst_relname
,
2124 dereference
? AT_SYMLINK_FOLLOW
: 0,
2129 char *a_src_name
= nullptr;
2131 src_name
= a_src_name
= subst_suffix (dst_name
, dst_relname
,
2133 error (0, err
, _("cannot create hard link %s to %s"),
2134 quoteaf_n (0, dst_name
), quoteaf_n (1, src_name
));
2138 if (err
< 0 && verbose
)
2139 printf (_("removed %s\n"), quoteaf (dst_name
));
2143 /* Return true if the current file should be (tried to be) dereferenced:
2144 either for DEREF_ALWAYS or for DEREF_COMMAND_LINE_ARGUMENTS in the case
2145 where the current file is a COMMAND_LINE_ARG; otherwise return false. */
2148 should_dereference (const struct cp_options
*x
, bool command_line_arg
)
2150 return x
->dereference
== DEREF_ALWAYS
2151 || (x
->dereference
== DEREF_COMMAND_LINE_ARGUMENTS
2152 && command_line_arg
);
2155 /* Return true if the source file with basename SRCBASE and status SRC_ST
2156 is likely to be the simple backup file for DST_DIRFD+DST_RELNAME. */
2158 source_is_dst_backup (char const *srcbase
, struct stat
const *src_st
,
2159 int dst_dirfd
, char const *dst_relname
)
2161 size_t srcbaselen
= strlen (srcbase
);
2162 char const *dstbase
= last_component (dst_relname
);
2163 size_t dstbaselen
= strlen (dstbase
);
2164 size_t suffixlen
= strlen (simple_backup_suffix
);
2165 if (! (srcbaselen
== dstbaselen
+ suffixlen
2166 && memcmp (srcbase
, dstbase
, dstbaselen
) == 0
2167 && STREQ (srcbase
+ dstbaselen
, simple_backup_suffix
)))
2169 char *dst_back
= subst_suffix (dst_relname
,
2170 dst_relname
+ strlen (dst_relname
),
2171 simple_backup_suffix
);
2172 struct stat dst_back_sb
;
2173 int dst_back_status
= fstatat (dst_dirfd
, dst_back
, &dst_back_sb
, 0);
2175 return dst_back_status
== 0 && psame_inode (src_st
, &dst_back_sb
);
2178 /* Copy the file SRC_NAME to the file DST_NAME aka DST_DIRFD+DST_RELNAME.
2179 If NONEXISTENT_DST is positive, DST_NAME does not exist even as a
2180 dangling symlink; if negative, it does not exist except possibly
2181 as a dangling symlink; if zero, its existence status is unknown.
2182 A non-null PARENT describes the parent directory.
2183 ANCESTORS points to a linked, null terminated list of
2184 devices and inodes of parent directories of SRC_NAME.
2185 X summarizes the command-line options.
2186 COMMAND_LINE_ARG means SRC_NAME was specified on the command line.
2187 FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG is both input and output.
2188 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
2189 same as) DST_NAME; otherwise, clear it.
2190 If X->move_mode, set *RENAME_SUCCEEDED according to whether
2191 the source was simply renamed to the destination.
2192 Return true if successful. */
2194 copy_internal (char const *src_name
, char const *dst_name
,
2195 int dst_dirfd
, char const *dst_relname
,
2196 int nonexistent_dst
,
2197 struct stat
const *parent
,
2198 struct dir_list
*ancestors
,
2199 const struct cp_options
*x
,
2200 bool command_line_arg
,
2201 bool *first_dir_created_per_command_line_arg
,
2202 bool *copy_into_self
,
2203 bool *rename_succeeded
)
2207 mode_t src_mode
IF_LINT ( = 0);
2208 mode_t dst_mode
IF_LINT ( = 0);
2209 mode_t dst_mode_bits
;
2210 mode_t omitted_permissions
;
2211 bool restore_dst_mode
= false;
2212 char *earlier_file
= nullptr;
2213 char *dst_backup
= nullptr;
2214 char const *drelname
= *dst_relname
? dst_relname
: ".";
2216 bool copied_as_regular
= false;
2217 bool dest_is_symlink
= false;
2218 bool have_dst_lstat
= false;
2220 *copy_into_self
= false;
2222 int rename_errno
= x
->rename_errno
;
2225 if (rename_errno
< 0)
2226 rename_errno
= (renameatu (AT_FDCWD
, src_name
, dst_dirfd
, drelname
,
2229 nonexistent_dst
= *rename_succeeded
= rename_errno
== 0;
2232 if (rename_errno
== 0
2234 : rename_errno
!= EEXIST
2235 || (x
->interactive
!= I_ALWAYS_NO
&& x
->interactive
!= I_ALWAYS_SKIP
))
2237 char const *name
= rename_errno
== 0 ? dst_name
: src_name
;
2238 int dirfd
= rename_errno
== 0 ? dst_dirfd
: AT_FDCWD
;
2239 char const *relname
= rename_errno
== 0 ? drelname
: src_name
;
2241 = x
->dereference
== DEREF_NEVER
? AT_SYMLINK_NOFOLLOW
: 0;
2242 if (follow_fstatat (dirfd
, relname
, &src_sb
, fstatat_flags
) != 0)
2244 error (0, errno
, _("cannot stat %s"), quoteaf (name
));
2248 src_mode
= src_sb
.st_mode
;
2250 if (S_ISDIR (src_mode
) && !x
->recursive
)
2252 error (0, 0, ! x
->install_mode
/* cp */
2253 ? _("-r not specified; omitting directory %s")
2254 : _("omitting directory %s"),
2255 quoteaf (src_name
));
2261 #if defined lint && (defined __clang__ || defined __COVERITY__)
2262 affirm (x
->move_mode
);
2263 memset (&src_sb
, 0, sizeof src_sb
);
2267 /* Detect the case in which the same source file appears more than
2268 once on the command line and no backup option has been selected.
2269 If so, simply warn and don't copy it the second time.
2270 This check is enabled only if x->src_info is non-null. */
2271 if (command_line_arg
&& x
->src_info
)
2273 if ( ! S_ISDIR (src_mode
)
2274 && x
->backup_type
== no_backups
2275 && seen_file (x
->src_info
, src_name
, &src_sb
))
2277 error (0, 0, _("warning: source file %s specified more than once"),
2278 quoteaf (src_name
));
2282 record_file (x
->src_info
, src_name
, &src_sb
);
2285 bool dereference
= should_dereference (x
, command_line_arg
);
2287 /* Whether the destination is (or was) known to be new, updated as
2288 more info comes in. This may become true if the destination is a
2289 dangling symlink, in contexts where dangling symlinks should be
2290 treated the same as nonexistent files. */
2291 bool new_dst
= 0 < nonexistent_dst
;
2295 /* Normally, fill in DST_SB or set NEW_DST so that later code
2296 can use DST_SB if NEW_DST is false. However, don't bother
2297 doing this when rename_errno == EEXIST and X->interactive is
2298 I_ALWAYS_NO or I_ALWAYS_SKIP, something that can happen only
2299 with mv in which case x->update must be false which means
2300 that even if !NEW_DST the move will be abandoned without
2301 looking at DST_SB. */
2302 if (! (rename_errno
== EEXIST
2303 && (x
->interactive
== I_ALWAYS_NO
2304 || x
->interactive
== I_ALWAYS_SKIP
)))
2306 /* Regular files can be created by writing through symbolic
2307 links, but other files cannot. So use stat on the
2308 destination when copying a regular file, and lstat otherwise.
2309 However, if we intend to unlink or remove the destination
2310 first, use lstat, since a copy won't actually be made to the
2311 destination in that case. */
2313 = ((! S_ISREG (src_mode
)
2314 && (! x
->copy_as_regular
2315 || S_ISDIR (src_mode
) || S_ISLNK (src_mode
)))
2316 || x
->move_mode
|| x
->symbolic_link
|| x
->hard_link
2317 || x
->backup_type
!= no_backups
2318 || x
->unlink_dest_before_opening
);
2319 if (!use_lstat
&& nonexistent_dst
< 0)
2321 else if (0 <= follow_fstatat (dst_dirfd
, drelname
, &dst_sb
,
2322 use_lstat
? AT_SYMLINK_NOFOLLOW
: 0))
2324 have_dst_lstat
= use_lstat
;
2325 rename_errno
= EEXIST
;
2327 else if (errno
== ENOENT
)
2329 else if (errno
== ELOOP
&& !use_lstat
2330 && x
->unlink_dest_after_failed_open
)
2332 /* cp -f's destination might be a symlink loop.
2333 Leave new_dst=false so that we try to unlink later. */
2337 error (0, errno
, _("cannot stat %s"), quoteaf (dst_name
));
2342 if (rename_errno
== EEXIST
)
2344 bool return_now
= false;
2345 bool return_val
= true;
2346 bool skipped
= false;
2348 if ((x
->interactive
!= I_ALWAYS_NO
&& x
->interactive
!= I_ALWAYS_SKIP
)
2349 && ! same_file_ok (src_name
, &src_sb
, dst_dirfd
, drelname
,
2350 &dst_sb
, x
, &return_now
))
2352 error (0, 0, _("%s and %s are the same file"),
2353 quoteaf_n (0, src_name
), quoteaf_n (1, dst_name
));
2357 if (x
->update
&& !S_ISDIR (src_mode
))
2359 /* When preserving timestamps (but not moving within a file
2360 system), don't worry if the destination timestamp is
2361 less than the source merely because of timestamp
2363 int options
= ((x
->preserve_timestamps
2365 && dst_sb
.st_dev
== src_sb
.st_dev
))
2366 ? UTIMECMP_TRUNCATE_SOURCE
2369 if (0 <= utimecmpat (dst_dirfd
, dst_relname
, &dst_sb
,
2372 /* We're using --update and the destination is not older
2373 than the source, so do not copy or move. Pretend the
2374 rename succeeded, so the caller (if it's mv) doesn't
2375 end up removing the source file. */
2376 if (rename_succeeded
)
2377 *rename_succeeded
= true;
2379 /* However, we still must record that we've processed
2380 this src/dest pair, in case this source file is
2381 hard-linked to another one. In that case, we'll use
2382 the mapping information to link the corresponding
2383 destination names. */
2384 earlier_file
= remember_copied (dst_relname
, src_sb
.st_ino
,
2388 /* Note we currently replace DST_NAME unconditionally,
2389 even if it was a newer separate file. */
2390 if (! create_hard_link (nullptr, dst_dirfd
, earlier_file
,
2391 dst_name
, dst_dirfd
, dst_relname
,
2393 x
->verbose
, dereference
))
2404 /* When there is an existing destination file, we may end up
2405 returning early, and hence not copying/moving the file.
2406 This may be due to an interactive 'negative' reply to the
2407 prompt about the existing file. It may also be due to the
2408 use of the --no-clobber option.
2410 cp and mv treat -i and -f differently. */
2413 if (abandon_move (x
, dst_name
, dst_dirfd
, drelname
, &dst_sb
))
2415 /* Pretend the rename succeeded, so the caller (mv)
2416 doesn't end up removing the source file. */
2417 if (rename_succeeded
)
2418 *rename_succeeded
= true;
2421 return_val
= x
->interactive
== I_ALWAYS_SKIP
;
2426 if (! S_ISDIR (src_mode
)
2427 && (x
->interactive
== I_ALWAYS_NO
2428 || x
->interactive
== I_ALWAYS_SKIP
2429 || (x
->interactive
== I_ASK_USER
2430 && ! overwrite_ok (x
, dst_name
, dst_dirfd
,
2431 dst_relname
, &dst_sb
))))
2434 return_val
= x
->interactive
== I_ALWAYS_SKIP
;
2441 if (x
->interactive
== I_ALWAYS_NO
)
2442 error (0, 0, _("not replacing %s"), quoteaf (dst_name
));
2444 printf (_("skipped %s\n"), quoteaf (dst_name
));
2452 if (!S_ISDIR (dst_sb
.st_mode
))
2454 if (S_ISDIR (src_mode
))
2456 if (x
->move_mode
&& x
->backup_type
!= no_backups
)
2458 /* Moving a directory onto an existing
2459 non-directory is ok only with --backup. */
2464 _("cannot overwrite non-directory %s with directory %s"),
2465 quoteaf_n (0, dst_name
), quoteaf_n (1, src_name
));
2470 /* Don't let the user destroy their data, even if they try hard:
2471 This mv command must fail (likewise for cp):
2472 rm -rf a b c; mkdir a b c; touch a/f b/f; mv a/f b/f c
2473 Otherwise, the contents of b/f would be lost.
2474 In the case of 'cp', b/f would be lost if the user simulated
2475 a move using cp and rm.
2476 Note that it works fine if you use --backup=numbered. */
2477 if (command_line_arg
2478 && x
->backup_type
!= numbered_backups
2479 && seen_file (x
->dest_info
, dst_relname
, &dst_sb
))
2482 _("will not overwrite just-created %s with %s"),
2483 quoteaf_n (0, dst_name
), quoteaf_n (1, src_name
));
2488 if (!S_ISDIR (src_mode
))
2490 if (S_ISDIR (dst_sb
.st_mode
))
2492 if (x
->move_mode
&& x
->backup_type
!= no_backups
)
2494 /* Moving a non-directory onto an existing
2495 directory is ok only with --backup. */
2500 _("cannot overwrite directory %s with non-directory"),
2501 quoteaf (dst_name
));
2509 /* Don't allow user to move a directory onto a non-directory. */
2510 if (S_ISDIR (src_sb
.st_mode
) && !S_ISDIR (dst_sb
.st_mode
)
2511 && x
->backup_type
== no_backups
)
2514 _("cannot move directory onto non-directory: %s -> %s"),
2515 quotef_n (0, src_name
), quotef_n (0, dst_name
));
2520 char const *srcbase
;
2521 if (x
->backup_type
!= no_backups
2522 /* Don't try to back up a destination if the last
2523 component of src_name is "." or "..". */
2524 && ! dot_or_dotdot (srcbase
= last_component (src_name
))
2525 /* Create a backup of each destination directory in move mode,
2526 but not in copy mode. FIXME: it might make sense to add an
2527 option to suppress backup creation also for move mode.
2528 That would let one use mv to merge new content into an
2529 existing hierarchy. */
2530 && (x
->move_mode
|| ! S_ISDIR (dst_sb
.st_mode
)))
2532 /* Fail if creating the backup file would likely destroy
2533 the source file. Otherwise, the commands:
2534 cd /tmp; rm -f a a~; : > a; echo A > a~; cp --b=simple a~ a
2535 would leave two zero-length files: a and a~. */
2536 if (x
->backup_type
!= numbered_backups
2537 && source_is_dst_backup (srcbase
, &src_sb
,
2538 dst_dirfd
, dst_relname
))
2542 ? _("backing up %s might destroy source; %s not moved")
2543 : _("backing up %s might destroy source; %s not copied"));
2545 quoteaf_n (0, dst_name
),
2546 quoteaf_n (1, src_name
));
2550 char *tmp_backup
= backup_file_rename (dst_dirfd
, dst_relname
,
2554 Using alloca for a file name that may be arbitrarily
2555 long is not recommended. In fact, even forming such a name
2556 should be discouraged. Eventually, this code will be rewritten
2557 to use fts, so using alloca here will be less of a problem. */
2560 idx_t dirlen
= dst_relname
- dst_name
;
2561 idx_t backupsize
= strlen (tmp_backup
) + 1;
2562 dst_backup
= alloca (dirlen
+ backupsize
);
2563 memcpy (mempcpy (dst_backup
, dst_name
, dirlen
),
2564 tmp_backup
, backupsize
);
2567 else if (errno
!= ENOENT
)
2569 error (0, errno
, _("cannot backup %s"), quoteaf (dst_name
));
2574 else if (! S_ISDIR (dst_sb
.st_mode
)
2575 /* Never unlink dst_name when in move mode. */
2577 && (x
->unlink_dest_before_opening
2578 || (x
->data_copy_required
2579 && ((x
->preserve_links
&& 1 < dst_sb
.st_nlink
)
2580 || (x
->dereference
== DEREF_NEVER
2581 && ! S_ISREG (src_sb
.st_mode
))))
2584 if (unlinkat (dst_dirfd
, dst_relname
, 0) != 0 && errno
!= ENOENT
)
2586 error (0, errno
, _("cannot remove %s"), quoteaf (dst_name
));
2591 printf (_("removed %s\n"), quoteaf (dst_name
));
2596 /* Ensure we don't try to copy through a symlink that was
2597 created by a prior call to this function. */
2598 if (command_line_arg
2601 && x
->backup_type
== no_backups
)
2603 /* If we did not follow symlinks above, good: use that data.
2604 Otherwise, use AT_SYMLINK_NOFOLLOW, in case dst_name is a symlink. */
2605 struct stat tmp_buf
;
2606 struct stat
*dst_lstat_sb
2607 = (have_dst_lstat
? &dst_sb
2608 : fstatat (dst_dirfd
, drelname
, &tmp_buf
, AT_SYMLINK_NOFOLLOW
) < 0
2609 ? nullptr : &tmp_buf
);
2611 /* Never copy through a symlink we've just created. */
2613 && S_ISLNK (dst_lstat_sb
->st_mode
)
2614 && seen_file (x
->dest_info
, dst_relname
, dst_lstat_sb
))
2617 _("will not copy %s through just-created symlink %s"),
2618 quoteaf_n (0, src_name
), quoteaf_n (1, dst_name
));
2623 /* If the source is a directory, we don't always create the destination
2624 directory. So --verbose should not announce anything until we're
2625 sure we'll create a directory. Also don't announce yet when moving
2626 so we can distinguish renames versus copies. */
2627 if (x
->verbose
&& !x
->move_mode
&& !S_ISDIR (src_mode
))
2628 emit_verbose (src_name
, dst_name
, dst_backup
);
2630 /* Associate the destination file name with the source device and inode
2631 so that if we encounter a matching dev/ino pair in the source tree
2632 we can arrange to create a hard link between the corresponding names
2633 in the destination tree.
2635 When using the --link (-l) option, there is no need to take special
2636 measures, because (barring race conditions) files that are hard-linked
2637 in the source tree will also be hard-linked in the destination tree.
2639 Sometimes, when preserving links, we have to record dev/ino even
2640 though st_nlink == 1:
2641 - when in move_mode, since we may be moving a group of N hard-linked
2642 files (via two or more command line arguments) to a different
2643 partition; the links may be distributed among the command line
2644 arguments (possibly hierarchies) so that the link count of
2645 the final, once-linked source file is reduced to 1 when it is
2646 considered below. But in this case (for mv) we don't need to
2647 incur the expense of recording the dev/ino => name mapping; all we
2648 really need is a lookup, to see if the dev/ino pair has already
2650 - when using -H and processing a command line argument;
2651 that command line argument could be a symlink pointing to another
2652 command line argument. With 'cp -H --preserve=link', we hard-link
2653 those two destination files.
2654 - likewise for -L except that it applies to all files, not just
2655 command line arguments.
2657 Also, with --recursive, record dev/ino of each command-line directory.
2658 We'll use that info to detect this problem: cp -R dir dir. */
2660 if (rename_errno
== 0)
2661 earlier_file
= nullptr;
2662 else if (x
->recursive
&& S_ISDIR (src_mode
))
2664 if (command_line_arg
)
2665 earlier_file
= remember_copied (dst_relname
,
2666 src_sb
.st_ino
, src_sb
.st_dev
);
2668 earlier_file
= src_to_dest_lookup (src_sb
.st_ino
, src_sb
.st_dev
);
2670 else if (x
->move_mode
&& src_sb
.st_nlink
== 1)
2672 earlier_file
= src_to_dest_lookup (src_sb
.st_ino
, src_sb
.st_dev
);
2674 else if (x
->preserve_links
2676 && (1 < src_sb
.st_nlink
2677 || (command_line_arg
2678 && x
->dereference
== DEREF_COMMAND_LINE_ARGUMENTS
)
2679 || x
->dereference
== DEREF_ALWAYS
))
2681 earlier_file
= remember_copied (dst_relname
,
2682 src_sb
.st_ino
, src_sb
.st_dev
);
2685 /* Did we copy this inode somewhere else (in this command line argument)
2686 and therefore this is a second hard link to the inode? */
2690 /* Avoid damaging the destination file system by refusing to preserve
2691 hard-linked directories (which are found at least in Netapp snapshot
2693 if (S_ISDIR (src_mode
))
2695 /* If src_name and earlier_file refer to the same directory entry,
2696 then warn about copying a directory into itself. */
2697 if (same_nameat (AT_FDCWD
, src_name
, dst_dirfd
, earlier_file
))
2699 error (0, 0, _("cannot copy a directory, %s, into itself, %s"),
2700 quoteaf_n (0, top_level_src_name
),
2701 quoteaf_n (1, top_level_dst_name
));
2702 *copy_into_self
= true;
2705 else if (same_nameat (dst_dirfd
, dst_relname
,
2706 dst_dirfd
, earlier_file
))
2708 error (0, 0, _("warning: source directory %s "
2709 "specified more than once"),
2710 quoteaf (top_level_src_name
));
2711 /* In move mode, if a previous rename succeeded, then
2712 we won't be in this path as the source is missing. If the
2713 rename previously failed, then that has been handled, so
2714 pretend this attempt succeeded so the source isn't removed. */
2715 if (x
->move_mode
&& rename_succeeded
)
2716 *rename_succeeded
= true;
2717 /* We only do backups in move mode, and for non directories.
2718 So just ignore this repeated entry. */
2721 else if (x
->dereference
== DEREF_ALWAYS
2722 || (command_line_arg
2723 && x
->dereference
== DEREF_COMMAND_LINE_ARGUMENTS
))
2725 /* This happens when e.g., encountering a directory for the
2726 second or subsequent time via symlinks when cp is invoked
2727 with -R and -L. E.g.,
2728 rm -rf a b c d; mkdir a b c d; ln -s ../c a; ln -s ../c b;
2734 char *earlier
= subst_suffix (dst_name
, dst_relname
,
2736 error (0, 0, _("will not create hard link %s to directory %s"),
2737 quoteaf_n (0, dst_name
), quoteaf_n (1, earlier
));
2744 if (! create_hard_link (nullptr, dst_dirfd
, earlier_file
,
2745 dst_name
, dst_dirfd
, dst_relname
,
2746 true, x
->verbose
, dereference
))
2755 if (rename_errno
== EEXIST
)
2756 rename_errno
= (renameat (AT_FDCWD
, src_name
, dst_dirfd
, drelname
) == 0
2759 if (rename_errno
== 0)
2763 printf (_("renamed "));
2764 emit_verbose (src_name
, dst_name
, dst_backup
);
2767 if (x
->set_security_context
)
2769 /* -Z failures are only warnings currently. */
2770 (void) set_file_security_ctx (dst_name
, true, x
);
2773 if (rename_succeeded
)
2774 *rename_succeeded
= true;
2776 if (command_line_arg
&& !x
->last_file
)
2778 /* Record destination dev/ino/name, so that if we are asked
2779 to overwrite that file again, we can detect it and fail. */
2780 /* It's fine to use the _source_ stat buffer (src_sb) to get the
2781 _destination_ dev/ino, since the rename above can't have
2782 changed those, and 'mv' always uses lstat.
2783 We could limit it further by operating
2784 only on non-directories. */
2785 record_file (x
->dest_info
, dst_relname
, &src_sb
);
2791 /* FIXME: someday, consider what to do when moving a directory into
2792 itself but when source and destination are on different devices. */
2794 /* This happens when attempting to rename a directory to a
2795 subdirectory of itself. */
2796 if (rename_errno
== EINVAL
)
2798 /* FIXME: this is a little fragile in that it relies on rename(2)
2799 failing with a specific errno value. Expect problems on
2800 non-POSIX systems. */
2801 error (0, 0, _("cannot move %s to a subdirectory of itself, %s"),
2802 quoteaf_n (0, top_level_src_name
),
2803 quoteaf_n (1, top_level_dst_name
));
2805 /* Note that there is no need to call forget_created here,
2806 (compare with the other calls in this file) since the
2807 destination directory didn't exist before. */
2809 *copy_into_self
= true;
2810 /* FIXME-cleanup: Don't return true here; adjust mv.c accordingly.
2811 The only caller that uses this code (mv.c) ends up setting its
2812 exit status to nonzero when copy_into_self is nonzero. */
2816 /* WARNING: there probably exist systems for which an inter-device
2817 rename fails with a value of errno not handled here.
2818 If/as those are reported, add them to the condition below.
2819 If this happens to you, please do the following and send the output
2820 to the bug-reporting address (e.g., in the output of cp --help):
2821 touch k; perl -e 'rename "k","/tmp/k" or print "$!(",$!+0,")\n"'
2822 where your current directory is on one partition and /tmp is the other.
2823 Also, please try to find the E* errno macro name corresponding to
2824 the diagnostic and parenthesized integer, and include that in your
2825 e-mail. One way to do that is to run a command like this
2826 find /usr/include/. -type f \
2827 | xargs grep 'define.*\<E[A-Z]*\>.*\<18\>' /dev/null
2828 where you'd replace '18' with the integer in parentheses that
2829 was output from the perl one-liner above.
2830 If necessary, of course, change '/tmp' to some other directory. */
2831 if (rename_errno
!= EXDEV
|| x
->no_copy
)
2833 /* There are many ways this can happen due to a race condition.
2834 When something happens between the initial follow_fstatat and the
2835 subsequent rename, we can get many different types of errors.
2836 For example, if the destination is initially a non-directory
2837 or non-existent, but it is created as a directory, the rename
2838 fails. If two 'mv' commands try to rename the same file at
2839 about the same time, one will succeed and the other will fail.
2840 If the permissions on the directory containing the source or
2841 destination file are made too restrictive, the rename will
2843 char const *quoted_dst_name
= quoteaf_n (1, dst_name
);
2844 switch (rename_errno
)
2846 case EDQUOT
: case EEXIST
: case EISDIR
: case EMLINK
:
2847 case ENOSPC
: case ETXTBSY
:
2848 #if ENOTEMPTY != EEXIST
2851 /* The destination must be the problem. Don't mention
2852 the source as that is more likely to confuse the user
2854 error (0, rename_errno
, _("cannot overwrite %s"),
2859 error (0, rename_errno
, _("cannot move %s to %s"),
2860 quoteaf_n (0, src_name
), quoted_dst_name
);
2863 forget_created (src_sb
.st_ino
, src_sb
.st_dev
);
2867 /* The rename attempt has failed. Remove any existing destination
2868 file so that a cross-device 'mv' acts as if it were really using
2869 the rename syscall. Note both src and dst must both be directories
2870 or not, and this is enforced above. Therefore we check the src_mode
2871 and operate on dst_name here as a tighter constraint and also because
2872 src_mode is readily available here. */
2873 if ((unlinkat (dst_dirfd
, drelname
,
2874 S_ISDIR (src_mode
) ? AT_REMOVEDIR
: 0)
2879 _("inter-device move failed: %s to %s; unable to remove target"),
2880 quoteaf_n (0, src_name
), quoteaf_n (1, dst_name
));
2881 forget_created (src_sb
.st_ino
, src_sb
.st_dev
);
2885 if (x
->verbose
&& !S_ISDIR (src_mode
))
2887 printf (_("copied "));
2888 emit_verbose (src_name
, dst_name
, dst_backup
);
2893 /* If the ownership might change, or if it is a directory (whose
2894 special mode bits may change after the directory is created),
2895 omit some permissions at first, so unauthorized users cannot nip
2896 in before the file is ready. */
2897 dst_mode_bits
= (x
->set_mode
? x
->mode
: src_mode
) & CHMOD_MODE_BITS
;
2898 omitted_permissions
=
2900 & (x
->preserve_ownership
? S_IRWXG
| S_IRWXO
2901 : S_ISDIR (src_mode
) ? S_IWGRP
| S_IWOTH
2906 /* If required, set the default security context for new files.
2907 Also for existing files this is used as a reference
2908 when copying the context with --preserve=context.
2909 FIXME: Do we need to consider dst_mode_bits here? */
2910 if (! set_process_security_ctx (src_name
, dst_name
, src_mode
, new_dst
, x
))
2913 if (S_ISDIR (src_mode
))
2915 struct dir_list
*dir
;
2917 /* If this directory has been copied before during the
2918 recursion, there is a symbolic link to an ancestor
2919 directory of the symbolic link. It is impossible to
2920 continue to copy this, unless we've got an infinite file system. */
2922 if (is_ancestor (&src_sb
, ancestors
))
2924 error (0, 0, _("cannot copy cyclic symbolic link %s"),
2925 quoteaf (src_name
));
2929 /* Insert the current directory in the list of parents. */
2931 dir
= alloca (sizeof *dir
);
2932 dir
->parent
= ancestors
;
2933 dir
->ino
= src_sb
.st_ino
;
2934 dir
->dev
= src_sb
.st_dev
;
2936 if (new_dst
|| !S_ISDIR (dst_sb
.st_mode
))
2938 /* POSIX says mkdir's behavior is implementation-defined when
2939 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
2940 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
2941 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
2942 mode_t mode
= dst_mode_bits
& ~omitted_permissions
;
2943 if (mkdirat (dst_dirfd
, drelname
, mode
) != 0)
2945 error (0, errno
, _("cannot create directory %s"),
2946 quoteaf (dst_name
));
2950 /* We need search and write permissions to the new directory
2951 for writing the directory's contents. Check if these
2952 permissions are there. */
2954 if (fstatat (dst_dirfd
, drelname
, &dst_sb
, AT_SYMLINK_NOFOLLOW
) != 0)
2956 error (0, errno
, _("cannot stat %s"), quoteaf (dst_name
));
2959 else if ((dst_sb
.st_mode
& S_IRWXU
) != S_IRWXU
)
2961 /* Make the new directory searchable and writable. */
2963 dst_mode
= dst_sb
.st_mode
;
2964 restore_dst_mode
= true;
2966 if (lchmodat (dst_dirfd
, drelname
, dst_mode
| S_IRWXU
) != 0)
2968 error (0, errno
, _("setting permissions for %s"),
2969 quoteaf (dst_name
));
2974 /* Record the created directory's inode and device numbers into
2975 the search structure, so that we can avoid copying it again.
2976 Do this only for the first directory that is created for each
2977 source command line argument. */
2978 if (!*first_dir_created_per_command_line_arg
)
2980 remember_copied (dst_relname
, dst_sb
.st_ino
, dst_sb
.st_dev
);
2981 *first_dir_created_per_command_line_arg
= true;
2987 printf (_("created directory %s\n"), quoteaf (dst_name
));
2989 emit_verbose (src_name
, dst_name
, nullptr);
2994 omitted_permissions
= 0;
2996 /* For directories, the process global context could be reset for
2997 descendants, so use it to set the context for existing dirs here.
2998 This will also give earlier indication of failure to set ctx. */
2999 if (x
->set_security_context
|| x
->preserve_security_context
)
3000 if (! set_file_security_ctx (dst_name
, false, x
))
3002 if (x
->require_preserve_context
)
3007 /* Decide whether to copy the contents of the directory. */
3008 if (x
->one_file_system
&& parent
&& parent
->st_dev
!= src_sb
.st_dev
)
3010 /* Here, we are crossing a file system boundary and cp's -x option
3011 is in effect: so don't copy the contents of this directory. */
3015 /* Copy the contents of the directory. Don't just return if
3016 this fails -- otherwise, the failure to read a single file
3017 in a source directory would cause the containing destination
3018 directory not to have owner/perms set properly. */
3019 delayed_ok
= copy_dir (src_name
, dst_name
, dst_dirfd
, dst_relname
,
3020 new_dst
, &src_sb
, dir
, x
,
3021 first_dir_created_per_command_line_arg
,
3025 else if (x
->symbolic_link
)
3027 dest_is_symlink
= true;
3028 if (*src_name
!= '/')
3030 /* Check that DST_NAME denotes a file in the current directory. */
3032 struct stat dst_parent_sb
;
3034 bool in_current_dir
;
3036 dst_parent
= dir_name (dst_relname
);
3038 in_current_dir
= ((dst_dirfd
== AT_FDCWD
&& STREQ (".", dst_parent
))
3039 /* If either stat call fails, it's ok not to report
3040 the failure and say dst_name is in the current
3041 directory. Other things will fail later. */
3042 || stat (".", &dot_sb
) != 0
3043 || (fstatat (dst_dirfd
, dst_parent
, &dst_parent_sb
,
3045 || psame_inode (&dot_sb
, &dst_parent_sb
));
3048 if (! in_current_dir
)
3051 _("%s: can make relative symbolic links only in current directory"),
3057 int err
= force_symlinkat (src_name
, dst_dirfd
, dst_relname
,
3058 x
->unlink_dest_after_failed_open
, -1);
3061 error (0, err
, _("cannot create symbolic link %s to %s"),
3062 quoteaf_n (0, dst_name
), quoteaf_n (1, src_name
));
3067 /* POSIX 2008 states that it is implementation-defined whether
3068 link() on a symlink creates a hard-link to the symlink, or only
3069 to the referent (effectively dereferencing the symlink) (POSIX
3070 2001 required the latter behavior, although many systems provided
3071 the former). Yet cp, invoked with '--link --no-dereference',
3072 should not follow the link. We can approximate the desired
3073 behavior by skipping this hard-link creating block and instead
3074 copying the symlink, via the 'S_ISLNK'- copying code below.
3076 Note gnulib's linkat module, guarantees that the symlink is not
3077 dereferenced. However its emulation currently doesn't maintain
3078 timestamps or ownership so we only call it when we know the
3079 emulation will not be needed. */
3080 else if (x
->hard_link
3081 && !(! CAN_HARDLINK_SYMLINKS
&& S_ISLNK (src_mode
)
3082 && x
->dereference
== DEREF_NEVER
))
3084 bool replace
= (x
->unlink_dest_after_failed_open
3085 || x
->interactive
== I_ASK_USER
);
3086 if (! create_hard_link (src_name
, AT_FDCWD
, src_name
,
3087 dst_name
, dst_dirfd
, dst_relname
,
3088 replace
, false, dereference
))
3091 else if (S_ISREG (src_mode
)
3092 || (x
->copy_as_regular
&& !S_ISLNK (src_mode
)))
3094 copied_as_regular
= true;
3095 /* POSIX says the permission bits of the source file must be
3096 used as the 3rd argument in the open call. Historical
3097 practice passed all the source mode bits to 'open', but the extra
3098 bits were ignored, so it should be the same either way.
3100 This call uses DST_MODE_BITS, not SRC_MODE. These are
3101 normally the same, and the exception (where x->set_mode) is
3102 used only by 'install', which POSIX does not specify and
3103 where DST_MODE_BITS is what's wanted. */
3104 if (! copy_reg (src_name
, dst_name
, dst_dirfd
, dst_relname
,
3105 x
, dst_mode_bits
& S_IRWXUGO
,
3106 omitted_permissions
, &new_dst
, &src_sb
))
3109 else if (S_ISFIFO (src_mode
))
3111 /* Use mknodat, rather than mkfifoat, because the former preserves
3112 the special mode bits of a fifo on Solaris 10, while mkfifoat
3113 does not. But fall back on mkfifoat, because on some BSD systems,
3114 mknodat always fails when asked to create a FIFO. */
3115 mode_t mode
= src_mode
& ~omitted_permissions
;
3116 if (mknodat (dst_dirfd
, dst_relname
, mode
, 0) != 0)
3117 if (mkfifoat (dst_dirfd
, dst_relname
, mode
& ~S_IFIFO
) != 0)
3119 error (0, errno
, _("cannot create fifo %s"), quoteaf (dst_name
));
3123 else if (S_ISBLK (src_mode
) || S_ISCHR (src_mode
) || S_ISSOCK (src_mode
))
3125 mode_t mode
= src_mode
& ~omitted_permissions
;
3126 if (mknodat (dst_dirfd
, dst_relname
, mode
, src_sb
.st_rdev
) != 0)
3128 error (0, errno
, _("cannot create special file %s"),
3129 quoteaf (dst_name
));
3133 else if (S_ISLNK (src_mode
))
3135 char *src_link_val
= areadlink_with_size (src_name
, src_sb
.st_size
);
3136 dest_is_symlink
= true;
3137 if (src_link_val
== nullptr)
3139 error (0, errno
, _("cannot read symbolic link %s"),
3140 quoteaf (src_name
));
3144 int symlink_err
= force_symlinkat (src_link_val
, dst_dirfd
, dst_relname
,
3145 x
->unlink_dest_after_failed_open
, -1);
3146 if (0 < symlink_err
&& x
->update
&& !new_dst
&& S_ISLNK (dst_sb
.st_mode
)
3147 && dst_sb
.st_size
== strlen (src_link_val
))
3149 /* See if the destination is already the desired symlink.
3150 FIXME: This behavior isn't documented, and seems wrong
3151 in some cases, e.g., if the destination symlink has the
3152 wrong ownership, permissions, or timestamps. */
3153 char *dest_link_val
=
3154 areadlinkat_with_size (dst_dirfd
, dst_relname
, dst_sb
.st_size
);
3157 if (STREQ (dest_link_val
, src_link_val
))
3159 free (dest_link_val
);
3162 free (src_link_val
);
3163 if (0 < symlink_err
)
3165 error (0, symlink_err
, _("cannot create symbolic link %s"),
3166 quoteaf (dst_name
));
3170 if (x
->preserve_security_context
)
3171 restore_default_fscreatecon_or_die ();
3173 if (x
->preserve_ownership
)
3175 /* Preserve the owner and group of the just-'copied'
3176 symbolic link, if possible. */
3178 && (lchownat (dst_dirfd
, dst_relname
,
3179 src_sb
.st_uid
, src_sb
.st_gid
)
3181 && ! chown_failure_ok (x
))
3183 error (0, errno
, _("failed to preserve ownership for %s"),
3185 if (x
->require_preserve
)
3190 /* Can't preserve ownership of symlinks.
3191 FIXME: maybe give a warning or even error for symlinks
3192 in directories with the sticky bit set -- there, not
3193 preserving owner/group is a potential security problem. */
3199 error (0, 0, _("%s has unknown file type"), quoteaf (src_name
));
3203 /* With -Z or --preserve=context, set the context for existing files.
3204 Note this is done already for copy_reg() for reasons described therein. */
3205 if (!new_dst
&& !x
->copy_as_regular
&& !S_ISDIR (src_mode
)
3206 && (x
->set_security_context
|| x
->preserve_security_context
))
3208 if (! set_file_security_ctx (dst_name
, false, x
))
3210 if (x
->require_preserve_context
)
3215 if (command_line_arg
&& x
->dest_info
)
3217 /* Now that the destination file is very likely to exist,
3218 add its info to the set. */
3220 if (fstatat (dst_dirfd
, drelname
, &sb
, AT_SYMLINK_NOFOLLOW
) == 0)
3221 record_file (x
->dest_info
, dst_relname
, &sb
);
3224 /* If we've just created a hard-link due to cp's --link option,
3226 if (x
->hard_link
&& ! S_ISDIR (src_mode
)
3227 && !(! CAN_HARDLINK_SYMLINKS
&& S_ISLNK (src_mode
)
3228 && x
->dereference
== DEREF_NEVER
))
3231 if (copied_as_regular
)
3234 /* POSIX says that 'cp -p' must restore the following:
3236 - setuid, setgid bits
3238 If it fails to restore any of those, we may give a warning but
3239 the destination must not be removed.
3240 FIXME: implement the above. */
3242 /* Adjust the times (and if possible, ownership) for the copy.
3243 chown turns off set[ug]id bits for non-root,
3244 so do the chmod last. */
3246 if (x
->preserve_timestamps
)
3248 struct timespec timespec
[2];
3249 timespec
[0] = get_stat_atime (&src_sb
);
3250 timespec
[1] = get_stat_mtime (&src_sb
);
3252 int utimensat_flags
= dest_is_symlink
? AT_SYMLINK_NOFOLLOW
: 0;
3253 if (utimensat (dst_dirfd
, drelname
, timespec
, utimensat_flags
) != 0)
3255 error (0, errno
, _("preserving times for %s"), quoteaf (dst_name
));
3256 if (x
->require_preserve
)
3261 /* Avoid calling chown if we know it's not necessary. */
3262 if (!dest_is_symlink
&& x
->preserve_ownership
3263 && (new_dst
|| !SAME_OWNER_AND_GROUP (src_sb
, dst_sb
)))
3265 switch (set_owner (x
, dst_name
, dst_dirfd
, drelname
, -1,
3266 &src_sb
, new_dst
, &dst_sb
))
3272 src_mode
&= ~ (S_ISUID
| S_ISGID
| S_ISVTX
);
3277 /* Set xattrs after ownership as changing owners will clear capabilities. */
3278 if (x
->preserve_xattr
&& ! copy_attr (src_name
, -1, dst_name
, -1, x
)
3279 && x
->require_preserve_xattr
)
3282 /* The operations beyond this point may dereference a symlink. */
3283 if (dest_is_symlink
)
3286 set_author (dst_name
, -1, &src_sb
);
3288 if (x
->preserve_mode
|| x
->move_mode
)
3290 if (copy_acl (src_name
, -1, dst_name
, -1, src_mode
) != 0
3291 && x
->require_preserve
)
3294 else if (x
->set_mode
)
3296 if (set_acl (dst_name
, -1, x
->mode
) != 0)
3299 else if (x
->explicit_no_preserve_mode
&& new_dst
)
3301 int default_permissions
= S_ISDIR (src_mode
) || S_ISSOCK (src_mode
)
3302 ? S_IRWXUGO
: MODE_RW_UGO
;
3303 if (set_acl (dst_name
, -1, default_permissions
& ~cached_umask ()) != 0)
3308 if (omitted_permissions
)
3310 omitted_permissions
&= ~ cached_umask ();
3312 if (omitted_permissions
&& !restore_dst_mode
)
3314 /* Permissions were deliberately omitted when the file
3315 was created due to security concerns. See whether
3316 they need to be re-added now. It'd be faster to omit
3317 the lstat, but deducing the current destination mode
3318 is tricky in the presence of implementation-defined
3319 rules for special mode bits. */
3320 if (new_dst
&& (fstatat (dst_dirfd
, drelname
, &dst_sb
,
3321 AT_SYMLINK_NOFOLLOW
)
3324 error (0, errno
, _("cannot stat %s"), quoteaf (dst_name
));
3327 dst_mode
= dst_sb
.st_mode
;
3328 if (omitted_permissions
& ~dst_mode
)
3329 restore_dst_mode
= true;
3333 if (restore_dst_mode
)
3335 if (lchmodat (dst_dirfd
, drelname
, dst_mode
| omitted_permissions
)
3338 error (0, errno
, _("preserving permissions for %s"),
3339 quoteaf (dst_name
));
3340 if (x
->require_preserve
)
3350 if (x
->preserve_security_context
)
3351 restore_default_fscreatecon_or_die ();
3353 /* We have failed to create the destination file.
3354 If we've just added a dev/ino entry via the remember_copied
3355 call above (i.e., unless we've just failed to create a hard link),
3356 remove the entry associating the source dev/ino with the
3357 destination file name, so we don't try to 'preserve' a link
3358 to a file we didn't create. */
3359 if (earlier_file
== nullptr)
3360 forget_created (src_sb
.st_ino
, src_sb
.st_dev
);
3364 char const *dst_relbackup
= &dst_backup
[dst_relname
- dst_name
];
3365 if (renameat (dst_dirfd
, dst_relbackup
, dst_dirfd
, drelname
) != 0)
3366 error (0, errno
, _("cannot un-backup %s"), quoteaf (dst_name
));
3370 printf (_("%s -> %s (unbackup)\n"),
3371 quoteaf_n (0, dst_backup
), quoteaf_n (1, dst_name
));
3378 valid_options (const struct cp_options
*co
)
3380 affirm (VALID_BACKUP_TYPE (co
->backup_type
));
3381 affirm (VALID_SPARSE_MODE (co
->sparse_mode
));
3382 affirm (VALID_REFLINK_MODE (co
->reflink_mode
));
3383 affirm (!(co
->hard_link
&& co
->symbolic_link
));
3385 (co
->reflink_mode
== REFLINK_ALWAYS
3386 && co
->sparse_mode
!= SPARSE_AUTO
));
3389 /* Copy the file SRC_NAME to the file DST_NAME aka DST_DIRFD+DST_RELNAME.
3390 If NONEXISTENT_DST is positive, DST_NAME does not exist even as a
3391 dangling symlink; if negative, it does not exist except possibly
3392 as a dangling symlink; if zero, its existence status is unknown.
3393 OPTIONS summarizes the command-line options.
3394 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
3395 same as) DST_NAME; otherwise, set clear it.
3396 If X->move_mode, set *RENAME_SUCCEEDED according to whether
3397 the source was simply renamed to the destination.
3398 Return true if successful. */
3401 copy (char const *src_name
, char const *dst_name
,
3402 int dst_dirfd
, char const *dst_relname
,
3403 int nonexistent_dst
, const struct cp_options
*options
,
3404 bool *copy_into_self
, bool *rename_succeeded
)
3406 valid_options (options
);
3408 /* Record the file names: they're used in case of error, when copying
3409 a directory into itself. I don't like to make these tools do *any*
3410 extra work in the common case when that work is solely to handle
3411 exceptional cases, but in this case, I don't see a way to derive the
3412 top level source and destination directory names where they're used.
3413 An alternative is to use COPY_INTO_SELF and print the diagnostic
3414 from every caller -- but I don't want to do that. */
3415 top_level_src_name
= src_name
;
3416 top_level_dst_name
= dst_name
;
3418 bool first_dir_created_per_command_line_arg
= false;
3419 return copy_internal (src_name
, dst_name
, dst_dirfd
, dst_relname
,
3420 nonexistent_dst
, nullptr, nullptr,
3422 &first_dir_created_per_command_line_arg
,
3423 copy_into_self
, rename_succeeded
);
3426 /* Set *X to the default options for a value of type struct cp_options. */
3429 cp_options_default (struct cp_options
*x
)
3431 memset (x
, 0, sizeof *x
);
3432 #ifdef PRIV_FILE_CHOWN
3434 priv_set_t
*pset
= priv_allocset ();
3437 if (getppriv (PRIV_EFFECTIVE
, pset
) == 0)
3439 x
->chown_privileges
= priv_ismember (pset
, PRIV_FILE_CHOWN
);
3440 x
->owner_privileges
= priv_ismember (pset
, PRIV_FILE_OWNER
);
3442 priv_freeset (pset
);
3445 x
->chown_privileges
= x
->owner_privileges
= (geteuid () == ROOT_UID
);
3447 x
->rename_errno
= -1;
3450 /* Return true if it's OK for chown to fail, where errno is
3451 the error number that chown failed with and X is the copying
3455 chown_failure_ok (struct cp_options
const *x
)
3457 /* If non-root uses -p, it's ok if we can't preserve ownership.
3458 But root probably wants to know, e.g. if NFS disallows it,
3459 or if the target system doesn't support file ownership.
3461 Treat EACCES like EPERM and EINVAL to work around a bug in Linux
3462 CIFS <https://bugs.gnu.org/65599>. Although this means coreutils
3463 will ignore EACCES errors that it should report, problems should
3464 occur only when some other process is racing with coreutils and
3465 coreutils is not immune to races anyway. */
3467 return ((errno
== EPERM
|| errno
== EINVAL
|| errno
== EACCES
)
3468 && !x
->chown_privileges
);
3471 /* Similarly, return true if it's OK for chmod and similar operations
3472 to fail, where errno is the error number that chmod failed with and
3473 X is the copying option set. */
3476 owner_failure_ok (struct cp_options
const *x
)
3478 return ((errno
== EPERM
|| errno
== EINVAL
|| errno
== EACCES
)
3479 && !x
->owner_privileges
);
3482 /* Return the user's umask, caching the result.
3484 FIXME: If the destination's parent directory has has a default ACL,
3485 some operating systems (e.g., GNU/Linux's "POSIX" ACLs) use that
3486 ACL's mask rather than the process umask. Currently, the callers
3487 of cached_umask incorrectly assume that this situation cannot occur. */
3491 static mode_t mask
= (mode_t
) -1;
3492 if (mask
== (mode_t
) -1)