dd: output final progress before syncing
[coreutils.git] / src / copy.c
blob4a7d9b5d9cbc7e4b96f3682d45bb13f2856ead75
1 /* copy.c -- core functions for copying files and directories
2 Copyright (C) 1989-2022 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
17 /* Extracted from cp.c and librarified by Jim Meyering. */
19 #include <config.h>
20 #include <stdio.h>
21 #include <assert.h>
22 #include <sys/ioctl.h>
23 #include <sys/types.h>
24 #include <selinux/selinux.h>
26 #if HAVE_HURD_H
27 # include <hurd.h>
28 #endif
29 #if HAVE_PRIV_H
30 # include <priv.h>
31 #endif
33 #include "system.h"
34 #include "acl.h"
35 #include "alignalloc.h"
36 #include "backupfile.h"
37 #include "buffer-lcm.h"
38 #include "canonicalize.h"
39 #include "copy.h"
40 #include "cp-hash.h"
41 #include "die.h"
42 #include "error.h"
43 #include "fadvise.h"
44 #include "fcntl--.h"
45 #include "file-set.h"
46 #include "filemode.h"
47 #include "filenamecat.h"
48 #include "force-link.h"
49 #include "full-write.h"
50 #include "hash.h"
51 #include "hash-triple.h"
52 #include "ignore-value.h"
53 #include "ioblksize.h"
54 #include "quote.h"
55 #include "renameatu.h"
56 #include "root-uid.h"
57 #include "same.h"
58 #include "savedir.h"
59 #include "stat-size.h"
60 #include "stat-time.h"
61 #include "utimecmp.h"
62 #include "utimens.h"
63 #include "write-any-file.h"
64 #include "areadlink.h"
65 #include "yesno.h"
66 #include "selinux.h"
68 #ifndef USE_XATTR
69 # define USE_XATTR false
70 #endif
72 #if USE_XATTR
73 # include <attr/error_context.h>
74 # include <attr/libattr.h>
75 # include <stdarg.h>
76 # include "verror.h"
77 #endif
79 #if HAVE_LINUX_FALLOC_H
80 # include <linux/falloc.h>
81 #endif
83 /* See HAVE_FALLOCATE workaround when including this file. */
84 #ifdef HAVE_LINUX_FS_H
85 # include <linux/fs.h>
86 #endif
88 #if !defined FICLONE && defined __linux__
89 # define FICLONE _IOW (0x94, 9, int)
90 #endif
92 #if HAVE_FCLONEFILEAT && !USE_XATTR
93 # include <sys/clonefile.h>
94 #endif
96 #ifndef HAVE_FCHOWN
97 # define HAVE_FCHOWN false
98 # define fchown(fd, uid, gid) (-1)
99 #endif
101 #ifndef USE_ACL
102 # define USE_ACL 0
103 #endif
105 #define SAME_OWNER(A, B) ((A).st_uid == (B).st_uid)
106 #define SAME_GROUP(A, B) ((A).st_gid == (B).st_gid)
107 #define SAME_OWNER_AND_GROUP(A, B) (SAME_OWNER (A, B) && SAME_GROUP (A, B))
109 /* LINK_FOLLOWS_SYMLINKS is tri-state; if it is -1, we don't know
110 how link() behaves, so assume we can't hardlink symlinks in that case. */
111 #if (defined HAVE_LINKAT && ! LINKAT_SYMLINK_NOTSUP) || ! LINK_FOLLOWS_SYMLINKS
112 # define CAN_HARDLINK_SYMLINKS 1
113 #else
114 # define CAN_HARDLINK_SYMLINKS 0
115 #endif
117 struct dir_list
119 struct dir_list *parent;
120 ino_t ino;
121 dev_t dev;
124 /* Initial size of the cp.dest_info hash table. */
125 #define DEST_INFO_INITIAL_CAPACITY 61
127 static bool copy_internal (char const *src_name, char const *dst_name,
128 int dst_dirfd, char const *dst_relname,
129 int nonexistent_dst, struct stat const *parent,
130 struct dir_list *ancestors,
131 const struct cp_options *x,
132 bool command_line_arg,
133 bool *first_dir_created_per_command_line_arg,
134 bool *copy_into_self,
135 bool *rename_succeeded);
136 static bool owner_failure_ok (struct cp_options const *x);
138 /* Pointers to the file names: they're used in the diagnostic that is issued
139 when we detect the user is trying to copy a directory into itself. */
140 static char const *top_level_src_name;
141 static char const *top_level_dst_name;
143 #ifndef DEV_FD_MIGHT_BE_CHR
144 # define DEV_FD_MIGHT_BE_CHR false
145 #endif
147 /* Act like fstat (DIRFD, FILENAME, ST, FLAGS), except when following
148 symbolic links on Solaris-like systems, treat any character-special
149 device like /dev/fd/0 as if it were the file it is open on. */
150 static int
151 follow_fstatat (int dirfd, char const *filename, struct stat *st, int flags)
153 int result = fstatat (dirfd, filename, st, flags);
155 if (DEV_FD_MIGHT_BE_CHR && result == 0 && !(flags & AT_SYMLINK_NOFOLLOW)
156 && S_ISCHR (st->st_mode))
158 static dev_t stdin_rdev;
159 static signed char stdin_rdev_status;
160 if (stdin_rdev_status == 0)
162 struct stat stdin_st;
163 if (stat ("/dev/stdin", &stdin_st) == 0 && S_ISCHR (stdin_st.st_mode)
164 && minor (stdin_st.st_rdev) == STDIN_FILENO)
166 stdin_rdev = stdin_st.st_rdev;
167 stdin_rdev_status = 1;
169 else
170 stdin_rdev_status = -1;
172 if (0 < stdin_rdev_status && major (stdin_rdev) == major (st->st_rdev))
173 result = fstat (minor (st->st_rdev), st);
176 return result;
179 /* Attempt to punch a hole to avoid any permanent
180 speculative preallocation on file systems such as XFS.
181 Return values as per fallocate(2) except ENOSYS etc. are ignored. */
183 static int
184 punch_hole (int fd, off_t offset, off_t length)
186 int ret = 0;
187 /* +0 is to work around older <linux/fs.h> defining HAVE_FALLOCATE to empty. */
188 #if HAVE_FALLOCATE + 0
189 # if defined FALLOC_FL_PUNCH_HOLE && defined FALLOC_FL_KEEP_SIZE
190 ret = fallocate (fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
191 offset, length);
192 if (ret < 0 && (is_ENOTSUP (errno) || errno == ENOSYS))
193 ret = 0;
194 # endif
195 #endif
196 return ret;
199 /* Create a hole at the end of a file,
200 avoiding preallocation if requested. */
202 static bool
203 create_hole (int fd, char const *name, bool punch_holes, off_t size)
205 off_t file_end = lseek (fd, size, SEEK_CUR);
207 if (file_end < 0)
209 error (0, errno, _("cannot lseek %s"), quoteaf (name));
210 return false;
213 /* Some file systems (like XFS) preallocate when write extending a file.
214 I.e., a previous write() may have preallocated extra space
215 that the seek above will not discard. A subsequent write() could
216 then make this allocation permanent. */
217 if (punch_holes && punch_hole (fd, file_end - size, size) < 0)
219 error (0, errno, _("error deallocating %s"), quoteaf (name));
220 return false;
223 return true;
227 /* Copy the regular file open on SRC_FD/SRC_NAME to DST_FD/DST_NAME,
228 honoring the MAKE_HOLES setting and using the BUF_SIZE-byte buffer
229 BUF for temporary storage. Copy no more than MAX_N_READ bytes.
230 Return true upon successful completion;
231 print a diagnostic and return false upon error.
232 Note that for best results, BUF should be "well"-aligned.
233 Set *LAST_WRITE_MADE_HOLE to true if the final operation on
234 DEST_FD introduced a hole. Set *TOTAL_N_READ to the number of
235 bytes read. */
236 static bool
237 sparse_copy (int src_fd, int dest_fd, char *buf, size_t buf_size,
238 size_t hole_size, bool punch_holes, bool allow_reflink,
239 char const *src_name, char const *dst_name,
240 uintmax_t max_n_read, off_t *total_n_read,
241 bool *last_write_made_hole)
243 *last_write_made_hole = false;
244 *total_n_read = 0;
246 /* If not looking for holes, use copy_file_range if functional,
247 but don't use if reflink disallowed as that may be implicit. */
248 if (!hole_size && allow_reflink)
249 while (max_n_read)
251 /* Copy at most COPY_MAX bytes at a time; this is min
252 (SSIZE_MAX, SIZE_MAX) truncated to a value that is
253 surely aligned well. */
254 ssize_t copy_max = MIN (SSIZE_MAX, SIZE_MAX) >> 30 << 30;
255 ssize_t n_copied = copy_file_range (src_fd, NULL, dest_fd, NULL,
256 MIN (max_n_read, copy_max), 0);
257 if (n_copied == 0)
259 /* copy_file_range incorrectly returns 0 when reading from
260 the proc file system on the Linux kernel through at
261 least 5.6.19 (2020), so fall back on 'read' if the
262 input file seems empty. */
263 if (*total_n_read == 0)
264 break;
265 return true;
267 if (n_copied < 0)
269 if (errno == ENOSYS || is_ENOTSUP (errno)
270 || errno == EINVAL || errno == EBADF
271 || errno == EXDEV || errno == ETXTBSY)
272 break;
274 /* copy_file_range might not be enabled in seccomp filters,
275 so retry with a standard copy. EPERM can also occur
276 for immutable files, but that would only be in the edge case
277 where the file is made immutable after creating/truncating,
278 in which case the (more accurate) error is still shown. */
279 if (errno == EPERM && *total_n_read == 0)
280 break;
282 if (errno == EINTR)
283 n_copied = 0;
284 else
286 error (0, errno, _("error copying %s to %s"),
287 quoteaf_n (0, src_name), quoteaf_n (1, dst_name));
288 return false;
291 max_n_read -= n_copied;
292 *total_n_read += n_copied;
295 bool make_hole = false;
296 off_t psize = 0;
298 while (max_n_read)
300 ssize_t n_read = read (src_fd, buf, MIN (max_n_read, buf_size));
301 if (n_read < 0)
303 if (errno == EINTR)
304 continue;
305 error (0, errno, _("error reading %s"), quoteaf (src_name));
306 return false;
308 if (n_read == 0)
309 break;
310 max_n_read -= n_read;
311 *total_n_read += n_read;
313 /* Loop over the input buffer in chunks of hole_size. */
314 size_t csize = hole_size ? hole_size : buf_size;
315 char *cbuf = buf;
316 char *pbuf = buf;
318 while (n_read)
320 bool prev_hole = make_hole;
321 csize = MIN (csize, n_read);
323 if (hole_size && csize)
324 make_hole = is_nul (cbuf, csize);
326 bool transition = (make_hole != prev_hole) && psize;
327 bool last_chunk = (n_read == csize && ! make_hole) || ! csize;
329 if (transition || last_chunk)
331 if (! transition)
332 psize += csize;
334 if (! prev_hole)
336 if (full_write (dest_fd, pbuf, psize) != psize)
338 error (0, errno, _("error writing %s"),
339 quoteaf (dst_name));
340 return false;
343 else
345 if (! create_hole (dest_fd, dst_name, punch_holes, psize))
346 return false;
349 pbuf = cbuf;
350 psize = csize;
352 if (last_chunk)
354 if (! csize)
355 n_read = 0; /* Finished processing buffer. */
357 if (transition)
358 csize = 0; /* Loop again to deal with last chunk. */
359 else
360 psize = 0; /* Reset for next read loop. */
363 else /* Coalesce writes/seeks. */
365 if (INT_ADD_WRAPV (psize, csize, &psize))
367 error (0, 0, _("overflow reading %s"), quoteaf (src_name));
368 return false;
372 n_read -= csize;
373 cbuf += csize;
376 *last_write_made_hole = make_hole;
378 /* It's tempting to break early here upon a short read from
379 a regular file. That would save the final read syscall
380 for each file. Unfortunately that doesn't work for
381 certain files in /proc or /sys with linux kernels. */
384 /* Ensure a trailing hole is created, so that subsequent
385 calls of sparse_copy() start at the correct offset. */
386 if (make_hole && ! create_hole (dest_fd, dst_name, punch_holes, psize))
387 return false;
388 else
389 return true;
392 /* Perform the O(1) btrfs clone operation, if possible.
393 Upon success, return 0. Otherwise, return -1 and set errno. */
394 static inline int
395 clone_file (int dest_fd, int src_fd)
397 #ifdef FICLONE
398 return ioctl (dest_fd, FICLONE, src_fd);
399 #else
400 (void) dest_fd;
401 (void) src_fd;
402 errno = ENOTSUP;
403 return -1;
404 #endif
407 /* Write N_BYTES zero bytes to file descriptor FD. Return true if successful.
408 Upon write failure, set errno and return false. */
409 static bool
410 write_zeros (int fd, off_t n_bytes)
412 static char *zeros;
413 static size_t nz = IO_BUFSIZE;
415 /* Attempt to use a relatively large calloc'd source buffer for
416 efficiency, but if that allocation fails, resort to a smaller
417 statically allocated one. */
418 if (zeros == NULL)
420 static char fallback[1024];
421 zeros = calloc (nz, 1);
422 if (zeros == NULL)
424 zeros = fallback;
425 nz = sizeof fallback;
429 while (n_bytes)
431 size_t n = MIN (nz, n_bytes);
432 if ((full_write (fd, zeros, n)) != n)
433 return false;
434 n_bytes -= n;
437 return true;
440 #ifdef SEEK_HOLE
441 /* Perform an efficient extent copy, if possible. This avoids
442 the overhead of detecting holes in hole-introducing/preserving
443 copy, and thus makes copying sparse files much more efficient.
444 Copy from SRC_FD to DEST_FD, using BUF (of size BUF_SIZE) for a buffer.
445 Look for holes of size HOLE_SIZE in the input.
446 The input file is of size SRC_TOTAL_SIZE.
447 Use SPARSE_MODE to determine whether to create holes in the output.
448 SRC_NAME and DST_NAME are the input and output file names.
449 Return true if successful, false (with a diagnostic) otherwise. */
451 static bool
452 lseek_copy (int src_fd, int dest_fd, char *buf, size_t buf_size,
453 size_t hole_size, off_t ext_start, off_t src_total_size,
454 enum Sparse_type sparse_mode,
455 bool allow_reflink,
456 char const *src_name, char const *dst_name)
458 off_t last_ext_start = 0;
459 off_t last_ext_len = 0;
460 off_t dest_pos = 0;
461 bool wrote_hole_at_eof = true;
463 while (0 <= ext_start)
465 off_t ext_end = lseek (src_fd, ext_start, SEEK_HOLE);
466 if (ext_end < 0)
468 if (errno != ENXIO)
469 goto cannot_lseek;
470 ext_end = src_total_size;
471 if (ext_end <= ext_start)
473 /* The input file grew; get its current size. */
474 src_total_size = lseek (src_fd, 0, SEEK_END);
475 if (src_total_size < 0)
476 goto cannot_lseek;
478 /* If the input file shrank after growing, stop copying. */
479 if (src_total_size <= ext_start)
480 break;
482 ext_end = src_total_size;
485 /* If the input file must have grown, increase its measured size. */
486 if (src_total_size < ext_end)
487 src_total_size = ext_end;
489 if (lseek (src_fd, ext_start, SEEK_SET) < 0)
490 goto cannot_lseek;
492 wrote_hole_at_eof = false;
493 off_t ext_hole_size = ext_start - last_ext_start - last_ext_len;
495 if (ext_hole_size)
497 if (sparse_mode != SPARSE_NEVER)
499 if (! create_hole (dest_fd, dst_name,
500 sparse_mode == SPARSE_ALWAYS,
501 ext_hole_size))
502 return false;
503 wrote_hole_at_eof = true;
505 else
507 /* When not inducing holes and when there is a hole between
508 the end of the previous extent and the beginning of the
509 current one, write zeros to the destination file. */
510 if (! write_zeros (dest_fd, ext_hole_size))
512 error (0, errno, _("%s: write failed"),
513 quotef (dst_name));
514 return false;
519 off_t ext_len = ext_end - ext_start;
520 last_ext_start = ext_start;
521 last_ext_len = ext_len;
523 /* Copy this extent, looking for further opportunities to not
524 bother to write zeros unless --sparse=never, since SEEK_HOLE
525 is conservative and may miss some holes. */
526 off_t n_read;
527 bool read_hole;
528 if ( ! sparse_copy (src_fd, dest_fd, buf, buf_size,
529 sparse_mode == SPARSE_NEVER ? 0 : hole_size,
530 true, allow_reflink, src_name, dst_name,
531 ext_len, &n_read, &read_hole))
532 return false;
534 dest_pos = ext_start + n_read;
535 if (n_read)
536 wrote_hole_at_eof = read_hole;
537 if (n_read < ext_len)
539 /* The input file shrank. */
540 src_total_size = dest_pos;
541 break;
544 ext_start = lseek (src_fd, dest_pos, SEEK_DATA);
545 if (ext_start < 0 && errno != ENXIO)
546 goto cannot_lseek;
549 /* When the source file ends with a hole, we have to do a little more work,
550 since the above copied only up to and including the final extent.
551 In order to complete the copy, we may have to insert a hole or write
552 zeros in the destination corresponding to the source file's hole-at-EOF.
554 In addition, if the final extent was a block of zeros at EOF and we've
555 just converted them to a hole in the destination, we must call ftruncate
556 here in order to record the proper length in the destination. */
557 if ((dest_pos < src_total_size || wrote_hole_at_eof)
558 && ! (sparse_mode == SPARSE_NEVER
559 ? write_zeros (dest_fd, src_total_size - dest_pos)
560 : ftruncate (dest_fd, src_total_size) == 0))
562 error (0, errno, _("failed to extend %s"), quoteaf (dst_name));
563 return false;
566 if (sparse_mode == SPARSE_ALWAYS && dest_pos < src_total_size
567 && punch_hole (dest_fd, dest_pos, src_total_size - dest_pos) < 0)
569 error (0, errno, _("error deallocating %s"), quoteaf (dst_name));
570 return false;
573 return true;
575 cannot_lseek:
576 error (0, errno, _("cannot lseek %s"), quoteaf (src_name));
577 return false;
579 #endif
581 /* FIXME: describe */
582 /* FIXME: rewrite this to use a hash table so we avoid the quadratic
583 performance hit that's probably noticeable only on trees deeper
584 than a few hundred levels. See use of active_dir_map in remove.c */
586 ATTRIBUTE_PURE
587 static bool
588 is_ancestor (const struct stat *sb, const struct dir_list *ancestors)
590 while (ancestors != 0)
592 if (ancestors->ino == sb->st_ino && ancestors->dev == sb->st_dev)
593 return true;
594 ancestors = ancestors->parent;
596 return false;
599 static bool
600 errno_unsupported (int err)
602 return err == ENOTSUP || err == ENODATA;
605 #if USE_XATTR
606 ATTRIBUTE_FORMAT ((printf, 2, 3))
607 static void
608 copy_attr_error (MAYBE_UNUSED struct error_context *ctx,
609 char const *fmt, ...)
611 if (!errno_unsupported (errno))
613 int err = errno;
614 va_list ap;
616 /* use verror module to print error message */
617 va_start (ap, fmt);
618 verror (0, err, fmt, ap);
619 va_end (ap);
623 ATTRIBUTE_FORMAT ((printf, 2, 3))
624 static void
625 copy_attr_allerror (MAYBE_UNUSED struct error_context *ctx,
626 char const *fmt, ...)
628 int err = errno;
629 va_list ap;
631 /* use verror module to print error message */
632 va_start (ap, fmt);
633 verror (0, err, fmt, ap);
634 va_end (ap);
637 static char const *
638 copy_attr_quote (MAYBE_UNUSED struct error_context *ctx, char const *str)
640 return quoteaf (str);
643 static void
644 copy_attr_free (MAYBE_UNUSED struct error_context *ctx,
645 MAYBE_UNUSED char const *str)
649 /* Exclude SELinux extended attributes that are otherwise handled,
650 and are problematic to copy again. Also honor attributes
651 configured for exclusion in /etc/xattr.conf.
652 FIXME: Should we handle POSIX ACLs similarly?
653 Return zero to skip. */
654 static int
655 check_selinux_attr (char const *name, struct error_context *ctx)
657 return STRNCMP_LIT (name, "security.selinux")
658 && attr_copy_check_permissions (name, ctx);
661 /* If positive SRC_FD and DST_FD descriptors are passed,
662 then copy by fd, otherwise copy by name. */
664 static bool
665 copy_attr (char const *src_path, int src_fd,
666 char const *dst_path, int dst_fd, struct cp_options const *x)
668 bool all_errors = (!x->data_copy_required || x->require_preserve_xattr);
669 bool some_errors = (!all_errors && !x->reduce_diagnostics);
670 int (*check) (char const *, struct error_context *)
671 = (x->preserve_security_context || x->set_security_context
672 ? check_selinux_attr : NULL);
674 # if 4 < __GNUC__ + (8 <= __GNUC_MINOR__)
675 /* Pacify gcc -Wsuggest-attribute=format through at least GCC 11.2.1. */
676 # pragma GCC diagnostic push
677 # pragma GCC diagnostic ignored "-Wsuggest-attribute=format"
678 # endif
679 struct error_context *ctx
680 = (all_errors || some_errors
681 ? (&(struct error_context) {
682 .error = all_errors ? copy_attr_allerror : copy_attr_error,
683 .quote = copy_attr_quote,
684 .quote_free = copy_attr_free
686 : NULL);
687 # if 4 < __GNUC__ + (8 <= __GNUC_MINOR__)
688 # pragma GCC diagnostic pop
689 # endif
691 return ! (0 <= src_fd && 0 <= dst_fd
692 ? attr_copy_fd (src_path, src_fd, dst_path, dst_fd, check, ctx)
693 : attr_copy_file (src_path, dst_path, check, ctx));
695 #else /* USE_XATTR */
697 static bool
698 copy_attr (MAYBE_UNUSED char const *src_path,
699 MAYBE_UNUSED int src_fd,
700 MAYBE_UNUSED char const *dst_path,
701 MAYBE_UNUSED int dst_fd,
702 MAYBE_UNUSED struct cp_options const *x)
704 return true;
706 #endif /* USE_XATTR */
708 /* Read the contents of the directory SRC_NAME_IN, and recursively
709 copy the contents to DST_NAME_IN aka DST_DIRFD+DST_RELNAME_IN.
710 NEW_DST is true if DST_NAME_IN is a directory
711 that was created previously in the recursion.
712 SRC_SB and ANCESTORS describe SRC_NAME_IN.
713 Set *COPY_INTO_SELF if SRC_NAME_IN is a parent of
714 (or the same as) DST_NAME_IN; otherwise, clear it.
715 Propagate *FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG from
716 caller to each invocation of copy_internal. Be careful to
717 pass the address of a temporary, and to update
718 *FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG only upon completion.
719 Return true if successful. */
721 static bool
722 copy_dir (char const *src_name_in, char const *dst_name_in,
723 int dst_dirfd, char const *dst_relname_in, bool new_dst,
724 const struct stat *src_sb, struct dir_list *ancestors,
725 const struct cp_options *x,
726 bool *first_dir_created_per_command_line_arg,
727 bool *copy_into_self)
729 char *name_space;
730 char *namep;
731 struct cp_options non_command_line_options = *x;
732 bool ok = true;
734 name_space = savedir (src_name_in, SAVEDIR_SORT_FASTREAD);
735 if (name_space == NULL)
737 /* This diagnostic is a bit vague because savedir can fail in
738 several different ways. */
739 error (0, errno, _("cannot access %s"), quoteaf (src_name_in));
740 return false;
743 /* For cp's -H option, dereference command line arguments, but do not
744 dereference symlinks that are found via recursive traversal. */
745 if (x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
746 non_command_line_options.dereference = DEREF_NEVER;
748 bool new_first_dir_created = false;
749 namep = name_space;
750 while (*namep != '\0')
752 bool local_copy_into_self;
753 char *src_name = file_name_concat (src_name_in, namep, NULL);
754 char *dst_name = file_name_concat (dst_name_in, namep, NULL);
755 bool first_dir_created = *first_dir_created_per_command_line_arg;
756 bool rename_succeeded;
758 ok &= copy_internal (src_name, dst_name, dst_dirfd,
759 dst_name + (dst_relname_in - dst_name_in),
760 new_dst, src_sb,
761 ancestors, &non_command_line_options, false,
762 &first_dir_created,
763 &local_copy_into_self, &rename_succeeded);
764 *copy_into_self |= local_copy_into_self;
766 free (dst_name);
767 free (src_name);
769 /* If we're copying into self, there's no point in continuing,
770 and in fact, that would even infloop, now that we record only
771 the first created directory per command line argument. */
772 if (local_copy_into_self)
773 break;
775 new_first_dir_created |= first_dir_created;
776 namep += strlen (namep) + 1;
778 free (name_space);
779 *first_dir_created_per_command_line_arg = new_first_dir_created;
781 return ok;
784 /* Set the owner and owning group of DEST_DESC to the st_uid and
785 st_gid fields of SRC_SB. If DEST_DESC is undefined (-1), set
786 the owner and owning group of DST_NAME aka DST_DIRFD+DST_RELNAME
787 instead; for safety prefer lchownat since no
788 symbolic links should be involved. DEST_DESC must
789 refer to the same file as DST_NAME if defined.
790 Upon failure to set both UID and GID, try to set only the GID.
791 NEW_DST is true if the file was newly created; otherwise,
792 DST_SB is the status of the destination.
793 Return 1 if the initial syscall succeeds, 0 if it fails but it's OK
794 not to preserve ownership, -1 otherwise. */
796 static int
797 set_owner (const struct cp_options *x, char const *dst_name,
798 int dst_dirfd, char const *dst_relname, int dest_desc,
799 struct stat const *src_sb, bool new_dst,
800 struct stat const *dst_sb)
802 uid_t uid = src_sb->st_uid;
803 gid_t gid = src_sb->st_gid;
805 /* Naively changing the ownership of an already-existing file before
806 changing its permissions would create a window of vulnerability if
807 the file's old permissions are too generous for the new owner and
808 group. Avoid the window by first changing to a restrictive
809 temporary mode if necessary. */
811 if (!new_dst && (x->preserve_mode || x->move_mode || x->set_mode))
813 mode_t old_mode = dst_sb->st_mode;
814 mode_t new_mode =
815 (x->preserve_mode || x->move_mode ? src_sb->st_mode : x->mode);
816 mode_t restrictive_temp_mode = old_mode & new_mode & S_IRWXU;
818 if ((USE_ACL
819 || (old_mode & CHMOD_MODE_BITS
820 & (~new_mode | S_ISUID | S_ISGID | S_ISVTX)))
821 && qset_acl (dst_name, dest_desc, restrictive_temp_mode) != 0)
823 if (! owner_failure_ok (x))
824 error (0, errno, _("clearing permissions for %s"),
825 quoteaf (dst_name));
826 return -x->require_preserve;
830 if (HAVE_FCHOWN && dest_desc != -1)
832 if (fchown (dest_desc, uid, gid) == 0)
833 return 1;
834 if (errno == EPERM || errno == EINVAL)
836 /* We've failed to set *both*. Now, try to set just the group
837 ID, but ignore any failure here, and don't change errno. */
838 int saved_errno = errno;
839 ignore_value (fchown (dest_desc, -1, gid));
840 errno = saved_errno;
843 else
845 if (lchownat (dst_dirfd, dst_relname, uid, gid) == 0)
846 return 1;
847 if (errno == EPERM || errno == EINVAL)
849 /* We've failed to set *both*. Now, try to set just the group
850 ID, but ignore any failure here, and don't change errno. */
851 int saved_errno = errno;
852 ignore_value (lchownat (dst_dirfd, dst_relname, -1, gid));
853 errno = saved_errno;
857 if (! chown_failure_ok (x))
859 error (0, errno, _("failed to preserve ownership for %s"),
860 quoteaf (dst_name));
861 if (x->require_preserve)
862 return -1;
865 return 0;
868 /* Set the st_author field of DEST_DESC to the st_author field of
869 SRC_SB. If DEST_DESC is undefined (-1), set the st_author field
870 of DST_NAME instead. DEST_DESC must refer to the same file as
871 DST_NAME if defined. */
873 static void
874 set_author (char const *dst_name, int dest_desc, const struct stat *src_sb)
876 #if HAVE_STRUCT_STAT_ST_AUTHOR
877 /* FIXME: Modify the following code so that it does not
878 follow symbolic links. */
880 /* Preserve the st_author field. */
881 file_t file = (dest_desc < 0
882 ? file_name_lookup (dst_name, 0, 0)
883 : getdport (dest_desc));
884 if (file == MACH_PORT_NULL)
885 error (0, errno, _("failed to lookup file %s"), quoteaf (dst_name));
886 else
888 error_t err = file_chauthor (file, src_sb->st_author);
889 if (err)
890 error (0, err, _("failed to preserve authorship for %s"),
891 quoteaf (dst_name));
892 mach_port_deallocate (mach_task_self (), file);
894 #else
895 (void) dst_name;
896 (void) dest_desc;
897 (void) src_sb;
898 #endif
901 /* Set the default security context for the process. New files will
902 have this security context set. Also existing files can have their
903 context adjusted based on this process context, by
904 set_file_security_ctx() called with PROCESS_LOCAL=true.
905 This should be called before files are created so there is no race
906 where a file may be present without an appropriate security context.
907 Based on CP_OPTIONS, diagnose warnings and fail when appropriate.
908 Return FALSE on failure, TRUE on success. */
910 bool
911 set_process_security_ctx (char const *src_name, char const *dst_name,
912 mode_t mode, bool new_dst, const struct cp_options *x)
914 if (x->preserve_security_context)
916 /* Set the default context for the process to match the source. */
917 bool all_errors = !x->data_copy_required || x->require_preserve_context;
918 bool some_errors = !all_errors && !x->reduce_diagnostics;
919 char *con;
921 if (0 <= lgetfilecon (src_name, &con))
923 if (setfscreatecon (con) < 0)
925 if (all_errors || (some_errors && !errno_unsupported (errno)))
926 error (0, errno,
927 _("failed to set default file creation context to %s"),
928 quote (con));
929 if (x->require_preserve_context)
931 freecon (con);
932 return false;
935 freecon (con);
937 else
939 if (all_errors || (some_errors && !errno_unsupported (errno)))
941 error (0, errno,
942 _("failed to get security context of %s"),
943 quoteaf (src_name));
945 if (x->require_preserve_context)
946 return false;
949 else if (x->set_security_context)
951 /* With -Z, adjust the default context for the process
952 to have the type component adjusted as per the destination path. */
953 if (new_dst && defaultcon (x->set_security_context, dst_name, mode) < 0
954 && ! ignorable_ctx_err (errno))
956 error (0, errno,
957 _("failed to set default file creation context for %s"),
958 quoteaf (dst_name));
962 return true;
965 /* Reset the security context of DST_NAME, to that already set
966 as the process default if !X->set_security_context. Otherwise
967 adjust the type component of DST_NAME's security context as
968 per the system default for that path. Issue warnings upon
969 failure, when allowed by various settings in X.
970 Return false on failure, true on success. */
972 bool
973 set_file_security_ctx (char const *dst_name,
974 bool recurse, const struct cp_options *x)
976 bool all_errors = (!x->data_copy_required
977 || x->require_preserve_context);
978 bool some_errors = !all_errors && !x->reduce_diagnostics;
980 if (! restorecon (x->set_security_context, dst_name, recurse))
982 if (all_errors || (some_errors && !errno_unsupported (errno)))
983 error (0, errno, _("failed to set the security context of %s"),
984 quoteaf_n (0, dst_name));
985 return false;
988 return true;
991 /* Change the file mode bits of the file identified by DESC or
992 DIRFD+NAME to MODE. Use DESC if DESC is valid and fchmod is
993 available, DIRFD+NAME otherwise. */
995 static int
996 fchmod_or_lchmod (int desc, int dirfd, char const *name, mode_t mode)
998 #if HAVE_FCHMOD
999 if (0 <= desc)
1000 return fchmod (desc, mode);
1001 #endif
1002 return lchmodat (dirfd, name, mode);
1005 #ifndef HAVE_STRUCT_STAT_ST_BLOCKS
1006 # define HAVE_STRUCT_STAT_ST_BLOCKS 0
1007 #endif
1009 /* Type of scan being done on the input when looking for sparseness. */
1010 enum scantype
1012 /* An error was found when determining scantype. */
1013 ERROR_SCANTYPE,
1015 /* No fancy scanning; just read and write. */
1016 PLAIN_SCANTYPE,
1018 /* Read and examine data looking for zero blocks; useful when
1019 attempting to create sparse output. */
1020 ZERO_SCANTYPE,
1022 /* lseek information is available. */
1023 LSEEK_SCANTYPE,
1026 /* Result of infer_scantype. */
1027 union scan_inference
1029 /* Used if infer_scantype returns LSEEK_SCANTYPE. This is the
1030 offset of the first data block, or -1 if the file has no data. */
1031 off_t ext_start;
1034 /* Return how to scan a file with descriptor FD and stat buffer SB.
1035 Store any information gathered into *SCAN_INFERENCE. */
1036 static enum scantype
1037 infer_scantype (int fd, struct stat const *sb,
1038 union scan_inference *scan_inference)
1040 if (! (HAVE_STRUCT_STAT_ST_BLOCKS
1041 && S_ISREG (sb->st_mode)
1042 && ST_NBLOCKS (*sb) < sb->st_size / ST_NBLOCKSIZE))
1043 return PLAIN_SCANTYPE;
1045 #ifdef SEEK_HOLE
1046 scan_inference->ext_start = lseek (fd, 0, SEEK_DATA);
1047 if (0 <= scan_inference->ext_start || errno == ENXIO)
1048 return LSEEK_SCANTYPE;
1049 else if (errno != EINVAL && !is_ENOTSUP (errno))
1050 return ERROR_SCANTYPE;
1051 #endif
1053 return ZERO_SCANTYPE;
1057 /* Copy a regular file from SRC_NAME to DST_NAME aka DST_DIRFD+DST_RELNAME.
1058 If the source file contains holes, copies holes and blocks of zeros
1059 in the source file as holes in the destination file.
1060 (Holes are read as zeroes by the 'read' system call.)
1061 When creating the destination, use DST_MODE & ~OMITTED_PERMISSIONS
1062 as the third argument in the call to open, adding
1063 OMITTED_PERMISSIONS after copying as needed.
1064 X provides many option settings.
1065 Return true if successful.
1066 *NEW_DST is initially as in copy_internal.
1067 If successful, set *NEW_DST to true if the destination file was created and
1068 to false otherwise; if unsuccessful, perhaps set *NEW_DST to some value.
1069 SRC_SB is the result of calling follow_fstatat on SRC_NAME. */
1071 static bool
1072 copy_reg (char const *src_name, char const *dst_name,
1073 int dst_dirfd, char const *dst_relname,
1074 const struct cp_options *x,
1075 mode_t dst_mode, mode_t omitted_permissions, bool *new_dst,
1076 struct stat const *src_sb)
1078 char *buf = NULL;
1079 int dest_desc;
1080 int dest_errno;
1081 int source_desc;
1082 mode_t src_mode = src_sb->st_mode;
1083 mode_t extra_permissions;
1084 struct stat sb;
1085 struct stat src_open_sb;
1086 union scan_inference scan_inference;
1087 bool return_val = true;
1088 bool data_copy_required = x->data_copy_required;
1089 bool preserve_xattr = USE_XATTR & x->preserve_xattr;
1091 source_desc = open (src_name,
1092 (O_RDONLY | O_BINARY
1093 | (x->dereference == DEREF_NEVER ? O_NOFOLLOW : 0)));
1094 if (source_desc < 0)
1096 error (0, errno, _("cannot open %s for reading"), quoteaf (src_name));
1097 return false;
1100 if (fstat (source_desc, &src_open_sb) != 0)
1102 error (0, errno, _("cannot fstat %s"), quoteaf (src_name));
1103 return_val = false;
1104 goto close_src_desc;
1107 /* Compare the source dev/ino from the open file to the incoming,
1108 saved ones obtained via a previous call to stat. */
1109 if (! SAME_INODE (*src_sb, src_open_sb))
1111 error (0, 0,
1112 _("skipping file %s, as it was replaced while being copied"),
1113 quoteaf (src_name));
1114 return_val = false;
1115 goto close_src_desc;
1118 /* The semantics of the following open calls are mandated
1119 by the specs for both cp and mv. */
1120 if (! *new_dst)
1122 int open_flags =
1123 O_WRONLY | O_BINARY | (data_copy_required ? O_TRUNC : 0);
1124 dest_desc = openat (dst_dirfd, dst_relname, open_flags);
1125 dest_errno = errno;
1127 /* When using cp --preserve=context to copy to an existing destination,
1128 reset the context as per the default context, which has already been
1129 set according to the src.
1130 When using the mutually exclusive -Z option, then adjust the type of
1131 the existing context according to the system default for the dest.
1132 Note we set the context here, _after_ the file is opened, lest the
1133 new context disallow that. */
1134 if (0 <= dest_desc
1135 && (x->set_security_context || x->preserve_security_context))
1137 if (! set_file_security_ctx (dst_name, false, x))
1139 if (x->require_preserve_context)
1141 return_val = false;
1142 goto close_src_and_dst_desc;
1147 if (dest_desc < 0 && dest_errno != ENOENT
1148 && x->unlink_dest_after_failed_open)
1150 if (unlinkat (dst_dirfd, dst_relname, 0) == 0)
1152 if (x->verbose)
1153 printf (_("removed %s\n"), quoteaf (dst_name));
1155 else if (errno != ENOENT)
1157 error (0, errno, _("cannot remove %s"), quoteaf (dst_name));
1158 return_val = false;
1159 goto close_src_desc;
1162 dest_errno = ENOENT;
1165 if (dest_desc < 0 && dest_errno == ENOENT)
1167 /* Ensure there is no race where a file may be left without
1168 an appropriate security context. */
1169 if (x->set_security_context)
1171 if (! set_process_security_ctx (src_name, dst_name, dst_mode,
1172 true, x))
1174 return_val = false;
1175 goto close_src_desc;
1179 /* Tell caller that the destination file is created. */
1180 *new_dst = true;
1184 if (*new_dst)
1186 #if HAVE_FCLONEFILEAT && !USE_XATTR
1187 int clone_flags = x->preserve_ownership ? 0 : CLONE_NOOWNERCOPY;
1188 if (data_copy_required && x->reflink_mode
1189 && x->preserve_mode && x->preserve_timestamps
1190 && (fclonefileat (source_desc, dst_dirfd, dst_relname, clone_flags)
1191 == 0))
1192 goto close_src_desc;
1193 #endif
1195 /* To allow copying xattrs on read-only files, create with u+w.
1196 This satisfies an inode permission check done by
1197 xattr_permission in fs/xattr.c of the GNU/Linux kernel. */
1198 mode_t open_mode =
1199 ((dst_mode & ~omitted_permissions)
1200 | (preserve_xattr && !x->owner_privileges ? S_IWUSR : 0));
1201 extra_permissions = open_mode & ~dst_mode; /* either 0 or S_IWUSR */
1203 int open_flags = O_WRONLY | O_CREAT | O_BINARY;
1204 dest_desc = openat (dst_dirfd, dst_relname, open_flags | O_EXCL,
1205 open_mode);
1206 dest_errno = errno;
1208 /* When trying to copy through a dangling destination symlink,
1209 the above open fails with EEXIST. If that happens, and
1210 readlinkat shows that it is a symlink, then we
1211 have a problem: trying to resolve this dangling symlink to
1212 a directory/destination-entry pair is fundamentally racy,
1213 so punt. If x->open_dangling_dest_symlink is set (cp sets
1214 that when POSIXLY_CORRECT is set in the environment), simply
1215 call open again, but without O_EXCL (potentially dangerous).
1216 If not, fail with a diagnostic. These shenanigans are necessary
1217 only when copying, i.e., not in move_mode. */
1218 if (dest_desc < 0 && dest_errno == EEXIST && ! x->move_mode)
1220 char dummy[1];
1221 if (0 <= readlinkat (dst_dirfd, dst_relname, dummy, sizeof dummy))
1223 if (x->open_dangling_dest_symlink)
1225 dest_desc = openat (dst_dirfd, dst_relname,
1226 open_flags, open_mode);
1227 dest_errno = errno;
1229 else
1231 error (0, 0, _("not writing through dangling symlink %s"),
1232 quoteaf (dst_name));
1233 return_val = false;
1234 goto close_src_desc;
1239 /* Improve quality of diagnostic when a nonexistent dst_name
1240 ends in a slash and open fails with errno == EISDIR. */
1241 if (dest_desc < 0 && dest_errno == EISDIR
1242 && *dst_name && dst_name[strlen (dst_name) - 1] == '/')
1243 dest_errno = ENOTDIR;
1245 else
1247 omitted_permissions = extra_permissions = 0;
1250 if (dest_desc < 0)
1252 error (0, dest_errno, _("cannot create regular file %s"),
1253 quoteaf (dst_name));
1254 return_val = false;
1255 goto close_src_desc;
1258 /* --attributes-only overrides --reflink. */
1259 if (data_copy_required && x->reflink_mode)
1261 if (clone_file (dest_desc, source_desc) == 0)
1262 data_copy_required = false;
1263 else if (x->reflink_mode == REFLINK_ALWAYS)
1265 error (0, errno, _("failed to clone %s from %s"),
1266 quoteaf_n (0, dst_name), quoteaf_n (1, src_name));
1267 return_val = false;
1268 goto close_src_and_dst_desc;
1272 if (! (data_copy_required | x->preserve_ownership | extra_permissions))
1273 sb.st_mode = 0;
1274 else if (fstat (dest_desc, &sb) != 0)
1276 error (0, errno, _("cannot fstat %s"), quoteaf (dst_name));
1277 return_val = false;
1278 goto close_src_and_dst_desc;
1281 /* If extra permissions needed for copy_xattr didn't happen (e.g.,
1282 due to umask) chmod to add them temporarily; if that fails give
1283 up with extra permissions, letting copy_attr fail later. */
1284 mode_t temporary_mode = sb.st_mode | extra_permissions;
1285 if (temporary_mode != sb.st_mode
1286 && (fchmod_or_lchmod (dest_desc, dst_dirfd, dst_relname, temporary_mode)
1287 != 0))
1288 extra_permissions = 0;
1290 if (data_copy_required)
1292 /* Choose a suitable buffer size; it may be adjusted later. */
1293 size_t buf_size = io_blksize (sb);
1294 size_t hole_size = ST_BLKSIZE (sb);
1296 /* Deal with sparse files. */
1297 enum scantype scantype = infer_scantype (source_desc, &src_open_sb,
1298 &scan_inference);
1299 if (scantype == ERROR_SCANTYPE)
1301 error (0, errno, _("cannot lseek %s"), quoteaf (src_name));
1302 return_val = false;
1303 goto close_src_and_dst_desc;
1305 bool make_holes
1306 = (S_ISREG (sb.st_mode)
1307 && (x->sparse_mode == SPARSE_ALWAYS
1308 || (x->sparse_mode == SPARSE_AUTO
1309 && scantype != PLAIN_SCANTYPE)));
1311 fdadvise (source_desc, 0, 0, FADVISE_SEQUENTIAL);
1313 /* If not making a sparse file, try to use a more-efficient
1314 buffer size. */
1315 if (! make_holes)
1317 /* Compute the least common multiple of the input and output
1318 buffer sizes, adjusting for outlandish values. */
1319 size_t blcm_max = MIN (SIZE_MAX, SSIZE_MAX);
1320 size_t blcm = buffer_lcm (io_blksize (src_open_sb), buf_size,
1321 blcm_max);
1323 /* Do not bother with a buffer larger than the input file, plus one
1324 byte to make sure the file has not grown while reading it. */
1325 if (S_ISREG (src_open_sb.st_mode) && src_open_sb.st_size < buf_size)
1326 buf_size = src_open_sb.st_size + 1;
1328 /* However, stick with a block size that is a positive multiple of
1329 blcm, overriding the above adjustments. Watch out for
1330 overflow. */
1331 buf_size += blcm - 1;
1332 buf_size -= buf_size % blcm;
1333 if (buf_size == 0 || blcm_max < buf_size)
1334 buf_size = blcm;
1337 buf = xalignalloc (getpagesize (), buf_size);
1339 off_t n_read;
1340 bool wrote_hole_at_eof = false;
1341 if (! (
1342 #ifdef SEEK_HOLE
1343 scantype == LSEEK_SCANTYPE
1344 ? lseek_copy (source_desc, dest_desc, buf, buf_size, hole_size,
1345 scan_inference.ext_start, src_open_sb.st_size,
1346 make_holes ? x->sparse_mode : SPARSE_NEVER,
1347 x->reflink_mode != REFLINK_NEVER,
1348 src_name, dst_name)
1350 #endif
1351 sparse_copy (source_desc, dest_desc, buf, buf_size,
1352 make_holes ? hole_size : 0,
1353 x->sparse_mode == SPARSE_ALWAYS,
1354 x->reflink_mode != REFLINK_NEVER,
1355 src_name, dst_name, UINTMAX_MAX, &n_read,
1356 &wrote_hole_at_eof)))
1358 return_val = false;
1359 goto close_src_and_dst_desc;
1361 else if (wrote_hole_at_eof && ftruncate (dest_desc, n_read) < 0)
1363 error (0, errno, _("failed to extend %s"), quoteaf (dst_name));
1364 return_val = false;
1365 goto close_src_and_dst_desc;
1369 if (x->preserve_timestamps)
1371 struct timespec timespec[2];
1372 timespec[0] = get_stat_atime (src_sb);
1373 timespec[1] = get_stat_mtime (src_sb);
1375 if (fdutimensat (dest_desc, dst_dirfd, dst_relname, timespec, 0) != 0)
1377 error (0, errno, _("preserving times for %s"), quoteaf (dst_name));
1378 if (x->require_preserve)
1380 return_val = false;
1381 goto close_src_and_dst_desc;
1386 /* Set ownership before xattrs as changing owners will
1387 clear capabilities. */
1388 if (x->preserve_ownership && ! SAME_OWNER_AND_GROUP (*src_sb, sb))
1390 switch (set_owner (x, dst_name, dst_dirfd, dst_relname, dest_desc,
1391 src_sb, *new_dst, &sb))
1393 case -1:
1394 return_val = false;
1395 goto close_src_and_dst_desc;
1397 case 0:
1398 src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX);
1399 break;
1403 if (preserve_xattr)
1405 if (!copy_attr (src_name, source_desc, dst_name, dest_desc, x)
1406 && x->require_preserve_xattr)
1407 return_val = false;
1410 set_author (dst_name, dest_desc, src_sb);
1412 if (x->preserve_mode || x->move_mode)
1414 if (copy_acl (src_name, source_desc, dst_name, dest_desc, src_mode) != 0
1415 && x->require_preserve)
1416 return_val = false;
1418 else if (x->set_mode)
1420 if (set_acl (dst_name, dest_desc, x->mode) != 0)
1421 return_val = false;
1423 else if (x->explicit_no_preserve_mode && *new_dst)
1425 if (set_acl (dst_name, dest_desc, MODE_RW_UGO & ~cached_umask ()) != 0)
1426 return_val = false;
1428 else if (omitted_permissions | extra_permissions)
1430 omitted_permissions &= ~ cached_umask ();
1431 if ((omitted_permissions | extra_permissions)
1432 && (fchmod_or_lchmod (dest_desc, dst_dirfd, dst_relname,
1433 dst_mode & ~ cached_umask ())
1434 != 0))
1436 error (0, errno, _("preserving permissions for %s"),
1437 quoteaf (dst_name));
1438 if (x->require_preserve)
1439 return_val = false;
1443 close_src_and_dst_desc:
1444 if (close (dest_desc) < 0)
1446 error (0, errno, _("failed to close %s"), quoteaf (dst_name));
1447 return_val = false;
1449 close_src_desc:
1450 if (close (source_desc) < 0)
1452 error (0, errno, _("failed to close %s"), quoteaf (src_name));
1453 return_val = false;
1456 alignfree (buf);
1457 return return_val;
1460 /* Return whether it's OK that two files are the "same" by some measure.
1461 The first file is SRC_NAME and has status SRC_SB.
1462 The second is DST_DIRFD+DST_RELNAME and has status DST_SB.
1463 The copying options are X. The goal is to avoid
1464 making the 'copy' operation remove both copies of the file
1465 in that case, while still allowing the user to e.g., move or
1466 copy a regular file onto a symlink that points to it.
1467 Try to minimize the cost of this function in the common case.
1468 Set *RETURN_NOW if we've determined that the caller has no more
1469 work to do and should return successfully, right away. */
1471 static bool
1472 same_file_ok (char const *src_name, struct stat const *src_sb,
1473 int dst_dirfd, char const *dst_relname, struct stat const *dst_sb,
1474 const struct cp_options *x, bool *return_now)
1476 const struct stat *src_sb_link;
1477 const struct stat *dst_sb_link;
1478 struct stat tmp_dst_sb;
1479 struct stat tmp_src_sb;
1481 bool same_link;
1482 bool same = SAME_INODE (*src_sb, *dst_sb);
1484 *return_now = false;
1486 /* FIXME: this should (at the very least) be moved into the following
1487 if-block. More likely, it should be removed, because it inhibits
1488 making backups. But removing it will result in a change in behavior
1489 that will probably have to be documented -- and tests will have to
1490 be updated. */
1491 if (same && x->hard_link)
1493 *return_now = true;
1494 return true;
1497 if (x->dereference == DEREF_NEVER)
1499 same_link = same;
1501 /* If both the source and destination files are symlinks (and we'll
1502 know this here IFF preserving symlinks), then it's usually ok
1503 when they are distinct. */
1504 if (S_ISLNK (src_sb->st_mode) && S_ISLNK (dst_sb->st_mode))
1506 bool sn = same_nameat (AT_FDCWD, src_name, dst_dirfd, dst_relname);
1507 if ( ! sn)
1509 /* It's fine when we're making any type of backup. */
1510 if (x->backup_type != no_backups)
1511 return true;
1513 /* Here we have two symlinks that are hard-linked together,
1514 and we're not making backups. In this unusual case, simply
1515 returning true would lead to mv calling "rename(A,B)",
1516 which would do nothing and return 0. */
1517 if (same_link)
1519 *return_now = true;
1520 return ! x->move_mode;
1524 return ! sn;
1527 src_sb_link = src_sb;
1528 dst_sb_link = dst_sb;
1530 else
1532 if (!same)
1533 return true;
1535 if (lstatat (dst_dirfd, dst_relname, &tmp_dst_sb) != 0
1536 || lstat (src_name, &tmp_src_sb) != 0)
1537 return true;
1539 src_sb_link = &tmp_src_sb;
1540 dst_sb_link = &tmp_dst_sb;
1542 same_link = SAME_INODE (*src_sb_link, *dst_sb_link);
1544 /* If both are symlinks, then it's ok, but only if the destination
1545 will be unlinked before being opened. This is like the test
1546 above, but with the addition of the unlink_dest_before_opening
1547 conjunct because otherwise, with two symlinks to the same target,
1548 we'd end up truncating the source file. */
1549 if (S_ISLNK (src_sb_link->st_mode) && S_ISLNK (dst_sb_link->st_mode)
1550 && x->unlink_dest_before_opening)
1551 return true;
1554 /* The backup code ensures there's a copy, so it's usually ok to
1555 remove any destination file. One exception is when both
1556 source and destination are the same directory entry. In that
1557 case, moving the destination file aside (in making the backup)
1558 would also rename the source file and result in an error. */
1559 if (x->backup_type != no_backups)
1561 if (!same_link)
1563 /* In copy mode when dereferencing symlinks, if the source is a
1564 symlink and the dest is not, then backing up the destination
1565 (moving it aside) would make it a dangling symlink, and the
1566 subsequent attempt to open it in copy_reg would fail with
1567 a misleading diagnostic. Avoid that by returning zero in
1568 that case so the caller can make cp (or mv when it has to
1569 resort to reading the source file) fail now. */
1571 /* FIXME-note: even with the following kludge, we can still provoke
1572 the offending diagnostic. It's just a little harder to do :-)
1573 $ rm -f a b c; touch c; ln -s c b; ln -s b a; cp -b a b
1574 cp: cannot open 'a' for reading: No such file or directory
1575 That's misleading, since a subsequent 'ls' shows that 'a'
1576 is still there.
1577 One solution would be to open the source file *before* moving
1578 aside the destination, but that'd involve a big rewrite. */
1579 if ( ! x->move_mode
1580 && x->dereference != DEREF_NEVER
1581 && S_ISLNK (src_sb_link->st_mode)
1582 && ! S_ISLNK (dst_sb_link->st_mode))
1583 return false;
1585 return true;
1588 /* FIXME: What about case insensitive file systems ? */
1589 return ! same_nameat (AT_FDCWD, src_name, dst_dirfd, dst_relname);
1592 #if 0
1593 /* FIXME: use or remove */
1595 /* If we're making a backup, we'll detect the problem case in
1596 copy_reg because SRC_NAME will no longer exist. Allowing
1597 the test to be deferred lets cp do some useful things.
1598 But when creating hardlinks and SRC_NAME is a symlink
1599 but DST_RELNAME is not we must test anyway. */
1600 if (x->hard_link
1601 || !S_ISLNK (src_sb_link->st_mode)
1602 || S_ISLNK (dst_sb_link->st_mode))
1603 return true;
1605 if (x->dereference != DEREF_NEVER)
1606 return true;
1607 #endif
1609 if (x->move_mode || x->unlink_dest_before_opening)
1611 /* They may refer to the same file if we're in move mode and the
1612 target is a symlink. That is ok, since we remove any existing
1613 destination file before opening it -- via 'rename' if they're on
1614 the same file system, via unlinkat otherwise. */
1615 if (S_ISLNK (dst_sb_link->st_mode))
1616 return true;
1618 /* It's not ok if they're distinct hard links to the same file as
1619 this causes a race condition and we may lose data in this case. */
1620 if (same_link
1621 && 1 < dst_sb_link->st_nlink
1622 && ! same_nameat (AT_FDCWD, src_name, dst_dirfd, dst_relname))
1623 return ! x->move_mode;
1626 /* If neither is a symlink, then it's ok as long as they aren't
1627 hard links to the same file. */
1628 if (!S_ISLNK (src_sb_link->st_mode) && !S_ISLNK (dst_sb_link->st_mode))
1630 if (!SAME_INODE (*src_sb_link, *dst_sb_link))
1631 return true;
1633 /* If they are the same file, it's ok if we're making hard links. */
1634 if (x->hard_link)
1636 *return_now = true;
1637 return true;
1641 /* At this point, it is normally an error (data loss) to move a symlink
1642 onto its referent, but in at least one narrow case, it is not:
1643 In move mode, when
1644 1) src is a symlink,
1645 2) dest has a link count of 2 or more and
1646 3) dest and the referent of src are not the same directory entry,
1647 then it's ok, since while we'll lose one of those hard links,
1648 src will still point to a remaining link.
1649 Note that technically, condition #3 obviates condition #2, but we
1650 retain the 1 < st_nlink condition because that means fewer invocations
1651 of the more expensive #3.
1653 Given this,
1654 $ touch f && ln f l && ln -s f s
1655 $ ls -og f l s
1656 -rw-------. 2 0 Jan 4 22:46 f
1657 -rw-------. 2 0 Jan 4 22:46 l
1658 lrwxrwxrwx. 1 1 Jan 4 22:46 s -> f
1659 this must fail: mv s f
1660 this must succeed: mv s l */
1661 if (x->move_mode
1662 && S_ISLNK (src_sb->st_mode)
1663 && 1 < dst_sb_link->st_nlink)
1665 char *abs_src = canonicalize_file_name (src_name);
1666 if (abs_src)
1668 bool result = ! same_nameat (AT_FDCWD, abs_src,
1669 dst_dirfd, dst_relname);
1670 free (abs_src);
1671 return result;
1675 /* It's ok to recreate a destination symlink. */
1676 if (x->symbolic_link && S_ISLNK (dst_sb_link->st_mode))
1677 return true;
1679 if (x->dereference == DEREF_NEVER)
1681 if ( ! S_ISLNK (src_sb_link->st_mode))
1682 tmp_src_sb = *src_sb_link;
1683 else if (stat (src_name, &tmp_src_sb) != 0)
1684 return true;
1686 if ( ! S_ISLNK (dst_sb_link->st_mode))
1687 tmp_dst_sb = *dst_sb_link;
1688 else if (statat (dst_dirfd, dst_relname, &tmp_dst_sb) != 0)
1689 return true;
1691 if ( ! SAME_INODE (tmp_src_sb, tmp_dst_sb))
1692 return true;
1694 if (x->hard_link)
1696 /* It's ok to attempt to hardlink the same file,
1697 and return early if not replacing a symlink.
1698 Note we need to return early to avoid a later
1699 unlink() of DST (when SRC is a symlink). */
1700 *return_now = ! S_ISLNK (dst_sb_link->st_mode);
1701 return true;
1705 return false;
1708 /* Return whether DST_DIRFD+DST_RELNAME, with mode MODE,
1709 is writable in the sense of 'mv'.
1710 Always consider a symbolic link to be writable. */
1711 static bool
1712 writable_destination (int dst_dirfd, char const *dst_relname, mode_t mode)
1714 return (S_ISLNK (mode)
1715 || can_write_any_file ()
1716 || faccessat (dst_dirfd, dst_relname, W_OK, AT_EACCESS) == 0);
1719 static bool
1720 overwrite_ok (struct cp_options const *x, char const *dst_name,
1721 int dst_dirfd, char const *dst_relname,
1722 struct stat const *dst_sb)
1724 if (! writable_destination (dst_dirfd, dst_relname, dst_sb->st_mode))
1726 char perms[12]; /* "-rwxrwxrwx " ls-style modes. */
1727 strmode (dst_sb->st_mode, perms);
1728 perms[10] = '\0';
1729 fprintf (stderr,
1730 (x->move_mode || x->unlink_dest_before_opening
1731 || x->unlink_dest_after_failed_open)
1732 ? _("%s: replace %s, overriding mode %04lo (%s)? ")
1733 : _("%s: unwritable %s (mode %04lo, %s); try anyway? "),
1734 program_name, quoteaf (dst_name),
1735 (unsigned long int) (dst_sb->st_mode & CHMOD_MODE_BITS),
1736 &perms[1]);
1738 else
1740 fprintf (stderr, _("%s: overwrite %s? "),
1741 program_name, quoteaf (dst_name));
1744 return yesno ();
1747 /* Initialize the hash table implementing a set of F_triple entries
1748 corresponding to destination files. */
1749 extern void
1750 dest_info_init (struct cp_options *x)
1752 x->dest_info
1753 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
1754 NULL,
1755 triple_hash,
1756 triple_compare,
1757 triple_free);
1758 if (! x->dest_info)
1759 xalloc_die ();
1762 #ifdef lint
1763 extern void
1764 dest_info_free (struct cp_options *x)
1766 if (x->dest_info)
1767 hash_free (x->dest_info);
1768 x->dest_info = NULL;
1770 #endif
1772 /* Initialize the hash table implementing a set of F_triple entries
1773 corresponding to source files listed on the command line. */
1774 extern void
1775 src_info_init (struct cp_options *x)
1778 /* Note that we use triple_hash_no_name here.
1779 Contrast with the use of triple_hash above.
1780 That is necessary because a source file may be specified
1781 in many different ways. We want to warn about this
1782 cp a a d/
1783 as well as this:
1784 cp a ./a d/
1786 x->src_info
1787 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
1788 NULL,
1789 triple_hash_no_name,
1790 triple_compare,
1791 triple_free);
1792 if (! x->src_info)
1793 xalloc_die ();
1796 #ifdef lint
1797 extern void
1798 src_info_free (struct cp_options *x)
1800 if (x->src_info)
1801 hash_free (x->src_info);
1802 x->src_info = NULL;
1804 #endif
1806 /* When effecting a move (e.g., for mv(1)), and given the name DST_NAME
1807 aka DST_DIRFD+DST_RELNAME
1808 of the destination and a corresponding stat buffer, DST_SB, return
1809 true if the logical 'move' operation should _not_ proceed.
1810 Otherwise, return false.
1811 Depending on options specified in X, this code may issue an
1812 interactive prompt asking whether it's ok to overwrite DST_NAME. */
1813 static bool
1814 abandon_move (const struct cp_options *x,
1815 char const *dst_name,
1816 int dst_dirfd, char const *dst_relname,
1817 struct stat const *dst_sb)
1819 assert (x->move_mode);
1820 return (x->interactive == I_ALWAYS_NO
1821 || ((x->interactive == I_ASK_USER
1822 || (x->interactive == I_UNSPECIFIED
1823 && x->stdin_tty
1824 && ! writable_destination (dst_dirfd, dst_relname,
1825 dst_sb->st_mode)))
1826 && ! overwrite_ok (x, dst_name, dst_dirfd, dst_relname, dst_sb)));
1829 /* Print --verbose output on standard output, e.g. 'new' -> 'old'.
1830 If BACKUP_DST_NAME is non-NULL, then also indicate that it is
1831 the name of a backup file. */
1832 static void
1833 emit_verbose (char const *src, char const *dst, char const *backup_dst_name)
1835 printf ("%s -> %s", quoteaf_n (0, src), quoteaf_n (1, dst));
1836 if (backup_dst_name)
1837 printf (_(" (backup: %s)"), quoteaf (backup_dst_name));
1838 putchar ('\n');
1841 /* A wrapper around "setfscreatecon (NULL)" that exits upon failure. */
1842 static void
1843 restore_default_fscreatecon_or_die (void)
1845 if (setfscreatecon (NULL) != 0)
1846 die (EXIT_FAILURE, errno,
1847 _("failed to restore the default file creation context"));
1850 /* Return a newly-allocated string that is like STR
1851 except replace its suffix SUFFIX with NEWSUFFIX. */
1852 static char *
1853 subst_suffix (char const *str, char const *suffix, char const *newsuffix)
1855 idx_t prefixlen = suffix - str;
1856 idx_t newsuffixsize = strlen (newsuffix) + 1;
1857 char *r = ximalloc (prefixlen + newsuffixsize);
1858 memcpy (r + prefixlen, newsuffix, newsuffixsize);
1859 return memcpy (r, str, prefixlen);
1862 /* Create a hard link to SRC_NAME aka SRC_DIRFD+SRC_RELNAME;
1863 the new link is at DST_NAME aka DST_DIRFD+DST_RELNAME.
1864 A null SRC_NAME stands for the file whose name is like DST_NAME
1865 except with DST_RELNAME replaced with SRC_RELNAME.
1866 Honor the REPLACE, VERBOSE and DEREFERENCE settings.
1867 Return true upon success. Otherwise, diagnose the
1868 failure and return false. If SRC_NAME is a symbolic link, then it will not
1869 be followed unless DEREFERENCE is true.
1870 If the system doesn't support hard links to symbolic links, then DST_NAME
1871 will be created as a symbolic link to SRC_NAME. */
1872 static bool
1873 create_hard_link (char const *src_name, int src_dirfd, char const *src_relname,
1874 char const *dst_name, int dst_dirfd, char const *dst_relname,
1875 bool replace, bool verbose, bool dereference)
1877 int err = force_linkat (src_dirfd, src_relname, dst_dirfd, dst_relname,
1878 dereference ? AT_SYMLINK_FOLLOW : 0,
1879 replace, -1);
1880 if (0 < err)
1883 char *a_src_name = NULL;
1884 if (!src_name)
1885 src_name = a_src_name = subst_suffix (dst_name, dst_relname,
1886 src_relname);
1887 error (0, err, _("cannot create hard link %s to %s"),
1888 quoteaf_n (0, dst_name), quoteaf_n (1, src_name));
1889 free (a_src_name);
1890 return false;
1892 if (err < 0 && verbose)
1893 printf (_("removed %s\n"), quoteaf (dst_name));
1894 return true;
1897 /* Return true if the current file should be (tried to be) dereferenced:
1898 either for DEREF_ALWAYS or for DEREF_COMMAND_LINE_ARGUMENTS in the case
1899 where the current file is a COMMAND_LINE_ARG; otherwise return false. */
1900 ATTRIBUTE_PURE
1901 static inline bool
1902 should_dereference (const struct cp_options *x, bool command_line_arg)
1904 return x->dereference == DEREF_ALWAYS
1905 || (x->dereference == DEREF_COMMAND_LINE_ARGUMENTS
1906 && command_line_arg);
1909 /* Return true if the source file with basename SRCBASE and status SRC_ST
1910 is likely to be the simple backup file for DST_DIRFD+DST_RELNAME. */
1911 static bool
1912 source_is_dst_backup (char const *srcbase, struct stat const *src_st,
1913 int dst_dirfd, char const *dst_relname)
1915 size_t srcbaselen = strlen (srcbase);
1916 char const *dstbase = last_component (dst_relname);
1917 size_t dstbaselen = strlen (dstbase);
1918 size_t suffixlen = strlen (simple_backup_suffix);
1919 if (! (srcbaselen == dstbaselen + suffixlen
1920 && memcmp (srcbase, dstbase, dstbaselen) == 0
1921 && STREQ (srcbase + dstbaselen, simple_backup_suffix)))
1922 return false;
1923 char *dst_back = subst_suffix (dst_relname,
1924 dst_relname + strlen (dst_relname),
1925 simple_backup_suffix);
1926 struct stat dst_back_sb;
1927 int dst_back_status = statat (dst_dirfd, dst_back, &dst_back_sb);
1928 free (dst_back);
1929 return dst_back_status == 0 && SAME_INODE (*src_st, dst_back_sb);
1932 /* Copy the file SRC_NAME to the file DST_NAME aka DST_DIRFD+DST_RELNAME.
1933 If NONEXISTENT_DST is positive, DST_NAME does not exist even as a
1934 dangling symlink; if negative, it does not exist except possibly
1935 as a dangling symlink; if zero, its existence status is unknown.
1936 A non-null PARENT describes the parent directory.
1937 ANCESTORS points to a linked, null terminated list of
1938 devices and inodes of parent directories of SRC_NAME.
1939 X summarizes the command-line options.
1940 COMMAND_LINE_ARG means SRC_NAME was specified on the command line.
1941 FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG is both input and output.
1942 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
1943 same as) DST_NAME; otherwise, clear it.
1944 If X->move_mode, set *RENAME_SUCCEEDED according to whether
1945 the source was simply renamed to the destination.
1946 Return true if successful. */
1947 static bool
1948 copy_internal (char const *src_name, char const *dst_name,
1949 int dst_dirfd, char const *dst_relname,
1950 int nonexistent_dst,
1951 struct stat const *parent,
1952 struct dir_list *ancestors,
1953 const struct cp_options *x,
1954 bool command_line_arg,
1955 bool *first_dir_created_per_command_line_arg,
1956 bool *copy_into_self,
1957 bool *rename_succeeded)
1959 struct stat src_sb;
1960 struct stat dst_sb;
1961 mode_t src_mode IF_LINT ( = 0);
1962 mode_t dst_mode IF_LINT ( = 0);
1963 mode_t dst_mode_bits;
1964 mode_t omitted_permissions;
1965 bool restore_dst_mode = false;
1966 char *earlier_file = NULL;
1967 char *dst_backup = NULL;
1968 bool delayed_ok;
1969 bool copied_as_regular = false;
1970 bool dest_is_symlink = false;
1971 bool have_dst_lstat = false;
1973 /* Whether the destination is (or was) known to be new, updated as
1974 more info comes in. This may become true if the destination is a
1975 dangling symlink, in contexts where dangling symlinks should be
1976 treated the same as nonexistent files. */
1977 bool new_dst = 0 < nonexistent_dst;
1979 *copy_into_self = false;
1981 int rename_errno = x->rename_errno;
1982 if (x->move_mode)
1984 if (rename_errno < 0)
1985 rename_errno = (renameatu (AT_FDCWD, src_name, dst_dirfd, dst_relname,
1986 RENAME_NOREPLACE)
1987 ? errno : 0);
1988 nonexistent_dst = *rename_succeeded = new_dst = rename_errno == 0;
1991 if (rename_errno == 0
1992 ? !x->last_file
1993 : rename_errno != EEXIST || x->interactive != I_ALWAYS_NO)
1995 char const *name = rename_errno == 0 ? dst_name : src_name;
1996 int dirfd = rename_errno == 0 ? dst_dirfd : AT_FDCWD;
1997 char const *relname = rename_errno == 0 ? dst_relname : src_name;
1998 int fstatat_flags
1999 = x->dereference == DEREF_NEVER ? AT_SYMLINK_NOFOLLOW : 0;
2000 if (follow_fstatat (dirfd, relname, &src_sb, fstatat_flags) != 0)
2002 error (0, errno, _("cannot stat %s"), quoteaf (name));
2003 return false;
2006 src_mode = src_sb.st_mode;
2008 if (S_ISDIR (src_mode) && !x->recursive)
2010 error (0, 0, ! x->install_mode /* cp */
2011 ? _("-r not specified; omitting directory %s")
2012 : _("omitting directory %s"),
2013 quoteaf (src_name));
2014 return false;
2017 #ifdef lint
2018 else
2020 assert (x->move_mode);
2021 memset (&src_sb, 0, sizeof src_sb);
2023 #endif
2025 /* Detect the case in which the same source file appears more than
2026 once on the command line and no backup option has been selected.
2027 If so, simply warn and don't copy it the second time.
2028 This check is enabled only if x->src_info is non-NULL. */
2029 if (command_line_arg && x->src_info)
2031 if ( ! S_ISDIR (src_mode)
2032 && x->backup_type == no_backups
2033 && seen_file (x->src_info, src_name, &src_sb))
2035 error (0, 0, _("warning: source file %s specified more than once"),
2036 quoteaf (src_name));
2037 return true;
2040 record_file (x->src_info, src_name, &src_sb);
2043 bool dereference = should_dereference (x, command_line_arg);
2045 if (nonexistent_dst <= 0)
2047 if (! (rename_errno == EEXIST && x->interactive == I_ALWAYS_NO))
2049 /* Regular files can be created by writing through symbolic
2050 links, but other files cannot. So use stat on the
2051 destination when copying a regular file, and lstat otherwise.
2052 However, if we intend to unlink or remove the destination
2053 first, use lstat, since a copy won't actually be made to the
2054 destination in that case. */
2055 bool use_lstat
2056 = ((! S_ISREG (src_mode)
2057 && (! x->copy_as_regular
2058 || S_ISDIR (src_mode) || S_ISLNK (src_mode)))
2059 || x->move_mode || x->symbolic_link || x->hard_link
2060 || x->backup_type != no_backups
2061 || x->unlink_dest_before_opening);
2062 int fstatat_flags = use_lstat ? AT_SYMLINK_NOFOLLOW : 0;
2063 if (!use_lstat && nonexistent_dst < 0)
2064 new_dst = true;
2065 else if (follow_fstatat (dst_dirfd, dst_relname, &dst_sb,
2066 fstatat_flags)
2067 == 0)
2069 have_dst_lstat = use_lstat;
2070 rename_errno = EEXIST;
2072 else
2074 if (errno == ELOOP && x->unlink_dest_after_failed_open)
2075 /* leave new_dst=false so we unlink later. */;
2076 else if (errno != ENOENT)
2078 error (0, errno, _("cannot stat %s"), quoteaf (dst_name));
2079 return false;
2081 else
2082 new_dst = true;
2086 if (rename_errno == EEXIST)
2088 bool return_now = false;
2090 if (x->interactive != I_ALWAYS_NO
2091 && ! same_file_ok (src_name, &src_sb, dst_dirfd, dst_relname,
2092 &dst_sb, x, &return_now))
2094 error (0, 0, _("%s and %s are the same file"),
2095 quoteaf_n (0, src_name), quoteaf_n (1, dst_name));
2096 return false;
2099 if (x->update && !S_ISDIR (src_mode))
2101 /* When preserving timestamps (but not moving within a file
2102 system), don't worry if the destination timestamp is
2103 less than the source merely because of timestamp
2104 truncation. */
2105 int options = ((x->preserve_timestamps
2106 && ! (x->move_mode
2107 && dst_sb.st_dev == src_sb.st_dev))
2108 ? UTIMECMP_TRUNCATE_SOURCE
2109 : 0);
2111 if (0 <= utimecmpat (dst_dirfd, dst_relname, &dst_sb,
2112 &src_sb, options))
2114 /* We're using --update and the destination is not older
2115 than the source, so do not copy or move. Pretend the
2116 rename succeeded, so the caller (if it's mv) doesn't
2117 end up removing the source file. */
2118 if (rename_succeeded)
2119 *rename_succeeded = true;
2121 /* However, we still must record that we've processed
2122 this src/dest pair, in case this source file is
2123 hard-linked to another one. In that case, we'll use
2124 the mapping information to link the corresponding
2125 destination names. */
2126 earlier_file = remember_copied (dst_relname, src_sb.st_ino,
2127 src_sb.st_dev);
2128 if (earlier_file)
2130 /* Note we currently replace DST_NAME unconditionally,
2131 even if it was a newer separate file. */
2132 if (! create_hard_link (NULL, dst_dirfd, earlier_file,
2133 dst_name, dst_dirfd, dst_relname,
2134 true,
2135 x->verbose, dereference))
2137 goto un_backup;
2141 return true;
2145 /* When there is an existing destination file, we may end up
2146 returning early, and hence not copying/moving the file.
2147 This may be due to an interactive 'negative' reply to the
2148 prompt about the existing file. It may also be due to the
2149 use of the --no-clobber option.
2151 cp and mv treat -i and -f differently. */
2152 if (x->move_mode)
2154 if (abandon_move (x, dst_name, dst_dirfd, dst_relname, &dst_sb))
2156 /* Pretend the rename succeeded, so the caller (mv)
2157 doesn't end up removing the source file. */
2158 if (rename_succeeded)
2159 *rename_succeeded = true;
2160 return true;
2163 else
2165 if (! S_ISDIR (src_mode)
2166 && (x->interactive == I_ALWAYS_NO
2167 || (x->interactive == I_ASK_USER
2168 && ! overwrite_ok (x, dst_name, dst_dirfd,
2169 dst_relname, &dst_sb))))
2170 return true;
2173 if (return_now)
2174 return true;
2176 if (!S_ISDIR (dst_sb.st_mode))
2178 if (S_ISDIR (src_mode))
2180 if (x->move_mode && x->backup_type != no_backups)
2182 /* Moving a directory onto an existing
2183 non-directory is ok only with --backup. */
2185 else
2187 error (0, 0,
2188 _("cannot overwrite non-directory %s with directory %s"),
2189 quoteaf_n (0, dst_name), quoteaf_n (1, src_name));
2190 return false;
2194 /* Don't let the user destroy their data, even if they try hard:
2195 This mv command must fail (likewise for cp):
2196 rm -rf a b c; mkdir a b c; touch a/f b/f; mv a/f b/f c
2197 Otherwise, the contents of b/f would be lost.
2198 In the case of 'cp', b/f would be lost if the user simulated
2199 a move using cp and rm.
2200 Note that it works fine if you use --backup=numbered. */
2201 if (command_line_arg
2202 && x->backup_type != numbered_backups
2203 && seen_file (x->dest_info, dst_relname, &dst_sb))
2205 error (0, 0,
2206 _("will not overwrite just-created %s with %s"),
2207 quoteaf_n (0, dst_name), quoteaf_n (1, src_name));
2208 return false;
2212 if (!S_ISDIR (src_mode))
2214 if (S_ISDIR (dst_sb.st_mode))
2216 if (x->move_mode && x->backup_type != no_backups)
2218 /* Moving a non-directory onto an existing
2219 directory is ok only with --backup. */
2221 else
2223 error (0, 0,
2224 _("cannot overwrite directory %s with non-directory"),
2225 quoteaf (dst_name));
2226 return false;
2231 if (x->move_mode)
2233 /* Don't allow user to move a directory onto a non-directory. */
2234 if (S_ISDIR (src_sb.st_mode) && !S_ISDIR (dst_sb.st_mode)
2235 && x->backup_type == no_backups)
2237 error (0, 0,
2238 _("cannot move directory onto non-directory: %s -> %s"),
2239 quotef_n (0, src_name), quotef_n (0, dst_name));
2240 return false;
2244 char const *srcbase;
2245 if (x->backup_type != no_backups
2246 /* Don't try to back up a destination if the last
2247 component of src_name is "." or "..". */
2248 && ! dot_or_dotdot (srcbase = last_component (src_name))
2249 /* Create a backup of each destination directory in move mode,
2250 but not in copy mode. FIXME: it might make sense to add an
2251 option to suppress backup creation also for move mode.
2252 That would let one use mv to merge new content into an
2253 existing hierarchy. */
2254 && (x->move_mode || ! S_ISDIR (dst_sb.st_mode)))
2256 /* Fail if creating the backup file would likely destroy
2257 the source file. Otherwise, the commands:
2258 cd /tmp; rm -f a a~; : > a; echo A > a~; cp --b=simple a~ a
2259 would leave two zero-length files: a and a~. */
2260 if (x->backup_type != numbered_backups
2261 && source_is_dst_backup (srcbase, &src_sb,
2262 dst_dirfd, dst_relname))
2264 char const *fmt;
2265 fmt = (x->move_mode
2266 ? _("backing up %s might destroy source; %s not moved")
2267 : _("backing up %s might destroy source; %s not copied"));
2268 error (0, 0, fmt,
2269 quoteaf_n (0, dst_name),
2270 quoteaf_n (1, src_name));
2271 return false;
2274 char *tmp_backup = backup_file_rename (dst_dirfd, dst_relname,
2275 x->backup_type);
2277 /* FIXME: use fts:
2278 Using alloca for a file name that may be arbitrarily
2279 long is not recommended. In fact, even forming such a name
2280 should be discouraged. Eventually, this code will be rewritten
2281 to use fts, so using alloca here will be less of a problem. */
2282 if (tmp_backup)
2284 idx_t dirlen = dst_relname - dst_name;
2285 idx_t backupsize = strlen (tmp_backup) + 1;
2286 dst_backup = alloca (dirlen + backupsize);
2287 memcpy (mempcpy (dst_backup, dst_name, dirlen),
2288 tmp_backup, backupsize);
2289 free (tmp_backup);
2291 else if (errno != ENOENT)
2293 error (0, errno, _("cannot backup %s"), quoteaf (dst_name));
2294 return false;
2296 new_dst = true;
2298 else if (! S_ISDIR (dst_sb.st_mode)
2299 /* Never unlink dst_name when in move mode. */
2300 && ! x->move_mode
2301 && (x->unlink_dest_before_opening
2302 || (x->data_copy_required
2303 && ((x->preserve_links && 1 < dst_sb.st_nlink)
2304 || (x->dereference == DEREF_NEVER
2305 && ! S_ISREG (src_sb.st_mode))))
2308 if (unlinkat (dst_dirfd, dst_relname, 0) != 0 && errno != ENOENT)
2310 error (0, errno, _("cannot remove %s"), quoteaf (dst_name));
2311 return false;
2313 new_dst = true;
2314 if (x->verbose)
2315 printf (_("removed %s\n"), quoteaf (dst_name));
2320 /* Ensure we don't try to copy through a symlink that was
2321 created by a prior call to this function. */
2322 if (command_line_arg
2323 && x->dest_info
2324 && ! x->move_mode
2325 && x->backup_type == no_backups)
2327 bool lstat_ok = true;
2328 struct stat tmp_buf;
2329 struct stat *dst_lstat_sb;
2331 /* If we did not follow symlinks above, good: use that data.
2332 Otherwise, call lstatat here, in case dst_name is a symlink. */
2333 if (have_dst_lstat)
2334 dst_lstat_sb = &dst_sb;
2335 else
2337 if (lstatat (dst_dirfd, dst_relname, &tmp_buf) == 0)
2338 dst_lstat_sb = &tmp_buf;
2339 else
2340 lstat_ok = false;
2343 /* Never copy through a symlink we've just created. */
2344 if (lstat_ok
2345 && S_ISLNK (dst_lstat_sb->st_mode)
2346 && seen_file (x->dest_info, dst_relname, dst_lstat_sb))
2348 error (0, 0,
2349 _("will not copy %s through just-created symlink %s"),
2350 quoteaf_n (0, src_name), quoteaf_n (1, dst_name));
2351 return false;
2355 /* If the source is a directory, we don't always create the destination
2356 directory. So --verbose should not announce anything until we're
2357 sure we'll create a directory. Also don't announce yet when moving
2358 so we can distinguish renames versus copies. */
2359 if (x->verbose && !x->move_mode && !S_ISDIR (src_mode))
2360 emit_verbose (src_name, dst_name, dst_backup);
2362 /* Associate the destination file name with the source device and inode
2363 so that if we encounter a matching dev/ino pair in the source tree
2364 we can arrange to create a hard link between the corresponding names
2365 in the destination tree.
2367 When using the --link (-l) option, there is no need to take special
2368 measures, because (barring race conditions) files that are hard-linked
2369 in the source tree will also be hard-linked in the destination tree.
2371 Sometimes, when preserving links, we have to record dev/ino even
2372 though st_nlink == 1:
2373 - when in move_mode, since we may be moving a group of N hard-linked
2374 files (via two or more command line arguments) to a different
2375 partition; the links may be distributed among the command line
2376 arguments (possibly hierarchies) so that the link count of
2377 the final, once-linked source file is reduced to 1 when it is
2378 considered below. But in this case (for mv) we don't need to
2379 incur the expense of recording the dev/ino => name mapping; all we
2380 really need is a lookup, to see if the dev/ino pair has already
2381 been copied.
2382 - when using -H and processing a command line argument;
2383 that command line argument could be a symlink pointing to another
2384 command line argument. With 'cp -H --preserve=link', we hard-link
2385 those two destination files.
2386 - likewise for -L except that it applies to all files, not just
2387 command line arguments.
2389 Also, with --recursive, record dev/ino of each command-line directory.
2390 We'll use that info to detect this problem: cp -R dir dir. */
2392 if (rename_errno == 0)
2393 earlier_file = NULL;
2394 else if (x->recursive && S_ISDIR (src_mode))
2396 if (command_line_arg)
2397 earlier_file = remember_copied (dst_relname,
2398 src_sb.st_ino, src_sb.st_dev);
2399 else
2400 earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev);
2402 else if (x->move_mode && src_sb.st_nlink == 1)
2404 earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev);
2406 else if (x->preserve_links
2407 && !x->hard_link
2408 && (1 < src_sb.st_nlink
2409 || (command_line_arg
2410 && x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
2411 || x->dereference == DEREF_ALWAYS))
2413 earlier_file = remember_copied (dst_relname,
2414 src_sb.st_ino, src_sb.st_dev);
2417 /* Did we copy this inode somewhere else (in this command line argument)
2418 and therefore this is a second hard link to the inode? */
2420 if (earlier_file)
2422 /* Avoid damaging the destination file system by refusing to preserve
2423 hard-linked directories (which are found at least in Netapp snapshot
2424 directories). */
2425 if (S_ISDIR (src_mode))
2427 /* If src_name and earlier_file refer to the same directory entry,
2428 then warn about copying a directory into itself. */
2429 if (same_nameat (AT_FDCWD, src_name, dst_dirfd, earlier_file))
2431 error (0, 0, _("cannot copy a directory, %s, into itself, %s"),
2432 quoteaf_n (0, top_level_src_name),
2433 quoteaf_n (1, top_level_dst_name));
2434 *copy_into_self = true;
2435 goto un_backup;
2437 else if (same_nameat (dst_dirfd, dst_relname,
2438 dst_dirfd, earlier_file))
2440 error (0, 0, _("warning: source directory %s "
2441 "specified more than once"),
2442 quoteaf (top_level_src_name));
2443 /* In move mode, if a previous rename succeeded, then
2444 we won't be in this path as the source is missing. If the
2445 rename previously failed, then that has been handled, so
2446 pretend this attempt succeeded so the source isn't removed. */
2447 if (x->move_mode && rename_succeeded)
2448 *rename_succeeded = true;
2449 /* We only do backups in move mode, and for non directories.
2450 So just ignore this repeated entry. */
2451 return true;
2453 else if (x->dereference == DEREF_ALWAYS
2454 || (command_line_arg
2455 && x->dereference == DEREF_COMMAND_LINE_ARGUMENTS))
2457 /* This happens when e.g., encountering a directory for the
2458 second or subsequent time via symlinks when cp is invoked
2459 with -R and -L. E.g.,
2460 rm -rf a b c d; mkdir a b c d; ln -s ../c a; ln -s ../c b;
2461 cp -RL a b d
2464 else
2466 char *earlier = subst_suffix (dst_name, dst_relname,
2467 earlier_file);
2468 error (0, 0, _("will not create hard link %s to directory %s"),
2469 quoteaf_n (0, dst_name), quoteaf_n (1, earlier));
2470 free (earlier);
2471 goto un_backup;
2474 else
2476 if (! create_hard_link (NULL, dst_dirfd, earlier_file,
2477 dst_name, dst_dirfd, dst_relname,
2478 true, x->verbose, dereference))
2479 goto un_backup;
2481 return true;
2485 if (x->move_mode)
2487 if (rename_errno == EEXIST)
2488 rename_errno = ((renameat (AT_FDCWD, src_name, dst_dirfd, dst_relname)
2489 == 0)
2490 ? 0 : errno);
2492 if (rename_errno == 0)
2494 if (x->verbose)
2496 printf (_("renamed "));
2497 emit_verbose (src_name, dst_name, dst_backup);
2500 if (x->set_security_context)
2502 /* -Z failures are only warnings currently. */
2503 (void) set_file_security_ctx (dst_name, true, x);
2506 if (rename_succeeded)
2507 *rename_succeeded = true;
2509 if (command_line_arg && !x->last_file)
2511 /* Record destination dev/ino/name, so that if we are asked
2512 to overwrite that file again, we can detect it and fail. */
2513 /* It's fine to use the _source_ stat buffer (src_sb) to get the
2514 _destination_ dev/ino, since the rename above can't have
2515 changed those, and 'mv' always uses lstat.
2516 We could limit it further by operating
2517 only on non-directories. */
2518 record_file (x->dest_info, dst_relname, &src_sb);
2521 return true;
2524 /* FIXME: someday, consider what to do when moving a directory into
2525 itself but when source and destination are on different devices. */
2527 /* This happens when attempting to rename a directory to a
2528 subdirectory of itself. */
2529 if (rename_errno == EINVAL)
2531 /* FIXME: this is a little fragile in that it relies on rename(2)
2532 failing with a specific errno value. Expect problems on
2533 non-POSIX systems. */
2534 error (0, 0, _("cannot move %s to a subdirectory of itself, %s"),
2535 quoteaf_n (0, top_level_src_name),
2536 quoteaf_n (1, top_level_dst_name));
2538 /* Note that there is no need to call forget_created here,
2539 (compare with the other calls in this file) since the
2540 destination directory didn't exist before. */
2542 *copy_into_self = true;
2543 /* FIXME-cleanup: Don't return true here; adjust mv.c accordingly.
2544 The only caller that uses this code (mv.c) ends up setting its
2545 exit status to nonzero when copy_into_self is nonzero. */
2546 return true;
2549 /* WARNING: there probably exist systems for which an inter-device
2550 rename fails with a value of errno not handled here.
2551 If/as those are reported, add them to the condition below.
2552 If this happens to you, please do the following and send the output
2553 to the bug-reporting address (e.g., in the output of cp --help):
2554 touch k; perl -e 'rename "k","/tmp/k" or print "$!(",$!+0,")\n"'
2555 where your current directory is on one partition and /tmp is the other.
2556 Also, please try to find the E* errno macro name corresponding to
2557 the diagnostic and parenthesized integer, and include that in your
2558 e-mail. One way to do that is to run a command like this
2559 find /usr/include/. -type f \
2560 | xargs grep 'define.*\<E[A-Z]*\>.*\<18\>' /dev/null
2561 where you'd replace '18' with the integer in parentheses that
2562 was output from the perl one-liner above.
2563 If necessary, of course, change '/tmp' to some other directory. */
2564 if (rename_errno != EXDEV)
2566 /* There are many ways this can happen due to a race condition.
2567 When something happens between the initial follow_fstatat and the
2568 subsequent rename, we can get many different types of errors.
2569 For example, if the destination is initially a non-directory
2570 or non-existent, but it is created as a directory, the rename
2571 fails. If two 'mv' commands try to rename the same file at
2572 about the same time, one will succeed and the other will fail.
2573 If the permissions on the directory containing the source or
2574 destination file are made too restrictive, the rename will
2575 fail. Etc. */
2576 error (0, rename_errno,
2577 _("cannot move %s to %s"),
2578 quoteaf_n (0, src_name), quoteaf_n (1, dst_name));
2579 forget_created (src_sb.st_ino, src_sb.st_dev);
2580 return false;
2583 /* The rename attempt has failed. Remove any existing destination
2584 file so that a cross-device 'mv' acts as if it were really using
2585 the rename syscall. Note both src and dst must both be directories
2586 or not, and this is enforced above. Therefore we check the src_mode
2587 and operate on dst_name here as a tighter constraint and also because
2588 src_mode is readily available here. */
2589 if ((unlinkat (dst_dirfd, dst_relname,
2590 S_ISDIR (src_mode) ? AT_REMOVEDIR : 0)
2591 != 0)
2592 && errno != ENOENT)
2594 error (0, errno,
2595 _("inter-device move failed: %s to %s; unable to remove target"),
2596 quoteaf_n (0, src_name), quoteaf_n (1, dst_name));
2597 forget_created (src_sb.st_ino, src_sb.st_dev);
2598 return false;
2601 if (x->verbose && !S_ISDIR (src_mode))
2603 printf (_("copied "));
2604 emit_verbose (src_name, dst_name, dst_backup);
2606 new_dst = true;
2609 /* If the ownership might change, or if it is a directory (whose
2610 special mode bits may change after the directory is created),
2611 omit some permissions at first, so unauthorized users cannot nip
2612 in before the file is ready. */
2613 dst_mode_bits = (x->set_mode ? x->mode : src_mode) & CHMOD_MODE_BITS;
2614 omitted_permissions =
2615 (dst_mode_bits
2616 & (x->preserve_ownership ? S_IRWXG | S_IRWXO
2617 : S_ISDIR (src_mode) ? S_IWGRP | S_IWOTH
2618 : 0));
2620 delayed_ok = true;
2622 /* If required, set the default security context for new files.
2623 Also for existing files this is used as a reference
2624 when copying the context with --preserve=context.
2625 FIXME: Do we need to consider dst_mode_bits here? */
2626 if (! set_process_security_ctx (src_name, dst_name, src_mode, new_dst, x))
2627 return false;
2629 if (S_ISDIR (src_mode))
2631 struct dir_list *dir;
2633 /* If this directory has been copied before during the
2634 recursion, there is a symbolic link to an ancestor
2635 directory of the symbolic link. It is impossible to
2636 continue to copy this, unless we've got an infinite file system. */
2638 if (is_ancestor (&src_sb, ancestors))
2640 error (0, 0, _("cannot copy cyclic symbolic link %s"),
2641 quoteaf (src_name));
2642 goto un_backup;
2645 /* Insert the current directory in the list of parents. */
2647 dir = alloca (sizeof *dir);
2648 dir->parent = ancestors;
2649 dir->ino = src_sb.st_ino;
2650 dir->dev = src_sb.st_dev;
2652 if (new_dst || !S_ISDIR (dst_sb.st_mode))
2654 /* POSIX says mkdir's behavior is implementation-defined when
2655 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
2656 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
2657 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
2658 mode_t mode = dst_mode_bits & ~omitted_permissions;
2659 if (mkdirat (dst_dirfd, dst_relname, mode) != 0)
2661 error (0, errno, _("cannot create directory %s"),
2662 quoteaf (dst_name));
2663 goto un_backup;
2666 /* We need search and write permissions to the new directory
2667 for writing the directory's contents. Check if these
2668 permissions are there. */
2670 if (lstatat (dst_dirfd, dst_relname, &dst_sb) != 0)
2672 error (0, errno, _("cannot stat %s"), quoteaf (dst_name));
2673 goto un_backup;
2675 else if ((dst_sb.st_mode & S_IRWXU) != S_IRWXU)
2677 /* Make the new directory searchable and writable. */
2679 dst_mode = dst_sb.st_mode;
2680 restore_dst_mode = true;
2682 if (lchmodat (dst_dirfd, dst_relname, dst_mode | S_IRWXU) != 0)
2684 error (0, errno, _("setting permissions for %s"),
2685 quoteaf (dst_name));
2686 goto un_backup;
2690 /* Record the created directory's inode and device numbers into
2691 the search structure, so that we can avoid copying it again.
2692 Do this only for the first directory that is created for each
2693 source command line argument. */
2694 if (!*first_dir_created_per_command_line_arg)
2696 remember_copied (dst_relname, dst_sb.st_ino, dst_sb.st_dev);
2697 *first_dir_created_per_command_line_arg = true;
2700 if (x->verbose)
2702 if (x->move_mode)
2703 printf (_("created directory %s\n"), quoteaf (dst_name));
2704 else
2705 emit_verbose (src_name, dst_name, NULL);
2708 else
2710 omitted_permissions = 0;
2712 /* For directories, the process global context could be reset for
2713 descendents, so use it to set the context for existing dirs here.
2714 This will also give earlier indication of failure to set ctx. */
2715 if (x->set_security_context || x->preserve_security_context)
2716 if (! set_file_security_ctx (dst_name, false, x))
2718 if (x->require_preserve_context)
2719 goto un_backup;
2723 /* Decide whether to copy the contents of the directory. */
2724 if (x->one_file_system && parent && parent->st_dev != src_sb.st_dev)
2726 /* Here, we are crossing a file system boundary and cp's -x option
2727 is in effect: so don't copy the contents of this directory. */
2729 else
2731 /* Copy the contents of the directory. Don't just return if
2732 this fails -- otherwise, the failure to read a single file
2733 in a source directory would cause the containing destination
2734 directory not to have owner/perms set properly. */
2735 delayed_ok = copy_dir (src_name, dst_name, dst_dirfd, dst_relname,
2736 new_dst, &src_sb, dir, x,
2737 first_dir_created_per_command_line_arg,
2738 copy_into_self);
2741 else if (x->symbolic_link)
2743 dest_is_symlink = true;
2744 if (*src_name != '/')
2746 /* Check that DST_NAME denotes a file in the current directory. */
2747 struct stat dot_sb;
2748 struct stat dst_parent_sb;
2749 char *dst_parent;
2750 bool in_current_dir;
2752 dst_parent = dir_name (dst_relname);
2754 in_current_dir = ((dst_dirfd == AT_FDCWD && STREQ (".", dst_parent))
2755 /* If either stat call fails, it's ok not to report
2756 the failure and say dst_name is in the current
2757 directory. Other things will fail later. */
2758 || stat (".", &dot_sb) != 0
2759 || (statat (dst_dirfd, dst_parent, &dst_parent_sb)
2760 != 0)
2761 || SAME_INODE (dot_sb, dst_parent_sb));
2762 free (dst_parent);
2764 if (! in_current_dir)
2766 error (0, 0,
2767 _("%s: can make relative symbolic links only in current directory"),
2768 quotef (dst_name));
2769 goto un_backup;
2773 int err = force_symlinkat (src_name, dst_dirfd, dst_relname,
2774 x->unlink_dest_after_failed_open, -1);
2775 if (0 < err)
2777 error (0, err, _("cannot create symbolic link %s to %s"),
2778 quoteaf_n (0, dst_name), quoteaf_n (1, src_name));
2779 goto un_backup;
2783 /* POSIX 2008 states that it is implementation-defined whether
2784 link() on a symlink creates a hard-link to the symlink, or only
2785 to the referent (effectively dereferencing the symlink) (POSIX
2786 2001 required the latter behavior, although many systems provided
2787 the former). Yet cp, invoked with '--link --no-dereference',
2788 should not follow the link. We can approximate the desired
2789 behavior by skipping this hard-link creating block and instead
2790 copying the symlink, via the 'S_ISLNK'- copying code below.
2792 Note gnulib's linkat module, guarantees that the symlink is not
2793 dereferenced. However its emulation currently doesn't maintain
2794 timestamps or ownership so we only call it when we know the
2795 emulation will not be needed. */
2796 else if (x->hard_link
2797 && !(! CAN_HARDLINK_SYMLINKS && S_ISLNK (src_mode)
2798 && x->dereference == DEREF_NEVER))
2800 bool replace = (x->unlink_dest_after_failed_open
2801 || x->interactive == I_ASK_USER);
2802 if (! create_hard_link (src_name, AT_FDCWD, src_name,
2803 dst_name, dst_dirfd, dst_relname,
2804 replace, false, dereference))
2805 goto un_backup;
2807 else if (S_ISREG (src_mode)
2808 || (x->copy_as_regular && !S_ISLNK (src_mode)))
2810 copied_as_regular = true;
2811 /* POSIX says the permission bits of the source file must be
2812 used as the 3rd argument in the open call. Historical
2813 practice passed all the source mode bits to 'open', but the extra
2814 bits were ignored, so it should be the same either way.
2816 This call uses DST_MODE_BITS, not SRC_MODE. These are
2817 normally the same, and the exception (where x->set_mode) is
2818 used only by 'install', which POSIX does not specify and
2819 where DST_MODE_BITS is what's wanted. */
2820 if (! copy_reg (src_name, dst_name, dst_dirfd, dst_relname,
2821 x, dst_mode_bits & S_IRWXUGO,
2822 omitted_permissions, &new_dst, &src_sb))
2823 goto un_backup;
2825 else if (S_ISFIFO (src_mode))
2827 /* Use mknodat, rather than mkfifoat, because the former preserves
2828 the special mode bits of a fifo on Solaris 10, while mkfifoat
2829 does not. But fall back on mkfifoat, because on some BSD systems,
2830 mknodat always fails when asked to create a FIFO. */
2831 mode_t mode = src_mode & ~omitted_permissions;
2832 if (mknodat (dst_dirfd, dst_relname, mode, 0) != 0)
2833 if (mkfifoat (dst_dirfd, dst_relname, mode & ~S_IFIFO) != 0)
2835 error (0, errno, _("cannot create fifo %s"), quoteaf (dst_name));
2836 goto un_backup;
2839 else if (S_ISBLK (src_mode) || S_ISCHR (src_mode) || S_ISSOCK (src_mode))
2841 mode_t mode = src_mode & ~omitted_permissions;
2842 if (mknodat (dst_dirfd, dst_relname, mode, src_sb.st_rdev) != 0)
2844 error (0, errno, _("cannot create special file %s"),
2845 quoteaf (dst_name));
2846 goto un_backup;
2849 else if (S_ISLNK (src_mode))
2851 char *src_link_val = areadlink_with_size (src_name, src_sb.st_size);
2852 dest_is_symlink = true;
2853 if (src_link_val == NULL)
2855 error (0, errno, _("cannot read symbolic link %s"),
2856 quoteaf (src_name));
2857 goto un_backup;
2860 int symlink_err = force_symlinkat (src_link_val, dst_dirfd, dst_relname,
2861 x->unlink_dest_after_failed_open, -1);
2862 if (0 < symlink_err && x->update && !new_dst && S_ISLNK (dst_sb.st_mode)
2863 && dst_sb.st_size == strlen (src_link_val))
2865 /* See if the destination is already the desired symlink.
2866 FIXME: This behavior isn't documented, and seems wrong
2867 in some cases, e.g., if the destination symlink has the
2868 wrong ownership, permissions, or timestamps. */
2869 char *dest_link_val =
2870 areadlinkat_with_size (dst_dirfd, dst_relname, dst_sb.st_size);
2871 if (dest_link_val)
2873 if (STREQ (dest_link_val, src_link_val))
2874 symlink_err = 0;
2875 free (dest_link_val);
2878 free (src_link_val);
2879 if (0 < symlink_err)
2881 error (0, symlink_err, _("cannot create symbolic link %s"),
2882 quoteaf (dst_name));
2883 goto un_backup;
2886 if (x->preserve_security_context)
2887 restore_default_fscreatecon_or_die ();
2889 if (x->preserve_ownership)
2891 /* Preserve the owner and group of the just-'copied'
2892 symbolic link, if possible. */
2893 if (HAVE_LCHOWN
2894 && (lchownat (dst_dirfd, dst_relname,
2895 src_sb.st_uid, src_sb.st_gid)
2896 != 0)
2897 && ! chown_failure_ok (x))
2899 error (0, errno, _("failed to preserve ownership for %s"),
2900 dst_name);
2901 if (x->require_preserve)
2902 goto un_backup;
2904 else
2906 /* Can't preserve ownership of symlinks.
2907 FIXME: maybe give a warning or even error for symlinks
2908 in directories with the sticky bit set -- there, not
2909 preserving owner/group is a potential security problem. */
2913 else
2915 error (0, 0, _("%s has unknown file type"), quoteaf (src_name));
2916 goto un_backup;
2919 /* With -Z or --preserve=context, set the context for existing files.
2920 Note this is done already for copy_reg() for reasons described therein. */
2921 if (!new_dst && !x->copy_as_regular && !S_ISDIR (src_mode)
2922 && (x->set_security_context || x->preserve_security_context))
2924 if (! set_file_security_ctx (dst_name, false, x))
2926 if (x->require_preserve_context)
2927 goto un_backup;
2931 if (command_line_arg && x->dest_info)
2933 /* Now that the destination file is very likely to exist,
2934 add its info to the set. */
2935 struct stat sb;
2936 if (lstatat (dst_dirfd, dst_relname, &sb) == 0)
2937 record_file (x->dest_info, dst_relname, &sb);
2940 /* If we've just created a hard-link due to cp's --link option,
2941 we're done. */
2942 if (x->hard_link && ! S_ISDIR (src_mode)
2943 && !(! CAN_HARDLINK_SYMLINKS && S_ISLNK (src_mode)
2944 && x->dereference == DEREF_NEVER))
2945 return delayed_ok;
2947 if (copied_as_regular)
2948 return delayed_ok;
2950 /* POSIX says that 'cp -p' must restore the following:
2951 - permission bits
2952 - setuid, setgid bits
2953 - owner and group
2954 If it fails to restore any of those, we may give a warning but
2955 the destination must not be removed.
2956 FIXME: implement the above. */
2958 /* Adjust the times (and if possible, ownership) for the copy.
2959 chown turns off set[ug]id bits for non-root,
2960 so do the chmod last. */
2962 if (x->preserve_timestamps)
2964 struct timespec timespec[2];
2965 timespec[0] = get_stat_atime (&src_sb);
2966 timespec[1] = get_stat_mtime (&src_sb);
2968 int utimensat_flags = dest_is_symlink ? AT_SYMLINK_NOFOLLOW : 0;
2969 if (utimensat (dst_dirfd, dst_relname, timespec, utimensat_flags) != 0)
2971 error (0, errno, _("preserving times for %s"), quoteaf (dst_name));
2972 if (x->require_preserve)
2973 return false;
2977 /* Avoid calling chown if we know it's not necessary. */
2978 if (!dest_is_symlink && x->preserve_ownership
2979 && (new_dst || !SAME_OWNER_AND_GROUP (src_sb, dst_sb)))
2981 switch (set_owner (x, dst_name, dst_dirfd, dst_relname, -1,
2982 &src_sb, new_dst, &dst_sb))
2984 case -1:
2985 return false;
2987 case 0:
2988 src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX);
2989 break;
2993 /* Set xattrs after ownership as changing owners will clear capabilities. */
2994 if (x->preserve_xattr && ! copy_attr (src_name, -1, dst_name, -1, x)
2995 && x->require_preserve_xattr)
2996 return false;
2998 /* The operations beyond this point may dereference a symlink. */
2999 if (dest_is_symlink)
3000 return delayed_ok;
3002 set_author (dst_name, -1, &src_sb);
3004 if (x->preserve_mode || x->move_mode)
3006 if (copy_acl (src_name, -1, dst_name, -1, src_mode) != 0
3007 && x->require_preserve)
3008 return false;
3010 else if (x->set_mode)
3012 if (set_acl (dst_name, -1, x->mode) != 0)
3013 return false;
3015 else if (x->explicit_no_preserve_mode && new_dst)
3017 int default_permissions = S_ISDIR (src_mode) || S_ISSOCK (src_mode)
3018 ? S_IRWXUGO : MODE_RW_UGO;
3019 if (set_acl (dst_name, -1, default_permissions & ~cached_umask ()) != 0)
3020 return false;
3022 else
3024 if (omitted_permissions)
3026 omitted_permissions &= ~ cached_umask ();
3028 if (omitted_permissions && !restore_dst_mode)
3030 /* Permissions were deliberately omitted when the file
3031 was created due to security concerns. See whether
3032 they need to be re-added now. It'd be faster to omit
3033 the lstat, but deducing the current destination mode
3034 is tricky in the presence of implementation-defined
3035 rules for special mode bits. */
3036 if (new_dst && lstatat (dst_dirfd, dst_relname, &dst_sb) != 0)
3038 error (0, errno, _("cannot stat %s"), quoteaf (dst_name));
3039 return false;
3041 dst_mode = dst_sb.st_mode;
3042 if (omitted_permissions & ~dst_mode)
3043 restore_dst_mode = true;
3047 if (restore_dst_mode)
3049 if (lchmodat (dst_dirfd, dst_relname, dst_mode | omitted_permissions)
3050 != 0)
3052 error (0, errno, _("preserving permissions for %s"),
3053 quoteaf (dst_name));
3054 if (x->require_preserve)
3055 return false;
3060 return delayed_ok;
3062 un_backup:
3064 if (x->preserve_security_context)
3065 restore_default_fscreatecon_or_die ();
3067 /* We have failed to create the destination file.
3068 If we've just added a dev/ino entry via the remember_copied
3069 call above (i.e., unless we've just failed to create a hard link),
3070 remove the entry associating the source dev/ino with the
3071 destination file name, so we don't try to 'preserve' a link
3072 to a file we didn't create. */
3073 if (earlier_file == NULL)
3074 forget_created (src_sb.st_ino, src_sb.st_dev);
3076 if (dst_backup)
3078 char const *dst_relbackup = &dst_backup[dst_relname - dst_name];
3079 if (renameat (dst_dirfd, dst_relbackup, dst_dirfd, dst_relname) != 0)
3080 error (0, errno, _("cannot un-backup %s"), quoteaf (dst_name));
3081 else
3083 if (x->verbose)
3084 printf (_("%s -> %s (unbackup)\n"),
3085 quoteaf_n (0, dst_backup), quoteaf_n (1, dst_name));
3088 return false;
3091 ATTRIBUTE_PURE
3092 static bool
3093 valid_options (const struct cp_options *co)
3095 assert (VALID_BACKUP_TYPE (co->backup_type));
3096 assert (VALID_SPARSE_MODE (co->sparse_mode));
3097 assert (VALID_REFLINK_MODE (co->reflink_mode));
3098 assert (!(co->hard_link && co->symbolic_link));
3099 assert (!
3100 (co->reflink_mode == REFLINK_ALWAYS
3101 && co->sparse_mode != SPARSE_AUTO));
3102 return true;
3105 /* Copy the file SRC_NAME to the file DST_NAME aka DST_DIRFD+DST_RELNAME.
3106 If NONEXISTENT_DST is positive, DST_NAME does not exist even as a
3107 dangling symlink; if negative, it does not exist except possibly
3108 as a dangling symlink; if zero, its existence status is unknown.
3109 OPTIONS summarizes the command-line options.
3110 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
3111 same as) DST_NAME; otherwise, set clear it.
3112 If X->move_mode, set *RENAME_SUCCEEDED according to whether
3113 the source was simply renamed to the destination.
3114 Return true if successful. */
3116 extern bool
3117 copy (char const *src_name, char const *dst_name,
3118 int dst_dirfd, char const *dst_relname,
3119 int nonexistent_dst, const struct cp_options *options,
3120 bool *copy_into_self, bool *rename_succeeded)
3122 assert (valid_options (options));
3124 /* Record the file names: they're used in case of error, when copying
3125 a directory into itself. I don't like to make these tools do *any*
3126 extra work in the common case when that work is solely to handle
3127 exceptional cases, but in this case, I don't see a way to derive the
3128 top level source and destination directory names where they're used.
3129 An alternative is to use COPY_INTO_SELF and print the diagnostic
3130 from every caller -- but I don't want to do that. */
3131 top_level_src_name = src_name;
3132 top_level_dst_name = dst_name;
3134 bool first_dir_created_per_command_line_arg = false;
3135 return copy_internal (src_name, dst_name, dst_dirfd, dst_relname,
3136 nonexistent_dst, NULL, NULL,
3137 options, true,
3138 &first_dir_created_per_command_line_arg,
3139 copy_into_self, rename_succeeded);
3142 /* Set *X to the default options for a value of type struct cp_options. */
3144 extern void
3145 cp_options_default (struct cp_options *x)
3147 memset (x, 0, sizeof *x);
3148 #ifdef PRIV_FILE_CHOWN
3150 priv_set_t *pset = priv_allocset ();
3151 if (!pset)
3152 xalloc_die ();
3153 if (getppriv (PRIV_EFFECTIVE, pset) == 0)
3155 x->chown_privileges = priv_ismember (pset, PRIV_FILE_CHOWN);
3156 x->owner_privileges = priv_ismember (pset, PRIV_FILE_OWNER);
3158 priv_freeset (pset);
3160 #else
3161 x->chown_privileges = x->owner_privileges = (geteuid () == ROOT_UID);
3162 #endif
3163 x->rename_errno = -1;
3166 /* Return true if it's OK for chown to fail, where errno is
3167 the error number that chown failed with and X is the copying
3168 option set. */
3170 extern bool
3171 chown_failure_ok (struct cp_options const *x)
3173 /* If non-root uses -p, it's ok if we can't preserve ownership.
3174 But root probably wants to know, e.g. if NFS disallows it,
3175 or if the target system doesn't support file ownership. */
3177 return ((errno == EPERM || errno == EINVAL) && !x->chown_privileges);
3180 /* Similarly, return true if it's OK for chmod and similar operations
3181 to fail, where errno is the error number that chmod failed with and
3182 X is the copying option set. */
3184 static bool
3185 owner_failure_ok (struct cp_options const *x)
3187 return ((errno == EPERM || errno == EINVAL) && !x->owner_privileges);
3190 /* Return the user's umask, caching the result.
3192 FIXME: If the destination's parent directory has has a default ACL,
3193 some operating systems (e.g., GNU/Linux's "POSIX" ACLs) use that
3194 ACL's mask rather than the process umask. Currently, the callers
3195 of cached_umask incorrectly assume that this situation cannot occur. */
3196 extern mode_t
3197 cached_umask (void)
3199 static mode_t mask = (mode_t) -1;
3200 if (mask == (mode_t) -1)
3202 mask = umask (0);
3203 umask (mask);
3205 return mask;