1 /* copy.c -- core functions for copying files and directories
2 Copyright (C) 1989-2012 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 <http://www.gnu.org/licenses/>. */
17 /* Extracted from cp.c and librarified by Jim Meyering. */
22 #include <sys/ioctl.h>
23 #include <sys/types.h>
24 #include <selinux/selinux.h>
35 #include "backupfile.h"
36 #include "buffer-lcm.h"
37 #include "canonicalize.h"
40 #include "extent-scan.h"
46 #include "filenamecat.h"
47 #include "full-write.h"
49 #include "hash-triple.h"
50 #include "ignore-value.h"
51 #include "ioblksize.h"
55 #include "stat-size.h"
56 #include "stat-time.h"
59 #include "write-any-file.h"
60 #include "areadlink.h"
64 # include <attr/error_context.h>
65 # include <attr/libattr.h>
71 # define HAVE_FCHOWN false
72 # define fchown(fd, uid, gid) (-1)
76 # define HAVE_LCHOWN false
77 # define lchown(name, uid, gid) chown (name, uid, gid)
82 rpl_mkfifo (char const *file, mode_t mode)
87 # define mkfifo rpl_mkfifo
94 #define SAME_OWNER(A, B) ((A).st_uid == (B).st_uid)
95 #define SAME_GROUP(A, B) ((A).st_gid == (B).st_gid)
96 #define SAME_OWNER_AND_GROUP(A, B) (SAME_OWNER (A, B) && SAME_GROUP (A, B))
100 struct dir_list *parent;
105 /* Initial size of the cp.dest_info hash table. */
106 #define DEST_INFO_INITIAL_CAPACITY 61
108 static bool copy_internal (char const *src_name, char const *dst_name,
109 bool new_dst, dev_t device,
110 struct dir_list *ancestors,
111 const struct cp_options *x,
112 bool command_line_arg,
113 bool *first_dir_created_per_command_line_arg,
114 bool *copy_into_self,
115 bool *rename_succeeded);
116 static bool owner_failure_ok (struct cp_options const *x);
118 /* Pointers to the file names: they're used in the diagnostic that is issued
119 when we detect the user is trying to copy a directory into itself. */
120 static char const *top_level_src_name;
121 static char const *top_level_dst_name;
123 /* Set the timestamp of symlink, FILE, to TIMESPEC.
124 If this system lacks support for that, simply return 0. */
126 utimens_symlink (char const *file, struct timespec const *timespec)
128 int err = lutimens (file, timespec);
129 /* When configuring on a system with new headers and libraries, and
130 running on one with a kernel that is old enough to lack the syscall,
131 utimensat fails with ENOSYS. Ignore that. */
132 if (err && errno == ENOSYS)
137 /* Copy the regular file open on SRC_FD/SRC_NAME to DST_FD/DST_NAME,
138 honoring the MAKE_HOLES setting and using the BUF_SIZE-byte buffer
139 BUF for temporary storage. Copy no more than MAX_N_READ bytes.
140 Return true upon successful completion;
141 print a diagnostic and return false upon error.
142 Note that for best results, BUF should be "well"-aligned.
143 BUF must have sizeof(uintptr_t)-1 bytes of additional space
144 beyond BUF[BUF_SIZE-1].
145 Set *LAST_WRITE_MADE_HOLE to true if the final operation on
146 DEST_FD introduced a hole. Set *TOTAL_N_READ to the number of
149 sparse_copy (int src_fd, int dest_fd, char *buf, size_t buf_size,
151 char const *src_name, char const *dst_name,
152 uintmax_t max_n_read, off_t *total_n_read,
153 bool *last_write_made_hole)
155 *last_write_made_hole = false;
160 bool make_hole = false;
162 ssize_t n_read = read (src_fd, buf, MIN (max_n_read, buf_size));
167 error (0, errno, _("reading %s"), quote (src_name));
172 max_n_read -= n_read;
173 *total_n_read += n_read;
177 /* Sentinel required by is_nul(). */
180 typedef uintptr_t word;
181 /* Usually, buf[n_read] is not the byte just before a "word"
182 (aka uintptr_t) boundary. In that case, the word-oriented
183 test below (*wp++ == 0) would read some uninitialized bytes
184 after the sentinel. To avoid false-positive reports about
185 this condition (e.g., from a tool like valgrind), set the
186 remaining bytes -- to any value. */
187 memset (buf + n_read + 1, 0, sizeof (word) - 1);
190 if ((make_hole = is_nul (buf, n_read)))
192 if (lseek (dest_fd, n_read, SEEK_CUR) < 0)
194 error (0, errno, _("cannot lseek %s"), quote (dst_name));
203 if (full_write (dest_fd, buf, n) != n)
205 error (0, errno, _("writing %s"), quote (dst_name));
209 /* It is tempting to return early here upon a short read from a
210 regular file. That would save the final read syscall for each
211 file. Unfortunately that doesn't work for certain files in
212 /proc with linux kernels from at least 2.6.9 .. 2.6.29. */
215 *last_write_made_hole = make_hole;
221 /* Perform the O(1) btrfs clone operation, if possible.
222 Upon success, return 0. Otherwise, return -1 and set errno. */
224 clone_file (int dest_fd, int src_fd)
227 # undef BTRFS_IOCTL_MAGIC
228 # define BTRFS_IOCTL_MAGIC 0x94
229 # undef BTRFS_IOC_CLONE
230 # define BTRFS_IOC_CLONE _IOW (BTRFS_IOCTL_MAGIC, 9, int)
231 return ioctl (dest_fd, BTRFS_IOC_CLONE, src_fd);
240 /* Write N_BYTES zero bytes to file descriptor FD. Return true if successful.
241 Upon write failure, set errno and return false. */
243 write_zeros (int fd, uint64_t n_bytes)
246 static size_t nz = IO_BUFSIZE;
248 /* Attempt to use a relatively large calloc'd source buffer for
249 efficiency, but if that allocation fails, resort to a smaller
250 statically allocated one. */
253 static char fallback[1024];
254 zeros = calloc (nz, 1);
258 nz = sizeof fallback;
264 uint64_t n = MIN (nz, n_bytes);
265 if ((full_write (fd, zeros, n)) != n)
273 /* Perform an efficient extent copy, if possible. This avoids
274 the overhead of detecting holes in hole-introducing/preserving
275 copy, and thus makes copying sparse files much more efficient.
276 Upon a successful copy, return true. If the initial extent scan
277 fails, set *NORMAL_COPY_REQUIRED to true and return false.
278 Upon any other failure, set *NORMAL_COPY_REQUIRED to false and
281 extent_copy (int src_fd, int dest_fd, char *buf, size_t buf_size,
282 off_t src_total_size, enum Sparse_type sparse_mode,
283 char const *src_name, char const *dst_name,
284 bool *require_normal_copy)
286 struct extent_scan scan;
287 off_t last_ext_start = 0;
288 uint64_t last_ext_len = 0;
290 /* Keep track of the output position.
291 We may need this at the end, for a final ftruncate. */
294 extent_scan_init (src_fd, &scan);
296 *require_normal_copy = false;
297 bool wrote_hole_at_eof = true;
300 bool ok = extent_scan_read (&scan);
303 if (scan.hit_final_extent)
306 if (scan.initial_scan_failed)
308 *require_normal_copy = true;
312 error (0, errno, _("%s: failed to get extents info"),
318 bool empty_extent = false;
319 for (i = 0; i < scan.ei_count || empty_extent; i++)
325 if (i < scan.ei_count)
327 ext_start = scan.ext_info[i].ext_logical;
328 ext_len = scan.ext_info[i].ext_length;
330 else /* empty extent at EOF. */
333 ext_start = last_ext_start + scan.ext_info[i].ext_length;
337 hole_size = ext_start - last_ext_start - last_ext_len;
339 wrote_hole_at_eof = false;
343 if (lseek (src_fd, ext_start, SEEK_SET) < 0)
345 error (0, errno, _("cannot lseek %s"), quote (src_name));
347 extent_scan_free (&scan);
351 if ((empty_extent && sparse_mode == SPARSE_ALWAYS)
352 || (!empty_extent && sparse_mode != SPARSE_NEVER))
354 if (lseek (dest_fd, ext_start, SEEK_SET) < 0)
356 error (0, errno, _("cannot lseek %s"), quote (dst_name));
359 wrote_hole_at_eof = true;
363 /* When not inducing holes and when there is a hole between
364 the end of the previous extent and the beginning of the
365 current one, write zeros to the destination file. */
366 off_t nzeros = hole_size;
368 nzeros = MIN (src_total_size - dest_pos, hole_size);
370 if (! write_zeros (dest_fd, nzeros))
372 error (0, errno, _("%s: write failed"), quote (dst_name));
376 dest_pos = MIN (src_total_size, ext_start);
380 last_ext_start = ext_start;
382 /* Treat an unwritten but allocated extent much like a hole.
383 I.E. don't read, but don't convert to a hole in the destination,
384 unless SPARSE_ALWAYS. */
385 /* For now, do not treat FIEMAP_EXTENT_UNWRITTEN specially,
386 because that (in combination with no sync) would lead to data
387 loss at least on XFS and ext4 when using 2.6.39-rc3 kernels. */
388 if (0 && (scan.ext_info[i].ext_flags & FIEMAP_EXTENT_UNWRITTEN))
392 if (ext_len == 0) /* The last extent is empty and processed. */
393 empty_extent = false;
398 empty_extent = false;
399 last_ext_len = ext_len;
401 if ( ! sparse_copy (src_fd, dest_fd, buf, buf_size,
402 sparse_mode == SPARSE_ALWAYS,
403 src_name, dst_name, ext_len, &n_read,
407 dest_pos = ext_start + n_read;
410 /* If the file ends with unwritten extents not accounted for in the
411 size, then skip processing them, and the associated redundant
412 read() calls which will always return 0. We will need to
413 remove this when we add fallocate() so that we can maintain
414 extents beyond the apparent size. */
415 if (dest_pos == src_total_size)
417 scan.hit_final_extent = true;
422 /* Release the space allocated to scan->ext_info. */
423 extent_scan_free (&scan);
426 while (! scan.hit_final_extent);
428 /* When the source file ends with a hole, we have to do a little more work,
429 since the above copied only up to and including the final extent.
430 In order to complete the copy, we may have to insert a hole or write
431 zeros in the destination corresponding to the source file's hole-at-EOF.
433 In addition, if the final extent was a block of zeros at EOF and we've
434 just converted them to a hole in the destination, we must call ftruncate
435 here in order to record the proper length in the destination. */
436 if ((dest_pos < src_total_size || wrote_hole_at_eof)
437 && (sparse_mode != SPARSE_NEVER
438 ? ftruncate (dest_fd, src_total_size)
439 : ! write_zeros (dest_fd, src_total_size - dest_pos)))
441 error (0, errno, _("failed to extend %s"), quote (dst_name));
448 /* FIXME: describe */
449 /* FIXME: rewrite this to use a hash table so we avoid the quadratic
450 performance hit that's probably noticeable only on trees deeper
451 than a few hundred levels. See use of active_dir_map in remove.c */
453 static bool _GL_ATTRIBUTE_PURE
454 is_ancestor (const struct stat *sb, const struct dir_list *ancestors)
456 while (ancestors != 0)
458 if (ancestors->ino == sb->st_ino && ancestors->dev == sb->st_dev)
460 ancestors = ancestors->parent;
466 errno_unsupported (int err)
468 return err == ENOTSUP || err == ENODATA;
473 copy_attr_error (struct error_context *ctx ATTRIBUTE_UNUSED,
474 char const *fmt, ...)
476 if (!errno_unsupported (errno))
481 /* use verror module to print error message */
483 verror (0, err, fmt, ap);
489 copy_attr_allerror (struct error_context *ctx ATTRIBUTE_UNUSED,
490 char const *fmt, ...)
495 /* use verror module to print error message */
497 verror (0, err, fmt, ap);
502 copy_attr_quote (struct error_context *ctx ATTRIBUTE_UNUSED, char const *str)
508 copy_attr_free (struct error_context *ctx ATTRIBUTE_UNUSED,
509 char const *str ATTRIBUTE_UNUSED)
513 /* If positive SRC_FD and DST_FD descriptors are passed,
514 then copy by fd, otherwise copy by name. */
517 copy_attr (char const *src_path, int src_fd,
518 char const *dst_path, int dst_fd, struct cp_options const *x)
521 bool all_errors = (!x->data_copy_required || x->require_preserve_xattr);
522 bool some_errors = (!all_errors && !x->reduce_diagnostics);
523 struct error_context ctx =
525 .error = all_errors ? copy_attr_allerror : copy_attr_error,
526 .quote = copy_attr_quote,
527 .quote_free = copy_attr_free
529 if (0 <= src_fd && 0 <= dst_fd)
530 ret = attr_copy_fd (src_path, src_fd, dst_path, dst_fd, 0,
531 (all_errors || some_errors ? &ctx : NULL));
533 ret = attr_copy_file (src_path, dst_path, 0,
534 (all_errors || some_errors ? &ctx : NULL));
538 #else /* USE_XATTR */
541 copy_attr (char const *src_path ATTRIBUTE_UNUSED,
542 int src_fd ATTRIBUTE_UNUSED,
543 char const *dst_path ATTRIBUTE_UNUSED,
544 int dst_fd ATTRIBUTE_UNUSED,
545 struct cp_options const *x ATTRIBUTE_UNUSED)
549 #endif /* USE_XATTR */
551 /* Read the contents of the directory SRC_NAME_IN, and recursively
552 copy the contents to DST_NAME_IN. NEW_DST is true if
553 DST_NAME_IN is a directory that was created previously in the
554 recursion. SRC_SB and ANCESTORS describe SRC_NAME_IN.
555 Set *COPY_INTO_SELF if SRC_NAME_IN is a parent of
556 (or the same as) DST_NAME_IN; otherwise, clear it.
557 Propagate *FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG from
558 caller to each invocation of copy_internal. Be careful to
559 pass the address of a temporary, and to update
560 *FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG only upon completion.
561 Return true if successful. */
564 copy_dir (char const *src_name_in, char const *dst_name_in, bool new_dst,
565 const struct stat *src_sb, struct dir_list *ancestors,
566 const struct cp_options *x,
567 bool *first_dir_created_per_command_line_arg,
568 bool *copy_into_self)
572 struct cp_options non_command_line_options = *x;
575 name_space = savedir (src_name_in);
576 if (name_space == NULL)
578 /* This diagnostic is a bit vague because savedir can fail in
579 several different ways. */
580 error (0, errno, _("cannot access %s"), quote (src_name_in));
584 /* For cp's -H option, dereference command line arguments, but do not
585 dereference symlinks that are found via recursive traversal. */
586 if (x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
587 non_command_line_options.dereference = DEREF_NEVER;
589 bool new_first_dir_created = false;
591 while (*namep != '\0')
593 bool local_copy_into_self;
594 char *src_name = file_name_concat (src_name_in, namep, NULL);
595 char *dst_name = file_name_concat (dst_name_in, namep, NULL);
596 bool first_dir_created = *first_dir_created_per_command_line_arg;
598 ok &= copy_internal (src_name, dst_name, new_dst, src_sb->st_dev,
599 ancestors, &non_command_line_options, false,
601 &local_copy_into_self, NULL);
602 *copy_into_self |= local_copy_into_self;
607 /* If we're copying into self, there's no point in continuing,
608 and in fact, that would even infloop, now that we record only
609 the first created directory per command line argument. */
610 if (local_copy_into_self)
613 new_first_dir_created |= first_dir_created;
614 namep += strlen (namep) + 1;
617 *first_dir_created_per_command_line_arg = new_first_dir_created;
622 /* Set the owner and owning group of DEST_DESC to the st_uid and
623 st_gid fields of SRC_SB. If DEST_DESC is undefined (-1), set
624 the owner and owning group of DST_NAME instead; for
625 safety prefer lchown if the system supports it since no
626 symbolic links should be involved. DEST_DESC must
627 refer to the same file as DEST_NAME if defined.
628 Upon failure to set both UID and GID, try to set only the GID.
629 NEW_DST is true if the file was newly created; otherwise,
630 DST_SB is the status of the destination.
631 Return 1 if the initial syscall succeeds, 0 if it fails but it's OK
632 not to preserve ownership, -1 otherwise. */
635 set_owner (const struct cp_options *x, char const *dst_name, int dest_desc,
636 struct stat const *src_sb, bool new_dst,
637 struct stat const *dst_sb)
639 uid_t uid = src_sb->st_uid;
640 gid_t gid = src_sb->st_gid;
642 /* Naively changing the ownership of an already-existing file before
643 changing its permissions would create a window of vulnerability if
644 the file's old permissions are too generous for the new owner and
645 group. Avoid the window by first changing to a restrictive
646 temporary mode if necessary. */
648 if (!new_dst && (x->preserve_mode || x->move_mode || x->set_mode))
650 mode_t old_mode = dst_sb->st_mode;
652 (x->preserve_mode || x->move_mode ? src_sb->st_mode : x->mode);
653 mode_t restrictive_temp_mode = old_mode & new_mode & S_IRWXU;
656 || (old_mode & CHMOD_MODE_BITS
657 & (~new_mode | S_ISUID | S_ISGID | S_ISVTX)))
658 && qset_acl (dst_name, dest_desc, restrictive_temp_mode) != 0)
660 if (! owner_failure_ok (x))
661 error (0, errno, _("clearing permissions for %s"),
663 return -x->require_preserve;
667 if (HAVE_FCHOWN && dest_desc != -1)
669 if (fchown (dest_desc, uid, gid) == 0)
671 if (errno == EPERM || errno == EINVAL)
673 /* We've failed to set *both*. Now, try to set just the group
674 ID, but ignore any failure here, and don't change errno. */
675 int saved_errno = errno;
676 ignore_value (fchown (dest_desc, -1, gid));
682 if (lchown (dst_name, uid, gid) == 0)
684 if (errno == EPERM || errno == EINVAL)
686 /* We've failed to set *both*. Now, try to set just the group
687 ID, but ignore any failure here, and don't change errno. */
688 int saved_errno = errno;
689 ignore_value (lchown (dst_name, -1, gid));
694 if (! chown_failure_ok (x))
696 error (0, errno, _("failed to preserve ownership for %s"),
698 if (x->require_preserve)
705 /* Set the st_author field of DEST_DESC to the st_author field of
706 SRC_SB. If DEST_DESC is undefined (-1), set the st_author field
707 of DST_NAME instead. DEST_DESC must refer to the same file as
708 DEST_NAME if defined. */
711 set_author (const char *dst_name, int dest_desc, const struct stat *src_sb)
713 #if HAVE_STRUCT_STAT_ST_AUTHOR
714 /* FIXME: Modify the following code so that it does not
715 follow symbolic links. */
717 /* Preserve the st_author field. */
718 file_t file = (dest_desc < 0
719 ? file_name_lookup (dst_name, 0, 0)
720 : getdport (dest_desc));
721 if (file == MACH_PORT_NULL)
722 error (0, errno, _("failed to lookup file %s"), quote (dst_name));
725 error_t err = file_chauthor (file, src_sb->st_author);
727 error (0, err, _("failed to preserve authorship for %s"),
729 mach_port_deallocate (mach_task_self (), file);
738 /* Change the file mode bits of the file identified by DESC or NAME to MODE.
739 Use DESC if DESC is valid and fchmod is available, NAME otherwise. */
742 fchmod_or_lchmod (int desc, char const *name, mode_t mode)
746 return fchmod (desc, mode);
748 return lchmod (name, mode);
751 #ifndef HAVE_STRUCT_STAT_ST_BLOCKS
752 # define HAVE_STRUCT_STAT_ST_BLOCKS 0
755 /* Use a heuristic to determine whether stat buffer SB comes from a file
756 with sparse blocks. If the file has fewer blocks than would normally
757 be needed for a file of its size, then at least one of the blocks in
758 the file is a hole. In that case, return true. */
760 is_probably_sparse (struct stat const *sb)
762 return (HAVE_STRUCT_STAT_ST_BLOCKS
763 && S_ISREG (sb->st_mode)
764 && ST_NBLOCKS (*sb) < sb->st_size / ST_NBLOCKSIZE);
768 /* Copy a regular file from SRC_NAME to DST_NAME.
769 If the source file contains holes, copies holes and blocks of zeros
770 in the source file as holes in the destination file.
771 (Holes are read as zeroes by the 'read' system call.)
772 When creating the destination, use DST_MODE & ~OMITTED_PERMISSIONS
773 as the third argument in the call to open, adding
774 OMITTED_PERMISSIONS after copying as needed.
775 X provides many option settings.
776 Return true if successful.
777 *NEW_DST is as in copy_internal.
778 SRC_SB is the result of calling XSTAT (aka stat) on SRC_NAME. */
781 copy_reg (char const *src_name, char const *dst_name,
782 const struct cp_options *x,
783 mode_t dst_mode, mode_t omitted_permissions, bool *new_dst,
784 struct stat const *src_sb)
787 char *buf_alloc = NULL;
788 char *name_alloc = NULL;
792 mode_t src_mode = src_sb->st_mode;
794 struct stat src_open_sb;
795 bool return_val = true;
796 bool data_copy_required = x->data_copy_required;
798 source_desc = open (src_name,
800 | (x->dereference == DEREF_NEVER ? O_NOFOLLOW : 0)));
803 error (0, errno, _("cannot open %s for reading"), quote (src_name));
807 if (fstat (source_desc, &src_open_sb) != 0)
809 error (0, errno, _("cannot fstat %s"), quote (src_name));
814 /* Compare the source dev/ino from the open file to the incoming,
815 saved ones obtained via a previous call to stat. */
816 if (! SAME_INODE (*src_sb, src_open_sb))
819 _("skipping file %s, as it was replaced while being copied"),
825 /* The semantics of the following open calls are mandated
826 by the specs for both cp and mv. */
830 O_WRONLY | O_BINARY | (x->data_copy_required ? O_TRUNC : 0);
831 dest_desc = open (dst_name, open_flags);
834 /* When using cp --preserve=context to copy to an existing destination,
835 use the default context rather than that of the source. Why?
836 1) the src context may prohibit writing, and
837 2) because it's more consistent to use the same context
838 that is used when the destination file doesn't already exist. */
839 if (x->preserve_security_context && 0 <= dest_desc)
841 bool all_errors = (!x->data_copy_required
842 || x->require_preserve_context);
843 bool some_errors = !all_errors && !x->reduce_diagnostics;
844 security_context_t con = NULL;
846 if (getfscreatecon (&con) < 0)
848 if (all_errors || (some_errors && !errno_unsupported (errno)))
849 error (0, errno, _("failed to get file system create context"));
850 if (x->require_preserve_context)
853 goto close_src_and_dst_desc;
859 if (fsetfilecon (dest_desc, con) < 0)
861 if (all_errors || (some_errors && !errno_unsupported (errno)))
863 _("failed to set the security context of %s to %s"),
864 quote_n (0, dst_name), quote_n (1, con));
865 if (x->require_preserve_context)
869 goto close_src_and_dst_desc;
876 if (dest_desc < 0 && x->unlink_dest_after_failed_open)
878 if (unlink (dst_name) != 0)
880 error (0, errno, _("cannot remove %s"), quote (dst_name));
885 printf (_("removed %s\n"), quote (dst_name));
887 /* Tell caller that the destination file was unlinked. */
894 int open_flags = O_WRONLY | O_CREAT | O_BINARY;
895 dest_desc = open (dst_name, open_flags | O_EXCL,
896 dst_mode & ~omitted_permissions);
899 /* When trying to copy through a dangling destination symlink,
900 the above open fails with EEXIST. If that happens, and
901 lstat'ing the DST_NAME shows that it is a symlink, then we
902 have a problem: trying to resolve this dangling symlink to
903 a directory/destination-entry pair is fundamentally racy,
904 so punt. If x->open_dangling_dest_symlink is set (cp sets
905 that when POSIXLY_CORRECT is set in the environment), simply
906 call open again, but without O_EXCL (potentially dangerous).
907 If not, fail with a diagnostic. These shenanigans are necessary
908 only when copying, i.e., not in move_mode. */
909 if (dest_desc < 0 && dest_errno == EEXIST && ! x->move_mode)
911 struct stat dangling_link_sb;
912 if (lstat (dst_name, &dangling_link_sb) == 0
913 && S_ISLNK (dangling_link_sb.st_mode))
915 if (x->open_dangling_dest_symlink)
917 dest_desc = open (dst_name, open_flags,
918 dst_mode & ~omitted_permissions);
923 error (0, 0, _("not writing through dangling symlink %s"),
931 /* Improve quality of diagnostic when a nonexistent dst_name
932 ends in a slash and open fails with errno == EISDIR. */
933 if (dest_desc < 0 && dest_errno == EISDIR
934 && *dst_name && dst_name[strlen (dst_name) - 1] == '/')
935 dest_errno = ENOTDIR;
939 omitted_permissions = 0;
944 error (0, dest_errno, _("cannot create regular file %s"),
950 if (fstat (dest_desc, &sb) != 0)
952 error (0, errno, _("cannot fstat %s"), quote (dst_name));
954 goto close_src_and_dst_desc;
957 /* --attributes-only overrides --reflink. */
958 if (data_copy_required && x->reflink_mode)
960 bool clone_ok = clone_file (dest_desc, source_desc) == 0;
961 if (clone_ok || x->reflink_mode == REFLINK_ALWAYS)
965 error (0, errno, _("failed to clone %s from %s"),
966 quote_n (0, dst_name), quote_n (1, src_name));
968 goto close_src_and_dst_desc;
970 data_copy_required = false;
974 if (data_copy_required)
976 typedef uintptr_t word;
978 /* Choose a suitable buffer size; it may be adjusted later. */
979 size_t buf_alignment = lcm (getpagesize (), sizeof (word));
980 size_t buf_alignment_slop = sizeof (word) + buf_alignment - 1;
981 size_t buf_size = io_blksize (sb);
983 /* Deal with sparse files. */
984 bool make_holes = false;
985 bool sparse_src = false;
987 if (S_ISREG (sb.st_mode))
989 /* Even with --sparse=always, try to create holes only
990 if the destination is a regular file. */
991 if (x->sparse_mode == SPARSE_ALWAYS)
994 /* Use a heuristic to determine whether SRC_NAME contains any sparse
995 blocks. If the file has fewer blocks than would normally be
996 needed for a file of its size, then at least one of the blocks in
997 the file is a hole. */
998 sparse_src = is_probably_sparse (&src_open_sb);
999 if (x->sparse_mode == SPARSE_AUTO && sparse_src)
1003 /* If not making a sparse file, try to use a more-efficient
1007 /* Compute the least common multiple of the input and output
1008 buffer sizes, adjusting for outlandish values. */
1009 size_t blcm_max = MIN (SIZE_MAX, SSIZE_MAX) - buf_alignment_slop;
1010 size_t blcm = buffer_lcm (io_blksize (src_open_sb), buf_size,
1013 /* Do not bother with a buffer larger than the input file, plus one
1014 byte to make sure the file has not grown while reading it. */
1015 if (S_ISREG (src_open_sb.st_mode) && src_open_sb.st_size < buf_size)
1016 buf_size = src_open_sb.st_size + 1;
1018 /* However, stick with a block size that is a positive multiple of
1019 blcm, overriding the above adjustments. Watch out for
1021 buf_size += blcm - 1;
1022 buf_size -= buf_size % blcm;
1023 if (buf_size == 0 || blcm_max < buf_size)
1027 /* Make a buffer with space for a sentinel at the end. */
1028 buf_alloc = xmalloc (buf_size + buf_alignment_slop);
1029 buf = ptr_align (buf_alloc, buf_alignment);
1033 bool normal_copy_required;
1035 /* Perform an efficient extent-based copy, falling back to the
1036 standard copy only if the initial extent scan fails. If the
1037 '--sparse=never' option is specified, write all data but use
1038 any extents to read more efficiently. */
1039 if (extent_copy (source_desc, dest_desc, buf, buf_size,
1040 src_open_sb.st_size,
1041 S_ISREG (sb.st_mode) ? x->sparse_mode : SPARSE_NEVER,
1042 src_name, dst_name, &normal_copy_required))
1043 goto preserve_metadata;
1045 if (! normal_copy_required)
1048 goto close_src_and_dst_desc;
1053 bool wrote_hole_at_eof;
1054 if ( ! sparse_copy (source_desc, dest_desc, buf, buf_size,
1055 make_holes, src_name, dst_name,
1056 UINTMAX_MAX, &n_read,
1058 || (wrote_hole_at_eof &&
1059 ftruncate (dest_desc, n_read) < 0))
1061 error (0, errno, _("failed to extend %s"), quote (dst_name));
1063 goto close_src_and_dst_desc;
1068 if (x->preserve_timestamps)
1070 struct timespec timespec[2];
1071 timespec[0] = get_stat_atime (src_sb);
1072 timespec[1] = get_stat_mtime (src_sb);
1074 if (fdutimens (dest_desc, dst_name, timespec) != 0)
1076 error (0, errno, _("preserving times for %s"), quote (dst_name));
1077 if (x->require_preserve)
1080 goto close_src_and_dst_desc;
1085 /* Set ownership before xattrs as changing owners will
1086 clear capabilities. */
1087 if (x->preserve_ownership && ! SAME_OWNER_AND_GROUP (*src_sb, sb))
1089 switch (set_owner (x, dst_name, dest_desc, src_sb, *new_dst, &sb))
1093 goto close_src_and_dst_desc;
1096 src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX);
1101 /* To allow copying xattrs on read-only files, temporarily chmod u+rw.
1102 This workaround is required as an inode permission check is done
1103 by xattr_permission() in fs/xattr.c of the GNU/Linux kernel tree. */
1104 if (x->preserve_xattr)
1106 bool access_changed = false;
1108 if (!(sb.st_mode & S_IWUSR) && geteuid () != 0)
1109 access_changed = fchmod_or_lchmod (dest_desc, dst_name, 0600) == 0;
1111 if (!copy_attr (src_name, source_desc, dst_name, dest_desc, x)
1112 && x->require_preserve_xattr)
1116 fchmod_or_lchmod (dest_desc, dst_name, dst_mode & ~omitted_permissions);
1119 set_author (dst_name, dest_desc, src_sb);
1121 if (x->preserve_mode || x->move_mode)
1123 if (copy_acl (src_name, source_desc, dst_name, dest_desc, src_mode) != 0
1124 && x->require_preserve)
1127 else if (x->set_mode)
1129 if (set_acl (dst_name, dest_desc, x->mode) != 0)
1132 else if (omitted_permissions)
1134 omitted_permissions &= ~ cached_umask ();
1135 if (omitted_permissions
1136 && fchmod_or_lchmod (dest_desc, dst_name, dst_mode) != 0)
1138 error (0, errno, _("preserving permissions for %s"),
1140 if (x->require_preserve)
1145 close_src_and_dst_desc:
1146 if (close (dest_desc) < 0)
1148 error (0, errno, _("closing %s"), quote (dst_name));
1152 if (close (source_desc) < 0)
1154 error (0, errno, _("closing %s"), quote (src_name));
1163 /* Return true if it's ok that the source and destination
1164 files are the 'same' by some measure. The goal is to avoid
1165 making the 'copy' operation remove both copies of the file
1166 in that case, while still allowing the user to e.g., move or
1167 copy a regular file onto a symlink that points to it.
1168 Try to minimize the cost of this function in the common case.
1169 Set *RETURN_NOW if we've determined that the caller has no more
1170 work to do and should return successfully, right away.
1172 Set *UNLINK_SRC if we've determined that the caller wants to do
1173 'rename (a, b)' where 'a' and 'b' are distinct hard links to the same
1174 file. In that case, the caller should try to unlink 'a' and then return
1175 successfully. Ideally, we wouldn't have to do that, and we'd be
1176 able to rely on rename to remove the source file. However, POSIX
1177 mistakenly requires that such a rename call do *nothing* and return
1181 same_file_ok (char const *src_name, struct stat const *src_sb,
1182 char const *dst_name, struct stat const *dst_sb,
1183 const struct cp_options *x, bool *return_now, bool *unlink_src)
1185 const struct stat *src_sb_link;
1186 const struct stat *dst_sb_link;
1187 struct stat tmp_dst_sb;
1188 struct stat tmp_src_sb;
1191 bool same = SAME_INODE (*src_sb, *dst_sb);
1193 *return_now = false;
1194 *unlink_src = false;
1196 /* FIXME: this should (at the very least) be moved into the following
1197 if-block. More likely, it should be removed, because it inhibits
1198 making backups. But removing it will result in a change in behavior
1199 that will probably have to be documented -- and tests will have to
1201 if (same && x->hard_link)
1207 if (x->dereference == DEREF_NEVER)
1211 /* If both the source and destination files are symlinks (and we'll
1212 know this here IFF preserving symlinks), then it's usually ok
1213 when they are distinct. */
1214 if (S_ISLNK (src_sb->st_mode) && S_ISLNK (dst_sb->st_mode))
1216 bool sn = same_name (src_name, dst_name);
1219 /* It's fine when we're making any type of backup. */
1220 if (x->backup_type != no_backups)
1223 /* Here we have two symlinks that are hard-linked together,
1224 and we're not making backups. In this unusual case, simply
1225 returning true would lead to mv calling "rename(A,B)",
1226 which would do nothing and return 0. I.e., A would
1227 not be removed. Hence, the solution is to tell the
1228 caller that all it must do is unlink A and return. */
1240 src_sb_link = src_sb;
1241 dst_sb_link = dst_sb;
1248 if (lstat (dst_name, &tmp_dst_sb) != 0
1249 || lstat (src_name, &tmp_src_sb) != 0)
1252 src_sb_link = &tmp_src_sb;
1253 dst_sb_link = &tmp_dst_sb;
1255 same_link = SAME_INODE (*src_sb_link, *dst_sb_link);
1257 /* If both are symlinks, then it's ok, but only if the destination
1258 will be unlinked before being opened. This is like the test
1259 above, but with the addition of the unlink_dest_before_opening
1260 conjunct because otherwise, with two symlinks to the same target,
1261 we'd end up truncating the source file. */
1262 if (S_ISLNK (src_sb_link->st_mode) && S_ISLNK (dst_sb_link->st_mode)
1263 && x->unlink_dest_before_opening)
1267 /* The backup code ensures there's a copy, so it's usually ok to
1268 remove any destination file. One exception is when both
1269 source and destination are the same directory entry. In that
1270 case, moving the destination file aside (in making the backup)
1271 would also rename the source file and result in an error. */
1272 if (x->backup_type != no_backups)
1276 /* In copy mode when dereferencing symlinks, if the source is a
1277 symlink and the dest is not, then backing up the destination
1278 (moving it aside) would make it a dangling symlink, and the
1279 subsequent attempt to open it in copy_reg would fail with
1280 a misleading diagnostic. Avoid that by returning zero in
1281 that case so the caller can make cp (or mv when it has to
1282 resort to reading the source file) fail now. */
1284 /* FIXME-note: even with the following kludge, we can still provoke
1285 the offending diagnostic. It's just a little harder to do :-)
1286 $ rm -f a b c; touch c; ln -s c b; ln -s b a; cp -b a b
1287 cp: cannot open 'a' for reading: No such file or directory
1288 That's misleading, since a subsequent 'ls' shows that 'a'
1290 One solution would be to open the source file *before* moving
1291 aside the destination, but that'd involve a big rewrite. */
1293 && x->dereference != DEREF_NEVER
1294 && S_ISLNK (src_sb_link->st_mode)
1295 && ! S_ISLNK (dst_sb_link->st_mode))
1301 return ! same_name (src_name, dst_name);
1305 /* FIXME: use or remove */
1307 /* If we're making a backup, we'll detect the problem case in
1308 copy_reg because SRC_NAME will no longer exist. Allowing
1309 the test to be deferred lets cp do some useful things.
1310 But when creating hardlinks and SRC_NAME is a symlink
1311 but DST_NAME is not we must test anyway. */
1313 || !S_ISLNK (src_sb_link->st_mode)
1314 || S_ISLNK (dst_sb_link->st_mode))
1317 if (x->dereference != DEREF_NEVER)
1321 /* They may refer to the same file if we're in move mode and the
1322 target is a symlink. That is ok, since we remove any existing
1323 destination file before opening it -- via 'rename' if they're on
1324 the same file system, via 'unlink (DST_NAME)' otherwise.
1325 It's also ok if they're distinct hard links to the same file. */
1326 if (x->move_mode || x->unlink_dest_before_opening)
1328 if (S_ISLNK (dst_sb_link->st_mode))
1332 && 1 < dst_sb_link->st_nlink
1333 && ! same_name (src_name, dst_name))
1344 /* If neither is a symlink, then it's ok as long as they aren't
1345 hard links to the same file. */
1346 if (!S_ISLNK (src_sb_link->st_mode) && !S_ISLNK (dst_sb_link->st_mode))
1348 if (!SAME_INODE (*src_sb_link, *dst_sb_link))
1351 /* If they are the same file, it's ok if we're making hard links. */
1359 /* At this point, it is normally an error (data loss) to move a symlink
1360 onto its referent, but in at least one narrow case, it is not:
1362 1) src is a symlink,
1363 2) dest has a link count of 2 or more and
1364 3) dest and the referent of src are not the same directory entry,
1365 then it's ok, since while we'll lose one of those hard links,
1366 src will still point to a remaining link.
1367 Note that technically, condition #3 obviates condition #2, but we
1368 retain the 1 < st_nlink condition because that means fewer invocations
1369 of the more expensive #3.
1372 $ touch f && ln f l && ln -s f s
1374 -rw-------. 2 0 Jan 4 22:46 f
1375 -rw-------. 2 0 Jan 4 22:46 l
1376 lrwxrwxrwx. 1 1 Jan 4 22:46 s -> f
1377 this must fail: mv s f
1378 this must succeed: mv s l */
1380 && S_ISLNK (src_sb->st_mode)
1381 && 1 < dst_sb_link->st_nlink)
1383 char *abs_src = canonicalize_file_name (src_name);
1386 bool result = ! same_name (abs_src, dst_name);
1392 /* It's ok to remove a destination symlink. But that works only when we
1393 unlink before opening the destination and when the source and destination
1394 files are on the same partition. */
1395 if (x->unlink_dest_before_opening
1396 && S_ISLNK (dst_sb_link->st_mode))
1397 return dst_sb_link->st_dev == src_sb_link->st_dev;
1399 if (x->dereference == DEREF_NEVER)
1401 if ( ! S_ISLNK (src_sb_link->st_mode))
1402 tmp_src_sb = *src_sb_link;
1403 else if (stat (src_name, &tmp_src_sb) != 0)
1406 if ( ! S_ISLNK (dst_sb_link->st_mode))
1407 tmp_dst_sb = *dst_sb_link;
1408 else if (stat (dst_name, &tmp_dst_sb) != 0)
1411 if ( ! SAME_INODE (tmp_src_sb, tmp_dst_sb))
1414 /* FIXME: shouldn't this be testing whether we're making symlinks? */
1425 /* Return true if FILE, with mode MODE, is writable in the sense of 'mv'.
1426 Always consider a symbolic link to be writable. */
1428 writable_destination (char const *file, mode_t mode)
1430 return (S_ISLNK (mode)
1431 || can_write_any_file ()
1432 || euidaccess (file, W_OK) == 0);
1436 overwrite_prompt (char const *dst_name, struct stat const *dst_sb)
1438 if (! writable_destination (dst_name, dst_sb->st_mode))
1440 char perms[12]; /* "-rwxrwxrwx " ls-style modes. */
1441 strmode (dst_sb->st_mode, perms);
1444 _("%s: try to overwrite %s, overriding mode %04lo (%s)? "),
1445 program_name, quote (dst_name),
1446 (unsigned long int) (dst_sb->st_mode & CHMOD_MODE_BITS),
1451 fprintf (stderr, _("%s: overwrite %s? "),
1452 program_name, quote (dst_name));
1456 /* Initialize the hash table implementing a set of F_triple entries
1457 corresponding to destination files. */
1459 dest_info_init (struct cp_options *x)
1462 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
1469 /* Initialize the hash table implementing a set of F_triple entries
1470 corresponding to source files listed on the command line. */
1472 src_info_init (struct cp_options *x)
1475 /* Note that we use triple_hash_no_name here.
1476 Contrast with the use of triple_hash above.
1477 That is necessary because a source file may be specified
1478 in many different ways. We want to warn about this
1484 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
1486 triple_hash_no_name,
1491 /* When effecting a move (e.g., for mv(1)), and given the name DST_NAME
1492 of the destination and a corresponding stat buffer, DST_SB, return
1493 true if the logical 'move' operation should _not_ proceed.
1494 Otherwise, return false.
1495 Depending on options specified in X, this code may issue an
1496 interactive prompt asking whether it's ok to overwrite DST_NAME. */
1498 abandon_move (const struct cp_options *x,
1499 char const *dst_name,
1500 struct stat const *dst_sb)
1502 assert (x->move_mode);
1503 return (x->interactive == I_ALWAYS_NO
1504 || ((x->interactive == I_ASK_USER
1505 || (x->interactive == I_UNSPECIFIED
1507 && ! writable_destination (dst_name, dst_sb->st_mode)))
1508 && (overwrite_prompt (dst_name, dst_sb), 1)
1512 /* Print --verbose output on standard output, e.g. 'new' -> 'old'.
1513 If BACKUP_DST_NAME is non-NULL, then also indicate that it is
1514 the name of a backup file. */
1516 emit_verbose (char const *src, char const *dst, char const *backup_dst_name)
1518 printf ("%s -> %s", quote_n (0, src), quote_n (1, dst));
1519 if (backup_dst_name)
1520 printf (_(" (backup: %s)"), quote (backup_dst_name));
1524 /* A wrapper around "setfscreatecon (NULL)" that exits upon failure. */
1526 restore_default_fscreatecon_or_die (void)
1528 if (setfscreatecon (NULL) != 0)
1529 error (EXIT_FAILURE, errno,
1530 _("failed to restore the default file creation context"));
1533 /* Create a hard link DST_NAME to SRC_NAME, honoring the REPLACE and
1534 VERBOSE settings. Return true upon success. Otherwise, diagnose
1535 the failure and return false.
1536 If SRC_NAME is a symbolic link it will not be followed. If the system
1537 doesn't support hard links to symbolic links, then DST_NAME will
1538 be created as a symbolic link to SRC_NAME. */
1540 create_hard_link (char const *src_name, char const *dst_name,
1541 bool replace, bool verbose)
1543 /* We want to guarantee that symlinks are not followed. */
1544 bool link_failed = (linkat (AT_FDCWD, src_name, AT_FDCWD, dst_name, 0) != 0);
1546 /* If the link failed because of an existing destination,
1547 remove that file and then call link again. */
1548 if (link_failed && replace && errno == EEXIST)
1550 if (unlink (dst_name) != 0)
1552 error (0, errno, _("cannot remove %s"), quote (dst_name));
1556 printf (_("removed %s\n"), quote (dst_name));
1557 link_failed = (linkat (AT_FDCWD, src_name, AT_FDCWD, dst_name, 0) != 0);
1562 error (0, errno, _("cannot create hard link %s to %s"),
1563 quote_n (0, dst_name), quote_n (1, src_name));
1570 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
1571 any type. NEW_DST should be true if the file DST_NAME cannot
1572 exist because its parent directory was just created; NEW_DST should
1573 be false if DST_NAME might already exist. DEVICE is the device
1574 number of the parent directory, or 0 if the parent of this file is
1575 not known. ANCESTORS points to a linked, null terminated list of
1576 devices and inodes of parent directories of SRC_NAME. COMMAND_LINE_ARG
1577 is true iff SRC_NAME was specified on the command line.
1578 FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG is both input and output.
1579 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
1580 same as) DST_NAME; otherwise, clear it.
1581 Return true if successful. */
1583 copy_internal (char const *src_name, char const *dst_name,
1586 struct dir_list *ancestors,
1587 const struct cp_options *x,
1588 bool command_line_arg,
1589 bool *first_dir_created_per_command_line_arg,
1590 bool *copy_into_self,
1591 bool *rename_succeeded)
1596 mode_t dst_mode IF_LINT ( = 0);
1597 mode_t dst_mode_bits;
1598 mode_t omitted_permissions;
1599 bool restore_dst_mode = false;
1600 char *earlier_file = NULL;
1601 char *dst_backup = NULL;
1602 bool backup_succeeded = false;
1604 bool copied_as_regular = false;
1605 bool dest_is_symlink = false;
1606 bool have_dst_lstat = false;
1608 if (x->move_mode && rename_succeeded)
1609 *rename_succeeded = false;
1611 *copy_into_self = false;
1613 if (XSTAT (x, src_name, &src_sb) != 0)
1615 error (0, errno, _("cannot stat %s"), quote (src_name));
1619 src_mode = src_sb.st_mode;
1621 if (S_ISDIR (src_mode) && !x->recursive)
1623 error (0, 0, _("omitting directory %s"), quote (src_name));
1627 /* Detect the case in which the same source file appears more than
1628 once on the command line and no backup option has been selected.
1629 If so, simply warn and don't copy it the second time.
1630 This check is enabled only if x->src_info is non-NULL. */
1631 if (command_line_arg)
1633 if ( ! S_ISDIR (src_sb.st_mode)
1634 && x->backup_type == no_backups
1635 && seen_file (x->src_info, src_name, &src_sb))
1637 error (0, 0, _("warning: source file %s specified more than once"),
1642 record_file (x->src_info, src_name, &src_sb);
1647 /* Regular files can be created by writing through symbolic
1648 links, but other files cannot. So use stat on the
1649 destination when copying a regular file, and lstat otherwise.
1650 However, if we intend to unlink or remove the destination
1651 first, use lstat, since a copy won't actually be made to the
1652 destination in that case. */
1654 ((S_ISREG (src_mode)
1655 || (x->copy_as_regular
1656 && ! (S_ISDIR (src_mode) || S_ISLNK (src_mode))))
1657 && ! (x->move_mode || x->symbolic_link || x->hard_link
1658 || x->backup_type != no_backups
1659 || x->unlink_dest_before_opening));
1661 ? stat (dst_name, &dst_sb)
1662 : lstat (dst_name, &dst_sb))
1665 if (errno != ENOENT)
1667 error (0, errno, _("cannot stat %s"), quote (dst_name));
1676 { /* Here, we know that dst_name exists, at least to the point
1677 that it is stat'able or lstat'able. */
1681 have_dst_lstat = !use_stat;
1682 if (! same_file_ok (src_name, &src_sb, dst_name, &dst_sb,
1683 x, &return_now, &unlink_src))
1685 error (0, 0, _("%s and %s are the same file"),
1686 quote_n (0, src_name), quote_n (1, dst_name));
1690 if (!S_ISDIR (src_mode) && x->update)
1692 /* When preserving time stamps (but not moving within a file
1693 system), don't worry if the destination time stamp is
1694 less than the source merely because of time stamp
1696 int options = ((x->preserve_timestamps
1698 && dst_sb.st_dev == src_sb.st_dev))
1699 ? UTIMECMP_TRUNCATE_SOURCE
1702 if (0 <= utimecmp (dst_name, &dst_sb, &src_sb, options))
1704 /* We're using --update and the destination is not older
1705 than the source, so do not copy or move. Pretend the
1706 rename succeeded, so the caller (if it's mv) doesn't
1707 end up removing the source file. */
1708 if (rename_succeeded)
1709 *rename_succeeded = true;
1711 /* However, we still must record that we've processed
1712 this src/dest pair, in case this source file is
1713 hard-linked to another one. In that case, we'll use
1714 the mapping information to link the corresponding
1715 destination names. */
1716 earlier_file = remember_copied (dst_name, src_sb.st_ino,
1720 /* Note we currently replace DST_NAME unconditionally,
1721 even if it was a newer separate file. */
1722 if (! create_hard_link (earlier_file, dst_name, true,
1733 /* When there is an existing destination file, we may end up
1734 returning early, and hence not copying/moving the file.
1735 This may be due to an interactive 'negative' reply to the
1736 prompt about the existing file. It may also be due to the
1737 use of the --reply=no option.
1739 cp and mv treat -i and -f differently. */
1742 if (abandon_move (x, dst_name, &dst_sb)
1743 || (unlink_src && unlink (src_name) == 0))
1745 /* Pretend the rename succeeded, so the caller (mv)
1746 doesn't end up removing the source file. */
1747 if (rename_succeeded)
1748 *rename_succeeded = true;
1749 if (unlink_src && x->verbose)
1750 printf (_("removed %s\n"), quote (src_name));
1755 error (0, errno, _("cannot remove %s"), quote (src_name));
1761 if (! S_ISDIR (src_mode)
1762 && (x->interactive == I_ALWAYS_NO
1763 || (x->interactive == I_ASK_USER
1764 && (overwrite_prompt (dst_name, &dst_sb), 1)
1772 if (!S_ISDIR (dst_sb.st_mode))
1774 if (S_ISDIR (src_mode))
1776 if (x->move_mode && x->backup_type != no_backups)
1778 /* Moving a directory onto an existing
1779 non-directory is ok only with --backup. */
1784 _("cannot overwrite non-directory %s with directory %s"),
1785 quote_n (0, dst_name), quote_n (1, src_name));
1790 /* Don't let the user destroy their data, even if they try hard:
1791 This mv command must fail (likewise for cp):
1792 rm -rf a b c; mkdir a b c; touch a/f b/f; mv a/f b/f c
1793 Otherwise, the contents of b/f would be lost.
1794 In the case of 'cp', b/f would be lost if the user simulated
1795 a move using cp and rm.
1796 Note that it works fine if you use --backup=numbered. */
1797 if (command_line_arg
1798 && x->backup_type != numbered_backups
1799 && seen_file (x->dest_info, dst_name, &dst_sb))
1802 _("will not overwrite just-created %s with %s"),
1803 quote_n (0, dst_name), quote_n (1, src_name));
1808 if (!S_ISDIR (src_mode))
1810 if (S_ISDIR (dst_sb.st_mode))
1812 if (x->move_mode && x->backup_type != no_backups)
1814 /* Moving a non-directory onto an existing
1815 directory is ok only with --backup. */
1820 _("cannot overwrite directory %s with non-directory"),
1829 /* Don't allow user to move a directory onto a non-directory. */
1830 if (S_ISDIR (src_sb.st_mode) && !S_ISDIR (dst_sb.st_mode)
1831 && x->backup_type == no_backups)
1834 _("cannot move directory onto non-directory: %s -> %s"),
1835 quote_n (0, src_name), quote_n (0, dst_name));
1840 if (x->backup_type != no_backups
1841 /* Don't try to back up a destination if the last
1842 component of src_name is "." or "..". */
1843 && ! dot_or_dotdot (last_component (src_name))
1844 /* Create a backup of each destination directory in move mode,
1845 but not in copy mode. FIXME: it might make sense to add an
1846 option to suppress backup creation also for move mode.
1847 That would let one use mv to merge new content into an
1848 existing hierarchy. */
1849 && (x->move_mode || ! S_ISDIR (dst_sb.st_mode)))
1851 char *tmp_backup = find_backup_file_name (dst_name,
1854 /* Detect (and fail) when creating the backup file would
1855 destroy the source file. Before, running the commands
1856 cd /tmp; rm -f a a~; : > a; echo A > a~; cp --b=simple a~ a
1857 would leave two zero-length files: a and a~. */
1858 /* FIXME: but simply change e.g., the final a~ to './a~'
1859 and the source will still be destroyed. */
1860 if (STREQ (tmp_backup, src_name))
1864 ? _("backing up %s would destroy source; %s not moved")
1865 : _("backing up %s would destroy source; %s not copied"));
1867 quote_n (0, dst_name),
1868 quote_n (1, src_name));
1874 Using alloca for a file name that may be arbitrarily
1875 long is not recommended. In fact, even forming such a name
1876 should be discouraged. Eventually, this code will be rewritten
1877 to use fts, so using alloca here will be less of a problem. */
1878 ASSIGN_STRDUPA (dst_backup, tmp_backup);
1880 /* In move mode, when src_name and dst_name are on the
1881 same partition (FIXME, and when they are non-directories),
1882 make the operation atomic: link dest
1883 to backup, then rename src to dest. */
1884 if (rename (dst_name, dst_backup) != 0)
1886 if (errno != ENOENT)
1888 error (0, errno, _("cannot backup %s"), quote (dst_name));
1898 backup_succeeded = true;
1902 else if (! S_ISDIR (dst_sb.st_mode)
1903 /* Never unlink dst_name when in move mode. */
1905 && (x->unlink_dest_before_opening
1906 || (x->preserve_links && 1 < dst_sb.st_nlink)
1907 || (x->dereference == DEREF_NEVER
1908 && ! S_ISREG (src_sb.st_mode))
1911 if (unlink (dst_name) != 0 && errno != ENOENT)
1913 error (0, errno, _("cannot remove %s"), quote (dst_name));
1918 printf (_("removed %s\n"), quote (dst_name));
1923 /* Ensure we don't try to copy through a symlink that was
1924 created by a prior call to this function. */
1925 if (command_line_arg
1928 && x->backup_type == no_backups)
1930 bool lstat_ok = true;
1931 struct stat tmp_buf;
1932 struct stat *dst_lstat_sb;
1934 /* If we called lstat above, good: use that data.
1935 Otherwise, call lstat here, in case dst_name is a symlink. */
1937 dst_lstat_sb = &dst_sb;
1940 if (lstat (dst_name, &tmp_buf) == 0)
1941 dst_lstat_sb = &tmp_buf;
1946 /* Never copy through a symlink we've just created. */
1948 && S_ISLNK (dst_lstat_sb->st_mode)
1949 && seen_file (x->dest_info, dst_name, dst_lstat_sb))
1952 _("will not copy %s through just-created symlink %s"),
1953 quote_n (0, src_name), quote_n (1, dst_name));
1958 /* If the source is a directory, we don't always create the destination
1959 directory. So --verbose should not announce anything until we're
1960 sure we'll create a directory. */
1961 if (x->verbose && !S_ISDIR (src_mode))
1962 emit_verbose (src_name, dst_name, backup_succeeded ? dst_backup : NULL);
1964 /* Associate the destination file name with the source device and inode
1965 so that if we encounter a matching dev/ino pair in the source tree
1966 we can arrange to create a hard link between the corresponding names
1967 in the destination tree.
1969 When using the --link (-l) option, there is no need to take special
1970 measures, because (barring race conditions) files that are hard-linked
1971 in the source tree will also be hard-linked in the destination tree.
1973 Sometimes, when preserving links, we have to record dev/ino even
1974 though st_nlink == 1:
1975 - when in move_mode, since we may be moving a group of N hard-linked
1976 files (via two or more command line arguments) to a different
1977 partition; the links may be distributed among the command line
1978 arguments (possibly hierarchies) so that the link count of
1979 the final, once-linked source file is reduced to 1 when it is
1980 considered below. But in this case (for mv) we don't need to
1981 incur the expense of recording the dev/ino => name mapping; all we
1982 really need is a lookup, to see if the dev/ino pair has already
1984 - when using -H and processing a command line argument;
1985 that command line argument could be a symlink pointing to another
1986 command line argument. With 'cp -H --preserve=link', we hard-link
1987 those two destination files.
1988 - likewise for -L except that it applies to all files, not just
1989 command line arguments.
1991 Also, with --recursive, record dev/ino of each command-line directory.
1992 We'll use that info to detect this problem: cp -R dir dir. */
1994 if (x->move_mode && src_sb.st_nlink == 1)
1996 earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev);
1998 else if (x->preserve_links
2000 && (1 < src_sb.st_nlink
2001 || (command_line_arg
2002 && x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
2003 || x->dereference == DEREF_ALWAYS))
2005 earlier_file = remember_copied (dst_name, src_sb.st_ino, src_sb.st_dev);
2007 else if (x->recursive && S_ISDIR (src_mode))
2009 if (command_line_arg)
2010 earlier_file = remember_copied (dst_name, src_sb.st_ino, src_sb.st_dev);
2012 earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev);
2015 /* Did we copy this inode somewhere else (in this command line argument)
2016 and therefore this is a second hard link to the inode? */
2020 /* Avoid damaging the destination file system by refusing to preserve
2021 hard-linked directories (which are found at least in Netapp snapshot
2023 if (S_ISDIR (src_mode))
2025 /* If src_name and earlier_file refer to the same directory entry,
2026 then warn about copying a directory into itself. */
2027 if (same_name (src_name, earlier_file))
2029 error (0, 0, _("cannot copy a directory, %s, into itself, %s"),
2030 quote_n (0, top_level_src_name),
2031 quote_n (1, top_level_dst_name));
2032 *copy_into_self = true;
2035 else if (x->dereference == DEREF_ALWAYS)
2037 /* This happens when e.g., encountering a directory for the
2038 second or subsequent time via symlinks when cp is invoked
2039 with -R and -L. E.g.,
2040 rm -rf a b c d; mkdir a b c d; ln -s ../c a; ln -s ../c b;
2046 error (0, 0, _("will not create hard link %s to directory %s"),
2047 quote_n (0, dst_name), quote_n (1, earlier_file));
2053 if (! create_hard_link (earlier_file, dst_name, true, x->verbose))
2062 if (rename (src_name, dst_name) == 0)
2064 if (x->verbose && S_ISDIR (src_mode))
2065 emit_verbose (src_name, dst_name,
2066 backup_succeeded ? dst_backup : NULL);
2068 if (rename_succeeded)
2069 *rename_succeeded = true;
2071 if (command_line_arg)
2073 /* Record destination dev/ino/name, so that if we are asked
2074 to overwrite that file again, we can detect it and fail. */
2075 /* It's fine to use the _source_ stat buffer (src_sb) to get the
2076 _destination_ dev/ino, since the rename above can't have
2077 changed those, and 'mv' always uses lstat.
2078 We could limit it further by operating
2079 only on non-directories. */
2080 record_file (x->dest_info, dst_name, &src_sb);
2086 /* FIXME: someday, consider what to do when moving a directory into
2087 itself but when source and destination are on different devices. */
2089 /* This happens when attempting to rename a directory to a
2090 subdirectory of itself. */
2091 if (errno == EINVAL)
2093 /* FIXME: this is a little fragile in that it relies on rename(2)
2094 failing with a specific errno value. Expect problems on
2095 non-POSIX systems. */
2096 error (0, 0, _("cannot move %s to a subdirectory of itself, %s"),
2097 quote_n (0, top_level_src_name),
2098 quote_n (1, top_level_dst_name));
2100 /* Note that there is no need to call forget_created here,
2101 (compare with the other calls in this file) since the
2102 destination directory didn't exist before. */
2104 *copy_into_self = true;
2105 /* FIXME-cleanup: Don't return true here; adjust mv.c accordingly.
2106 The only caller that uses this code (mv.c) ends up setting its
2107 exit status to nonzero when copy_into_self is nonzero. */
2111 /* WARNING: there probably exist systems for which an inter-device
2112 rename fails with a value of errno not handled here.
2113 If/as those are reported, add them to the condition below.
2114 If this happens to you, please do the following and send the output
2115 to the bug-reporting address (e.g., in the output of cp --help):
2116 touch k; perl -e 'rename "k","/tmp/k" or print "$!(",$!+0,")\n"'
2117 where your current directory is on one partion and /tmp is the other.
2118 Also, please try to find the E* errno macro name corresponding to
2119 the diagnostic and parenthesized integer, and include that in your
2120 e-mail. One way to do that is to run a command like this
2121 find /usr/include/. -type f \
2122 | xargs grep 'define.*\<E[A-Z]*\>.*\<18\>' /dev/null
2123 where you'd replace '18' with the integer in parentheses that
2124 was output from the perl one-liner above.
2125 If necessary, of course, change '/tmp' to some other directory. */
2128 /* There are many ways this can happen due to a race condition.
2129 When something happens between the initial XSTAT and the
2130 subsequent rename, we can get many different types of errors.
2131 For example, if the destination is initially a non-directory
2132 or non-existent, but it is created as a directory, the rename
2133 fails. If two 'mv' commands try to rename the same file at
2134 about the same time, one will succeed and the other will fail.
2135 If the permissions on the directory containing the source or
2136 destination file are made too restrictive, the rename will
2139 _("cannot move %s to %s"),
2140 quote_n (0, src_name), quote_n (1, dst_name));
2141 forget_created (src_sb.st_ino, src_sb.st_dev);
2145 /* The rename attempt has failed. Remove any existing destination
2146 file so that a cross-device 'mv' acts as if it were really using
2147 the rename syscall. */
2148 if (unlink (dst_name) != 0 && errno != ENOENT)
2151 _("inter-device move failed: %s to %s; unable to remove target"),
2152 quote_n (0, src_name), quote_n (1, dst_name));
2153 forget_created (src_sb.st_ino, src_sb.st_dev);
2160 /* If the ownership might change, or if it is a directory (whose
2161 special mode bits may change after the directory is created),
2162 omit some permissions at first, so unauthorized users cannot nip
2163 in before the file is ready. */
2164 dst_mode_bits = (x->set_mode ? x->mode : src_mode) & CHMOD_MODE_BITS;
2165 omitted_permissions =
2167 & (x->preserve_ownership ? S_IRWXG | S_IRWXO
2168 : S_ISDIR (src_mode) ? S_IWGRP | S_IWOTH
2173 if (x->preserve_security_context)
2175 bool all_errors = !x->data_copy_required || x->require_preserve_context;
2176 bool some_errors = !all_errors && !x->reduce_diagnostics;
2177 security_context_t con;
2179 if (0 <= lgetfilecon (src_name, &con))
2181 if (setfscreatecon (con) < 0)
2183 if (all_errors || (some_errors && !errno_unsupported (errno)))
2185 _("failed to set default file creation context to %s"),
2187 if (x->require_preserve_context)
2197 if (all_errors || (some_errors && !errno_unsupported (errno)))
2200 _("failed to get security context of %s"),
2203 if (x->require_preserve_context)
2208 if (S_ISDIR (src_mode))
2210 struct dir_list *dir;
2212 /* If this directory has been copied before during the
2213 recursion, there is a symbolic link to an ancestor
2214 directory of the symbolic link. It is impossible to
2215 continue to copy this, unless we've got an infinite disk. */
2217 if (is_ancestor (&src_sb, ancestors))
2219 error (0, 0, _("cannot copy cyclic symbolic link %s"),
2224 /* Insert the current directory in the list of parents. */
2226 dir = alloca (sizeof *dir);
2227 dir->parent = ancestors;
2228 dir->ino = src_sb.st_ino;
2229 dir->dev = src_sb.st_dev;
2231 if (new_dst || !S_ISDIR (dst_sb.st_mode))
2233 /* POSIX says mkdir's behavior is implementation-defined when
2234 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
2235 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
2236 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
2237 if (mkdir (dst_name, dst_mode_bits & ~omitted_permissions) != 0)
2239 error (0, errno, _("cannot create directory %s"),
2244 /* We need search and write permissions to the new directory
2245 for writing the directory's contents. Check if these
2246 permissions are there. */
2248 if (lstat (dst_name, &dst_sb) != 0)
2250 error (0, errno, _("cannot stat %s"), quote (dst_name));
2253 else if ((dst_sb.st_mode & S_IRWXU) != S_IRWXU)
2255 /* Make the new directory searchable and writable. */
2257 dst_mode = dst_sb.st_mode;
2258 restore_dst_mode = true;
2260 if (lchmod (dst_name, dst_mode | S_IRWXU) != 0)
2262 error (0, errno, _("setting permissions for %s"),
2268 /* Record the created directory's inode and device numbers into
2269 the search structure, so that we can avoid copying it again.
2270 Do this only for the first directory that is created for each
2271 source command line argument. */
2272 if (!*first_dir_created_per_command_line_arg)
2274 remember_copied (dst_name, dst_sb.st_ino, dst_sb.st_dev);
2275 *first_dir_created_per_command_line_arg = true;
2279 emit_verbose (src_name, dst_name, NULL);
2283 omitted_permissions = 0;
2286 /* Decide whether to copy the contents of the directory. */
2287 if (x->one_file_system && device != 0 && device != src_sb.st_dev)
2289 /* Here, we are crossing a file system boundary and cp's -x option
2290 is in effect: so don't copy the contents of this directory. */
2294 /* Copy the contents of the directory. Don't just return if
2295 this fails -- otherwise, the failure to read a single file
2296 in a source directory would cause the containing destination
2297 directory not to have owner/perms set properly. */
2298 delayed_ok = copy_dir (src_name, dst_name, new_dst, &src_sb, dir, x,
2299 first_dir_created_per_command_line_arg,
2303 else if (x->symbolic_link)
2305 dest_is_symlink = true;
2306 if (*src_name != '/')
2308 /* Check that DST_NAME denotes a file in the current directory. */
2310 struct stat dst_parent_sb;
2312 bool in_current_dir;
2314 dst_parent = dir_name (dst_name);
2316 in_current_dir = (STREQ (".", dst_parent)
2317 /* If either stat call fails, it's ok not to report
2318 the failure and say dst_name is in the current
2319 directory. Other things will fail later. */
2320 || stat (".", &dot_sb) != 0
2321 || stat (dst_parent, &dst_parent_sb) != 0
2322 || SAME_INODE (dot_sb, dst_parent_sb));
2325 if (! in_current_dir)
2328 _("%s: can make relative symbolic links only in current directory"),
2333 if (symlink (src_name, dst_name) != 0)
2335 error (0, errno, _("cannot create symbolic link %s to %s"),
2336 quote_n (0, dst_name), quote_n (1, src_name));
2341 /* POSIX 2008 states that it is implementation-defined whether
2342 link() on a symlink creates a hard-link to the symlink, or only
2343 to the referent (effectively dereferencing the symlink) (POSIX
2344 2001 required the latter behavior, although many systems provided
2345 the former). Yet cp, invoked with '--link --no-dereference',
2346 should not follow the link. We can approximate the desired
2347 behavior by skipping this hard-link creating block and instead
2348 copying the symlink, via the 'S_ISLNK'- copying code below.
2349 LINK_FOLLOWS_SYMLINKS is tri-state; if it is -1, we don't know
2350 how link() behaves, so we use the fallback case for safety.
2352 Note gnulib's linkat module, guarantees that the symlink is not
2353 dereferenced. However its emulation currently doesn't maintain
2354 timestamps or ownership so we only call it when we know the
2355 emulation will not be needed. */
2356 else if (x->hard_link
2357 && !(LINK_FOLLOWS_SYMLINKS && S_ISLNK (src_mode)
2358 && x->dereference == DEREF_NEVER))
2360 if (! create_hard_link (src_name, dst_name, false, false))
2363 else if (S_ISREG (src_mode)
2364 || (x->copy_as_regular && !S_ISLNK (src_mode)))
2366 copied_as_regular = true;
2367 /* POSIX says the permission bits of the source file must be
2368 used as the 3rd argument in the open call. Historical
2369 practice passed all the source mode bits to 'open', but the extra
2370 bits were ignored, so it should be the same either way. */
2371 if (! copy_reg (src_name, dst_name, x, src_mode & S_IRWXUGO,
2372 omitted_permissions, &new_dst, &src_sb))
2375 else if (S_ISFIFO (src_mode))
2377 /* Use mknod, rather than mkfifo, because the former preserves
2378 the special mode bits of a fifo on Solaris 10, while mkfifo
2379 does not. But fall back on mkfifo, because on some BSD systems,
2380 mknod always fails when asked to create a FIFO. */
2381 if (mknod (dst_name, src_mode & ~omitted_permissions, 0) != 0)
2382 if (mkfifo (dst_name, src_mode & ~S_IFIFO & ~omitted_permissions) != 0)
2384 error (0, errno, _("cannot create fifo %s"), quote (dst_name));
2388 else if (S_ISBLK (src_mode) || S_ISCHR (src_mode) || S_ISSOCK (src_mode))
2390 if (mknod (dst_name, src_mode & ~omitted_permissions, src_sb.st_rdev)
2393 error (0, errno, _("cannot create special file %s"),
2398 else if (S_ISLNK (src_mode))
2400 char *src_link_val = areadlink_with_size (src_name, src_sb.st_size);
2401 dest_is_symlink = true;
2402 if (src_link_val == NULL)
2404 error (0, errno, _("cannot read symbolic link %s"), quote (src_name));
2408 if (symlink (src_link_val, dst_name) == 0)
2409 free (src_link_val);
2412 int saved_errno = errno;
2413 bool same_link = false;
2414 if (x->update && !new_dst && S_ISLNK (dst_sb.st_mode)
2415 && dst_sb.st_size == strlen (src_link_val))
2417 /* See if the destination is already the desired symlink.
2418 FIXME: This behavior isn't documented, and seems wrong
2419 in some cases, e.g., if the destination symlink has the
2420 wrong ownership, permissions, or time stamps. */
2421 char *dest_link_val =
2422 areadlink_with_size (dst_name, dst_sb.st_size);
2423 if (dest_link_val && STREQ (dest_link_val, src_link_val))
2425 free (dest_link_val);
2427 free (src_link_val);
2431 error (0, saved_errno, _("cannot create symbolic link %s"),
2437 if (x->preserve_security_context)
2438 restore_default_fscreatecon_or_die ();
2440 if (x->preserve_ownership)
2442 /* Preserve the owner and group of the just-'copied'
2443 symbolic link, if possible. */
2445 && lchown (dst_name, src_sb.st_uid, src_sb.st_gid) != 0
2446 && ! chown_failure_ok (x))
2448 error (0, errno, _("failed to preserve ownership for %s"),
2454 /* Can't preserve ownership of symlinks.
2455 FIXME: maybe give a warning or even error for symlinks
2456 in directories with the sticky bit set -- there, not
2457 preserving owner/group is a potential security problem. */
2463 error (0, 0, _("%s has unknown file type"), quote (src_name));
2467 if (command_line_arg && x->dest_info)
2469 /* Now that the destination file is very likely to exist,
2470 add its info to the set. */
2472 if (lstat (dst_name, &sb) == 0)
2473 record_file (x->dest_info, dst_name, &sb);
2476 /* If we've just created a hard-link due to cp's --link option,
2478 if (x->hard_link && ! S_ISDIR (src_mode)
2479 && !(LINK_FOLLOWS_SYMLINKS && S_ISLNK (src_mode)
2480 && x->dereference == DEREF_NEVER))
2483 if (copied_as_regular)
2486 /* POSIX says that 'cp -p' must restore the following:
2488 - setuid, setgid bits
2490 If it fails to restore any of those, we may give a warning but
2491 the destination must not be removed.
2492 FIXME: implement the above. */
2494 /* Adjust the times (and if possible, ownership) for the copy.
2495 chown turns off set[ug]id bits for non-root,
2496 so do the chmod last. */
2498 if (x->preserve_timestamps)
2500 struct timespec timespec[2];
2501 timespec[0] = get_stat_atime (&src_sb);
2502 timespec[1] = get_stat_mtime (&src_sb);
2504 if ((dest_is_symlink
2505 ? utimens_symlink (dst_name, timespec)
2506 : utimens (dst_name, timespec))
2509 error (0, errno, _("preserving times for %s"), quote (dst_name));
2510 if (x->require_preserve)
2515 /* The operations beyond this point may dereference a symlink. */
2516 if (dest_is_symlink)
2519 /* Avoid calling chown if we know it's not necessary. */
2520 if (x->preserve_ownership
2521 && (new_dst || !SAME_OWNER_AND_GROUP (src_sb, dst_sb)))
2523 switch (set_owner (x, dst_name, -1, &src_sb, new_dst, &dst_sb))
2529 src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX);
2534 set_author (dst_name, -1, &src_sb);
2536 if (x->preserve_xattr && ! copy_attr (src_name, -1, dst_name, -1, x)
2537 && x->require_preserve_xattr)
2540 if (x->preserve_mode || x->move_mode)
2542 if (copy_acl (src_name, -1, dst_name, -1, src_mode) != 0
2543 && x->require_preserve)
2546 else if (x->set_mode)
2548 if (set_acl (dst_name, -1, x->mode) != 0)
2553 if (omitted_permissions)
2555 omitted_permissions &= ~ cached_umask ();
2557 if (omitted_permissions && !restore_dst_mode)
2559 /* Permissions were deliberately omitted when the file
2560 was created due to security concerns. See whether
2561 they need to be re-added now. It'd be faster to omit
2562 the lstat, but deducing the current destination mode
2563 is tricky in the presence of implementation-defined
2564 rules for special mode bits. */
2565 if (new_dst && lstat (dst_name, &dst_sb) != 0)
2567 error (0, errno, _("cannot stat %s"), quote (dst_name));
2570 dst_mode = dst_sb.st_mode;
2571 if (omitted_permissions & ~dst_mode)
2572 restore_dst_mode = true;
2576 if (restore_dst_mode)
2578 if (lchmod (dst_name, dst_mode | omitted_permissions) != 0)
2580 error (0, errno, _("preserving permissions for %s"),
2582 if (x->require_preserve)
2592 if (x->preserve_security_context)
2593 restore_default_fscreatecon_or_die ();
2595 /* We have failed to create the destination file.
2596 If we've just added a dev/ino entry via the remember_copied
2597 call above (i.e., unless we've just failed to create a hard link),
2598 remove the entry associating the source dev/ino with the
2599 destination file name, so we don't try to 'preserve' a link
2600 to a file we didn't create. */
2601 if (earlier_file == NULL)
2602 forget_created (src_sb.st_ino, src_sb.st_dev);
2606 if (rename (dst_backup, dst_name) != 0)
2607 error (0, errno, _("cannot un-backup %s"), quote (dst_name));
2611 printf (_("%s -> %s (unbackup)\n"),
2612 quote_n (0, dst_backup), quote_n (1, dst_name));
2618 static bool _GL_ATTRIBUTE_PURE
2619 valid_options (const struct cp_options *co)
2621 assert (co != NULL);
2622 assert (VALID_BACKUP_TYPE (co->backup_type));
2623 assert (VALID_SPARSE_MODE (co->sparse_mode));
2624 assert (VALID_REFLINK_MODE (co->reflink_mode));
2625 assert (!(co->hard_link && co->symbolic_link));
2627 (co->reflink_mode == REFLINK_ALWAYS
2628 && co->sparse_mode != SPARSE_AUTO));
2632 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
2633 any type. NONEXISTENT_DST should be true if the file DST_NAME
2634 is known not to exist (e.g., because its parent directory was just
2635 created); NONEXISTENT_DST should be false if DST_NAME might already
2636 exist. OPTIONS is ... FIXME-describe
2637 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
2638 same as) DST_NAME; otherwise, set clear it.
2639 Return true if successful. */
2642 copy (char const *src_name, char const *dst_name,
2643 bool nonexistent_dst, const struct cp_options *options,
2644 bool *copy_into_self, bool *rename_succeeded)
2646 assert (valid_options (options));
2648 /* Record the file names: they're used in case of error, when copying
2649 a directory into itself. I don't like to make these tools do *any*
2650 extra work in the common case when that work is solely to handle
2651 exceptional cases, but in this case, I don't see a way to derive the
2652 top level source and destination directory names where they're used.
2653 An alternative is to use COPY_INTO_SELF and print the diagnostic
2654 from every caller -- but I don't want to do that. */
2655 top_level_src_name = src_name;
2656 top_level_dst_name = dst_name;
2658 bool first_dir_created_per_command_line_arg = false;
2659 return copy_internal (src_name, dst_name, nonexistent_dst, 0, NULL,
2661 &first_dir_created_per_command_line_arg,
2662 copy_into_self, rename_succeeded);
2665 /* Set *X to the default options for a value of type struct cp_options. */
2668 cp_options_default (struct cp_options *x)
2670 memset (x, 0, sizeof *x);
2671 #ifdef PRIV_FILE_CHOWN
2673 priv_set_t *pset = priv_allocset ();
2676 if (getppriv (PRIV_EFFECTIVE, pset) == 0)
2678 x->chown_privileges = priv_ismember (pset, PRIV_FILE_CHOWN);
2679 x->owner_privileges = priv_ismember (pset, PRIV_FILE_OWNER);
2681 priv_freeset (pset);
2684 x->chown_privileges = x->owner_privileges = (geteuid () == 0);
2688 /* Return true if it's OK for chown to fail, where errno is
2689 the error number that chown failed with and X is the copying
2693 chown_failure_ok (struct cp_options const *x)
2695 /* If non-root uses -p, it's ok if we can't preserve ownership.
2696 But root probably wants to know, e.g. if NFS disallows it,
2697 or if the target system doesn't support file ownership. */
2699 return ((errno == EPERM || errno == EINVAL) && !x->chown_privileges);
2702 /* Similarly, return true if it's OK for chmod and similar operations
2703 to fail, where errno is the error number that chmod failed with and
2704 X is the copying option set. */
2707 owner_failure_ok (struct cp_options const *x)
2709 return ((errno == EPERM || errno == EINVAL) && !x->owner_privileges);
2712 /* Return the user's umask, caching the result. */
2717 static mode_t mask = (mode_t) -1;
2718 if (mask == (mode_t) -1)