1 /* copy.c -- core functions for copying files and directories
2 Copyright (C) 89, 90, 91, 1995-2008 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/types.h>
23 #include <selinux/selinux.h>
34 #include "backupfile.h"
35 #include "buffer-lcm.h"
38 #include "euidaccess.h"
43 #include "filenamecat.h"
44 #include "full-write.h"
46 #include "hash-triple.h"
51 #include "stat-time.h"
54 #include "write-any-file.h"
55 #include "areadlink.h"
59 # define HAVE_FCHOWN false
60 # define fchown(fd, uid, gid) (-1)
64 # define HAVE_LCHOWN false
65 # define lchown(name, uid, gid) chown (name, uid, gid)
70 rpl_mkfifo (char const *file, mode_t mode)
75 #define mkfifo rpl_mkfifo
82 #define SAME_OWNER(A, B) ((A).st_uid == (B).st_uid)
83 #define SAME_GROUP(A, B) ((A).st_gid == (B).st_gid)
84 #define SAME_OWNER_AND_GROUP(A, B) (SAME_OWNER (A, B) && SAME_GROUP (A, B))
88 struct dir_list *parent;
93 /* Initial size of the cp.dest_info hash table. */
94 #define DEST_INFO_INITIAL_CAPACITY 61
96 static bool copy_internal (char const *src_name, char const *dst_name,
97 bool new_dst, dev_t device,
98 struct dir_list *ancestors,
99 const struct cp_options *x,
100 bool command_line_arg,
101 bool *copy_into_self,
102 bool *rename_succeeded);
103 static bool owner_failure_ok (struct cp_options const *x);
105 /* Pointers to the file names: they're used in the diagnostic that is issued
106 when we detect the user is trying to copy a directory into itself. */
107 static char const *top_level_src_name;
108 static char const *top_level_dst_name;
110 /* The invocation name of this program. */
111 extern char *program_name;
113 /* FIXME: describe */
114 /* FIXME: rewrite this to use a hash table so we avoid the quadratic
115 performance hit that's probably noticeable only on trees deeper
116 than a few hundred levels. See use of active_dir_map in remove.c */
119 is_ancestor (const struct stat *sb, const struct dir_list *ancestors)
121 while (ancestors != 0)
123 if (ancestors->ino == sb->st_ino && ancestors->dev == sb->st_dev)
125 ancestors = ancestors->parent;
130 /* Read the contents of the directory SRC_NAME_IN, and recursively
131 copy the contents to DST_NAME_IN. NEW_DST is true if
132 DST_NAME_IN is a directory that was created previously in the
133 recursion. SRC_SB and ANCESTORS describe SRC_NAME_IN.
134 Set *COPY_INTO_SELF if SRC_NAME_IN is a parent of
135 (or the same as) DST_NAME_IN; otherwise, clear it.
136 Return true if successful. */
139 copy_dir (char const *src_name_in, char const *dst_name_in, bool new_dst,
140 const struct stat *src_sb, struct dir_list *ancestors,
141 const struct cp_options *x, bool *copy_into_self)
145 struct cp_options non_command_line_options = *x;
148 name_space = savedir (src_name_in);
149 if (name_space == NULL)
151 /* This diagnostic is a bit vague because savedir can fail in
152 several different ways. */
153 error (0, errno, _("cannot access %s"), quote (src_name_in));
157 /* For cp's -H option, dereference command line arguments, but do not
158 dereference symlinks that are found via recursive traversal. */
159 if (x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
160 non_command_line_options.dereference = DEREF_NEVER;
163 while (*namep != '\0')
165 bool local_copy_into_self;
166 char *src_name = file_name_concat (src_name_in, namep, NULL);
167 char *dst_name = file_name_concat (dst_name_in, namep, NULL);
169 ok &= copy_internal (src_name, dst_name, new_dst, src_sb->st_dev,
170 ancestors, &non_command_line_options, false,
171 &local_copy_into_self, NULL);
172 *copy_into_self |= local_copy_into_self;
177 namep += strlen (namep) + 1;
183 /* Set the owner and owning group of DEST_DESC to the st_uid and
184 st_gid fields of SRC_SB. If DEST_DESC is undefined (-1), set
185 the owner and owning group of DST_NAME instead; for
186 safety prefer lchown if the system supports it since no
187 symbolic links should be involved. DEST_DESC must
188 refer to the same file as DEST_NAME if defined.
189 Upon failure to set both UID and GID, try to set only the GID.
190 NEW_DST is true if the file was newly created; otherwise,
191 DST_SB is the status of the destination.
192 Return 1 if the initial syscall succeeds, 0 if it fails but it's OK
193 not to preserve ownership, -1 otherwise. */
196 set_owner (const struct cp_options *x, char const *dst_name, int dest_desc,
197 struct stat const *src_sb, bool new_dst,
198 struct stat const *dst_sb)
200 uid_t uid = src_sb->st_uid;
201 gid_t gid = src_sb->st_gid;
203 /* Naively changing the ownership of an already-existing file before
204 changing its permissions would create a window of vulnerability if
205 the file's old permissions are too generous for the new owner and
206 group. Avoid the window by first changing to a restrictive
207 temporary mode if necessary. */
209 if (!new_dst & (x->preserve_mode | x->move_mode | x->set_mode))
211 mode_t old_mode = dst_sb->st_mode;
213 (x->preserve_mode | x->move_mode ? src_sb->st_mode : x->mode);
214 mode_t restrictive_temp_mode = old_mode & new_mode & S_IRWXU;
217 || (old_mode & CHMOD_MODE_BITS
218 & (~new_mode | S_ISUID | S_ISGID | S_ISVTX)))
219 && qset_acl (dst_name, dest_desc, restrictive_temp_mode) != 0)
221 if (! owner_failure_ok (x))
222 error (0, errno, _("clearing permissions for %s"), quote (dst_name));
223 return -x->require_preserve;
227 if (HAVE_FCHOWN && dest_desc != -1)
229 if (fchown (dest_desc, uid, gid) == 0)
231 if (errno == EPERM || errno == EINVAL)
233 /* We've failed to set *both*. Now, try to set just the group
234 ID, but ignore any failure here, and don't change errno. */
235 int saved_errno = errno;
236 (void) fchown (dest_desc, -1, gid);
242 if (lchown (dst_name, uid, gid) == 0)
244 if (errno == EPERM || errno == EINVAL)
246 /* We've failed to set *both*. Now, try to set just the group
247 ID, but ignore any failure here, and don't change errno. */
248 int saved_errno = errno;
249 (void) lchown (dst_name, -1, gid);
254 if (! chown_failure_ok (x))
256 error (0, errno, _("failed to preserve ownership for %s"),
258 if (x->require_preserve)
265 /* Set the st_author field of DEST_DESC to the st_author field of
266 SRC_SB. If DEST_DESC is undefined (-1), set the st_author field
267 of DST_NAME instead. DEST_DESC must refer to the same file as
268 DEST_NAME if defined. */
271 set_author (const char *dst_name, int dest_desc, const struct stat *src_sb)
273 #if HAVE_STRUCT_STAT_ST_AUTHOR
274 /* FIXME: Modify the following code so that it does not
275 follow symbolic links. */
277 /* Preserve the st_author field. */
278 file_t file = (dest_desc < 0
279 ? file_name_lookup (dst_name, 0, 0)
280 : getdport (dest_desc));
281 if (file == MACH_PORT_NULL)
282 error (0, errno, _("failed to lookup file %s"), quote (dst_name));
285 error_t err = file_chauthor (file, src_sb->st_author);
287 error (0, err, _("failed to preserve authorship for %s"),
289 mach_port_deallocate (mach_task_self (), file);
298 /* Change the file mode bits of the file identified by DESC or NAME to MODE.
299 Use DESC if DESC is valid and fchmod is available, NAME otherwise. */
302 fchmod_or_lchmod (int desc, char const *name, mode_t mode)
306 return fchmod (desc, mode);
308 return lchmod (name, mode);
311 /* Copy a regular file from SRC_NAME to DST_NAME.
312 If the source file contains holes, copies holes and blocks of zeros
313 in the source file as holes in the destination file.
314 (Holes are read as zeroes by the `read' system call.)
315 When creating the destination, use DST_MODE & ~OMITTED_PERMISSIONS
316 as the third argument in the call to open, adding
317 OMITTED_PERMISSIONS after copying as needed.
318 X provides many option settings.
319 Return true if successful.
320 *NEW_DST is as in copy_internal.
321 SRC_SB is the result of calling XSTAT (aka stat) on SRC_NAME. */
324 copy_reg (char const *src_name, char const *dst_name,
325 const struct cp_options *x,
326 mode_t dst_mode, mode_t omitted_permissions, bool *new_dst,
327 struct stat const *src_sb)
330 char *buf_alloc = NULL;
331 char *name_alloc = NULL;
335 mode_t src_mode = src_sb->st_mode;
337 struct stat src_open_sb;
338 bool return_val = true;
340 source_desc = open (src_name,
342 | (x->dereference == DEREF_NEVER ? O_NOFOLLOW : 0)));
345 error (0, errno, _("cannot open %s for reading"), quote (src_name));
349 if (fstat (source_desc, &src_open_sb) != 0)
351 error (0, errno, _("cannot fstat %s"), quote (src_name));
356 /* Compare the source dev/ino from the open file to the incoming,
357 saved ones obtained via a previous call to stat. */
358 if (! SAME_INODE (*src_sb, src_open_sb))
361 _("skipping file %s, as it was replaced while being copied"),
367 /* The semantics of the following open calls are mandated
368 by the specs for both cp and mv. */
371 dest_desc = open (dst_name, O_WRONLY | O_TRUNC | O_BINARY);
374 /* When using cp --preserve=context to copy to an existing destination,
375 use the default context rather than that of the source. Why?
376 1) the src context may prohibit writing, and
377 2) because it's more consistent to use the same context
378 that is used when the destination file doesn't already exist. */
379 if (x->preserve_security_context && 0 <= dest_desc)
381 security_context_t con = NULL;
382 if (getfscreatecon (&con) < 0)
384 error (0, errno, _("failed to get file system create context"));
385 if (x->require_preserve_context)
388 goto close_src_and_dst_desc;
394 if (fsetfilecon (dest_desc, con) < 0)
397 _("failed to set the security context of %s to %s"),
398 quote_n (0, dst_name), quote_n (1, con));
399 if (x->require_preserve_context)
403 goto close_src_and_dst_desc;
410 if (dest_desc < 0 && x->unlink_dest_after_failed_open)
412 if (unlink (dst_name) != 0)
414 error (0, errno, _("cannot remove %s"), quote (dst_name));
419 printf (_("removed %s\n"), quote (dst_name));
421 /* Tell caller that the destination file was unlinked. */
428 int open_flags = O_WRONLY | O_CREAT | O_BINARY;
429 dest_desc = open (dst_name, open_flags | O_EXCL ,
430 dst_mode & ~omitted_permissions);
433 /* When trying to copy through a dangling destination symlink,
434 the above open fails with EEXIST. If that happens, and
435 lstat'ing the DST_NAME shows that it is a symlink, then we
436 have a problem: trying to resolve this dangling symlink to
437 a directory/destination-entry pair is fundamentally racy,
438 so punt. If POSIXLY_CORRECT is set, simply call open again,
439 but without O_EXCL (potentially dangerous). If not, fail
440 with a diagnostic. These shenanigans are necessary only
441 when copying, i.e., not in move_mode. */
442 if (dest_desc < 0 && dest_errno == EEXIST && ! x->move_mode)
444 struct stat dangling_link_sb;
445 if (lstat (dst_name, &dangling_link_sb) == 0
446 && S_ISLNK (dangling_link_sb.st_mode))
448 if (x->open_dangling_dest_symlink)
450 dest_desc = open (dst_name, open_flags,
451 dst_mode & ~omitted_permissions);
456 error (0, 0, _("not writing through dangling symlink %s"),
465 omitted_permissions = 0;
469 error (0, dest_errno, _("cannot create regular file %s"),
475 if (fstat (dest_desc, &sb) != 0)
477 error (0, errno, _("cannot fstat %s"), quote (dst_name));
479 goto close_src_and_dst_desc;
483 typedef uintptr_t word;
484 off_t n_read_total = 0;
486 /* Choose a suitable buffer size; it may be adjusted later. */
487 size_t buf_alignment = lcm (getpagesize (), sizeof (word));
488 size_t buf_alignment_slop = sizeof (word) + buf_alignment - 1;
489 size_t buf_size = ST_BLKSIZE (sb);
491 /* Deal with sparse files. */
492 bool last_write_made_hole = false;
493 bool make_holes = false;
495 if (S_ISREG (sb.st_mode))
497 /* Even with --sparse=always, try to create holes only
498 if the destination is a regular file. */
499 if (x->sparse_mode == SPARSE_ALWAYS)
502 #if HAVE_STRUCT_STAT_ST_BLOCKS
503 /* Use a heuristic to determine whether SRC_NAME contains any sparse
504 blocks. If the file has fewer blocks than would normally be
505 needed for a file of its size, then at least one of the blocks in
506 the file is a hole. */
507 if (x->sparse_mode == SPARSE_AUTO && S_ISREG (src_open_sb.st_mode)
508 && ST_NBLOCKS (src_open_sb) < src_open_sb.st_size / ST_NBLOCKSIZE)
513 /* If not making a sparse file, try to use a more-efficient
517 /* These days there's no point ever messing with buffers smaller
518 than 8 KiB. It would be nice to configure SMALL_BUF_SIZE
519 dynamically for this host and pair of files, but there doesn't
520 seem to be a good way to get readahead info portably. */
521 enum { SMALL_BUF_SIZE = 8 * 1024 };
523 /* Compute the least common multiple of the input and output
524 buffer sizes, adjusting for outlandish values. */
525 size_t blcm_max = MIN (SIZE_MAX, SSIZE_MAX) - buf_alignment_slop;
526 size_t blcm = buffer_lcm (ST_BLKSIZE (src_open_sb), buf_size,
529 /* Do not use a block size that is too small. */
530 buf_size = MAX (SMALL_BUF_SIZE, blcm);
532 /* Do not bother with a buffer larger than the input file, plus one
533 byte to make sure the file has not grown while reading it. */
534 if (S_ISREG (src_open_sb.st_mode) && src_open_sb.st_size < buf_size)
535 buf_size = src_open_sb.st_size + 1;
537 /* However, stick with a block size that is a positive multiple of
538 blcm, overriding the above adjustments. Watch out for
540 buf_size += blcm - 1;
541 buf_size -= buf_size % blcm;
542 if (buf_size == 0 || blcm_max < buf_size)
546 /* Make a buffer with space for a sentinel at the end. */
547 buf_alloc = xmalloc (buf_size + buf_alignment_slop);
548 buf = ptr_align (buf_alloc, buf_alignment);
554 ssize_t n_read = read (source_desc, buf, buf_size);
561 error (0, errno, _("reading %s"), quote (src_name));
563 goto close_src_and_dst_desc;
568 n_read_total += n_read;
574 /* Sentinel to stop loop. */
577 /* Usually, buf[n_read] is not the byte just before a "word"
578 (aka uintptr_t) boundary. In that case, the word-oriented
579 test below (*wp++ == 0) would read some uninitialized bytes
580 after the sentinel. To avoid false-positive reports about
581 this condition (e.g., from a tool like valgrind), set the
582 remaining bytes -- to any value. */
583 memset (buf + n_read + 1, 0, sizeof (word) - 1);
586 /* Find first nonzero *word*, or the word with the sentinel. */
592 /* Find the first nonzero *byte*, or the sentinel. */
594 cp = (char *) (wp - 1);
598 if (cp <= buf + n_read)
599 /* Clear to indicate that a normal write is needed. */
603 /* We found the sentinel, so the whole input block was zero.
605 if (lseek (dest_desc, n_read, SEEK_CUR) < 0)
607 error (0, errno, _("cannot lseek %s"), quote (dst_name));
609 goto close_src_and_dst_desc;
611 last_write_made_hole = true;
618 if (full_write (dest_desc, buf, n) != n)
620 error (0, errno, _("writing %s"), quote (dst_name));
622 goto close_src_and_dst_desc;
624 last_write_made_hole = false;
626 /* A short read on a regular file means EOF. */
627 if (n_read != buf_size && S_ISREG (src_open_sb.st_mode))
632 /* If the file ends with a `hole', we need to do something to record
633 the length of the file. On modern systems, calling ftruncate does
634 the job. On systems without native ftruncate support, we have to
635 write a byte at the ending position. Otherwise the kernel would
636 truncate the file at the end of the last write operation. */
638 if (last_write_made_hole)
641 ? /* ftruncate sets the file size,
642 so there is no need for a write. */
643 ftruncate (dest_desc, n_read_total) < 0
644 : /* Seek backwards one character and write a null. */
645 (lseek (dest_desc, (off_t) -1, SEEK_CUR) < 0L
646 || full_write (dest_desc, "", 1) != 1))
648 error (0, errno, _("writing %s"), quote (dst_name));
650 goto close_src_and_dst_desc;
655 if (x->preserve_timestamps)
657 struct timespec timespec[2];
658 timespec[0] = get_stat_atime (src_sb);
659 timespec[1] = get_stat_mtime (src_sb);
661 if (gl_futimens (dest_desc, dst_name, timespec) != 0)
663 error (0, errno, _("preserving times for %s"), quote (dst_name));
664 if (x->require_preserve)
667 goto close_src_and_dst_desc;
672 if (x->preserve_ownership && ! SAME_OWNER_AND_GROUP (*src_sb, sb))
674 switch (set_owner (x, dst_name, dest_desc, src_sb, *new_dst, &sb))
678 goto close_src_and_dst_desc;
681 src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX);
686 set_author (dst_name, dest_desc, src_sb);
688 if (x->preserve_mode || x->move_mode)
690 if (copy_acl (src_name, source_desc, dst_name, dest_desc, src_mode) != 0
691 && x->require_preserve)
694 else if (x->set_mode)
696 if (set_acl (dst_name, dest_desc, x->mode) != 0)
699 else if (omitted_permissions)
701 omitted_permissions &= ~ cached_umask ();
702 if (omitted_permissions
703 && fchmod_or_lchmod (dest_desc, dst_name, dst_mode) != 0)
705 error (0, errno, _("preserving permissions for %s"),
707 if (x->require_preserve)
712 close_src_and_dst_desc:
713 if (close (dest_desc) < 0)
715 error (0, errno, _("closing %s"), quote (dst_name));
719 if (close (source_desc) < 0)
721 error (0, errno, _("closing %s"), quote (src_name));
730 /* Return true if it's ok that the source and destination
731 files are the `same' by some measure. The goal is to avoid
732 making the `copy' operation remove both copies of the file
733 in that case, while still allowing the user to e.g., move or
734 copy a regular file onto a symlink that points to it.
735 Try to minimize the cost of this function in the common case.
736 Set *RETURN_NOW if we've determined that the caller has no more
737 work to do and should return successfully, right away.
739 Set *UNLINK_SRC if we've determined that the caller wants to do
740 `rename (a, b)' where `a' and `b' are distinct hard links to the same
741 file. In that case, the caller should try to unlink `a' and then return
742 successfully. Ideally, we wouldn't have to do that, and we'd be
743 able to rely on rename to remove the source file. However, POSIX
744 mistakenly requires that such a rename call do *nothing* and return
748 same_file_ok (char const *src_name, struct stat const *src_sb,
749 char const *dst_name, struct stat const *dst_sb,
750 const struct cp_options *x, bool *return_now, bool *unlink_src)
752 const struct stat *src_sb_link;
753 const struct stat *dst_sb_link;
754 struct stat tmp_dst_sb;
755 struct stat tmp_src_sb;
758 bool same = SAME_INODE (*src_sb, *dst_sb);
763 /* FIXME: this should (at the very least) be moved into the following
764 if-block. More likely, it should be removed, because it inhibits
765 making backups. But removing it will result in a change in behavior
766 that will probably have to be documented -- and tests will have to
768 if (same && x->hard_link)
774 if (x->dereference == DEREF_NEVER)
778 /* If both the source and destination files are symlinks (and we'll
779 know this here IFF preserving symlinks), then it's ok -- as long
780 as they are distinct. */
781 if (S_ISLNK (src_sb->st_mode) && S_ISLNK (dst_sb->st_mode))
782 return ! same_name (src_name, dst_name);
784 src_sb_link = src_sb;
785 dst_sb_link = dst_sb;
792 if (lstat (dst_name, &tmp_dst_sb) != 0
793 || lstat (src_name, &tmp_src_sb) != 0)
796 src_sb_link = &tmp_src_sb;
797 dst_sb_link = &tmp_dst_sb;
799 same_link = SAME_INODE (*src_sb_link, *dst_sb_link);
801 /* If both are symlinks, then it's ok, but only if the destination
802 will be unlinked before being opened. This is like the test
803 above, but with the addition of the unlink_dest_before_opening
804 conjunct because otherwise, with two symlinks to the same target,
805 we'd end up truncating the source file. */
806 if (S_ISLNK (src_sb_link->st_mode) && S_ISLNK (dst_sb_link->st_mode)
807 && x->unlink_dest_before_opening)
811 /* The backup code ensures there's a copy, so it's usually ok to
812 remove any destination file. One exception is when both
813 source and destination are the same directory entry. In that
814 case, moving the destination file aside (in making the backup)
815 would also rename the source file and result in an error. */
816 if (x->backup_type != no_backups)
820 /* In copy mode when dereferencing symlinks, if the source is a
821 symlink and the dest is not, then backing up the destination
822 (moving it aside) would make it a dangling symlink, and the
823 subsequent attempt to open it in copy_reg would fail with
824 a misleading diagnostic. Avoid that by returning zero in
825 that case so the caller can make cp (or mv when it has to
826 resort to reading the source file) fail now. */
828 /* FIXME-note: even with the following kludge, we can still provoke
829 the offending diagnostic. It's just a little harder to do :-)
830 $ rm -f a b c; touch c; ln -s c b; ln -s b a; cp -b a b
831 cp: cannot open `a' for reading: No such file or directory
832 That's misleading, since a subsequent `ls' shows that `a'
834 One solution would be to open the source file *before* moving
835 aside the destination, but that'd involve a big rewrite. */
837 && x->dereference != DEREF_NEVER
838 && S_ISLNK (src_sb_link->st_mode)
839 && ! S_ISLNK (dst_sb_link->st_mode))
845 return ! same_name (src_name, dst_name);
849 /* FIXME: use or remove */
851 /* If we're making a backup, we'll detect the problem case in
852 copy_reg because SRC_NAME will no longer exist. Allowing
853 the test to be deferred lets cp do some useful things.
854 But when creating hardlinks and SRC_NAME is a symlink
855 but DST_NAME is not we must test anyway. */
857 || !S_ISLNK (src_sb_link->st_mode)
858 || S_ISLNK (dst_sb_link->st_mode))
861 if (x->dereference != DEREF_NEVER)
865 /* They may refer to the same file if we're in move mode and the
866 target is a symlink. That is ok, since we remove any existing
867 destination file before opening it -- via `rename' if they're on
868 the same file system, via `unlink (DST_NAME)' otherwise.
869 It's also ok if they're distinct hard links to the same file. */
870 if (x->move_mode || x->unlink_dest_before_opening)
872 if (S_ISLNK (dst_sb_link->st_mode))
876 && 1 < dst_sb_link->st_nlink
877 && ! same_name (src_name, dst_name))
888 /* If neither is a symlink, then it's ok as long as they aren't
889 hard links to the same file. */
890 if (!S_ISLNK (src_sb_link->st_mode) && !S_ISLNK (dst_sb_link->st_mode))
892 if (!SAME_INODE (*src_sb_link, *dst_sb_link))
895 /* If they are the same file, it's ok if we're making hard links. */
903 /* It's ok to remove a destination symlink. But that works only when we
904 unlink before opening the destination and when the source and destination
905 files are on the same partition. */
906 if (x->unlink_dest_before_opening
907 && S_ISLNK (dst_sb_link->st_mode))
908 return dst_sb_link->st_dev == src_sb_link->st_dev;
910 if (x->dereference == DEREF_NEVER)
912 if ( ! S_ISLNK (src_sb_link->st_mode))
913 tmp_src_sb = *src_sb_link;
914 else if (stat (src_name, &tmp_src_sb) != 0)
917 if ( ! S_ISLNK (dst_sb_link->st_mode))
918 tmp_dst_sb = *dst_sb_link;
919 else if (stat (dst_name, &tmp_dst_sb) != 0)
922 if ( ! SAME_INODE (tmp_src_sb, tmp_dst_sb))
925 /* FIXME: shouldn't this be testing whether we're making symlinks? */
936 /* Return true if FILE, with mode MODE, is writable in the sense of 'mv'.
937 Always consider a symbolic link to be writable. */
939 writable_destination (char const *file, mode_t mode)
941 return (S_ISLNK (mode)
942 || can_write_any_file ()
943 || euidaccess (file, W_OK) == 0);
947 overwrite_prompt (char const *dst_name, struct stat const *dst_sb)
949 if (! writable_destination (dst_name, dst_sb->st_mode))
951 char perms[12]; /* "-rwxrwxrwx " ls-style modes. */
952 strmode (dst_sb->st_mode, perms);
955 _("%s: try to overwrite %s, overriding mode %04lo (%s)? "),
956 program_name, quote (dst_name),
957 (unsigned long int) (dst_sb->st_mode & CHMOD_MODE_BITS),
962 fprintf (stderr, _("%s: overwrite %s? "),
963 program_name, quote (dst_name));
967 /* Initialize the hash table implementing a set of F_triple entries
968 corresponding to destination files. */
970 dest_info_init (struct cp_options *x)
973 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
980 /* Initialize the hash table implementing a set of F_triple entries
981 corresponding to source files listed on the command line. */
983 src_info_init (struct cp_options *x)
986 /* Note that we use triple_hash_no_name here.
987 Contrast with the use of triple_hash above.
988 That is necessary because a source file may be specified
989 in many different ways. We want to warn about this
995 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
1002 /* When effecting a move (e.g., for mv(1)), and given the name DST_NAME
1003 of the destination and a corresponding stat buffer, DST_SB, return
1004 true if the logical `move' operation should _not_ proceed.
1005 Otherwise, return false.
1006 Depending on options specified in X, this code may issue an
1007 interactive prompt asking whether it's ok to overwrite DST_NAME. */
1009 abandon_move (const struct cp_options *x,
1010 char const *dst_name,
1011 struct stat const *dst_sb)
1013 assert (x->move_mode);
1014 return (x->interactive == I_ALWAYS_NO
1015 || ((x->interactive == I_ASK_USER
1016 || (x->interactive == I_UNSPECIFIED
1018 && ! writable_destination (dst_name, dst_sb->st_mode)))
1019 && (overwrite_prompt (dst_name, dst_sb), 1)
1023 /* Print --verbose output on standard output, e.g. `new' -> `old'.
1024 If BACKUP_DST_NAME is non-NULL, then also indicate that it is
1025 the name of a backup file. */
1027 emit_verbose (char const *src, char const *dst, char const *backup_dst_name)
1029 printf ("%s -> %s", quote_n (0, src), quote_n (1, dst));
1030 if (backup_dst_name)
1031 printf (_(" (backup: %s)"), quote (backup_dst_name));
1035 /* A wrapper around "setfscreatecon (NULL)" that exits upon failure. */
1037 restore_default_fscreatecon_or_die (void)
1039 if (setfscreatecon (NULL) != 0)
1040 error (EXIT_FAILURE, errno,
1041 _("failed to restore the default file creation context"));
1044 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
1045 any type. NEW_DST should be true if the file DST_NAME cannot
1046 exist because its parent directory was just created; NEW_DST should
1047 be false if DST_NAME might already exist. DEVICE is the device
1048 number of the parent directory, or 0 if the parent of this file is
1049 not known. ANCESTORS points to a linked, null terminated list of
1050 devices and inodes of parent directories of SRC_NAME. COMMAND_LINE_ARG
1051 is true iff SRC_NAME was specified on the command line.
1052 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
1053 same as) DST_NAME; otherwise, clear it.
1054 Return true if successful. */
1056 copy_internal (char const *src_name, char const *dst_name,
1059 struct dir_list *ancestors,
1060 const struct cp_options *x,
1061 bool command_line_arg,
1062 bool *copy_into_self,
1063 bool *rename_succeeded)
1068 mode_t dst_mode IF_LINT (= 0);
1069 mode_t dst_mode_bits;
1070 mode_t omitted_permissions;
1071 bool restore_dst_mode = false;
1072 char *earlier_file = NULL;
1073 char *dst_backup = NULL;
1074 bool backup_succeeded = false;
1076 bool copied_as_regular = false;
1077 bool preserve_metadata;
1078 bool have_dst_lstat = false;
1080 if (x->move_mode && rename_succeeded)
1081 *rename_succeeded = false;
1083 *copy_into_self = false;
1085 if (XSTAT (x, src_name, &src_sb) != 0)
1087 error (0, errno, _("cannot stat %s"), quote (src_name));
1091 src_mode = src_sb.st_mode;
1093 if (S_ISDIR (src_mode) && !x->recursive)
1095 error (0, 0, _("omitting directory %s"), quote (src_name));
1099 /* Detect the case in which the same source file appears more than
1100 once on the command line and no backup option has been selected.
1101 If so, simply warn and don't copy it the second time.
1102 This check is enabled only if x->src_info is non-NULL. */
1103 if (command_line_arg)
1105 if ( ! S_ISDIR (src_sb.st_mode)
1106 && x->backup_type == no_backups
1107 && seen_file (x->src_info, src_name, &src_sb))
1109 error (0, 0, _("warning: source file %s specified more than once"),
1114 record_file (x->src_info, src_name, &src_sb);
1119 /* Regular files can be created by writing through symbolic
1120 links, but other files cannot. So use stat on the
1121 destination when copying a regular file, and lstat otherwise.
1122 However, if we intend to unlink or remove the destination
1123 first, use lstat, since a copy won't actually be made to the
1124 destination in that case. */
1126 ((S_ISREG (src_mode)
1127 || (x->copy_as_regular
1128 && ! (S_ISDIR (src_mode) || S_ISLNK (src_mode))))
1129 && ! (x->move_mode || x->symbolic_link || x->hard_link
1130 || x->backup_type != no_backups
1131 || x->unlink_dest_before_opening));
1133 ? stat (dst_name, &dst_sb)
1134 : lstat (dst_name, &dst_sb))
1137 if (errno != ENOENT)
1139 error (0, errno, _("cannot stat %s"), quote (dst_name));
1148 { /* Here, we know that dst_name exists, at least to the point
1149 that it is stat'able or lstat'able. */
1153 have_dst_lstat = !use_stat;
1154 if (! same_file_ok (src_name, &src_sb, dst_name, &dst_sb,
1155 x, &return_now, &unlink_src))
1157 error (0, 0, _("%s and %s are the same file"),
1158 quote_n (0, src_name), quote_n (1, dst_name));
1162 if (!S_ISDIR (src_mode) && x->update)
1164 /* When preserving time stamps (but not moving within a file
1165 system), don't worry if the destination time stamp is
1166 less than the source merely because of time stamp
1168 int options = ((x->preserve_timestamps
1170 && dst_sb.st_dev == src_sb.st_dev))
1171 ? UTIMECMP_TRUNCATE_SOURCE
1174 if (0 <= utimecmp (dst_name, &dst_sb, &src_sb, options))
1176 /* We're using --update and the destination is not older
1177 than the source, so do not copy or move. Pretend the
1178 rename succeeded, so the caller (if it's mv) doesn't
1179 end up removing the source file. */
1180 if (rename_succeeded)
1181 *rename_succeeded = true;
1186 /* When there is an existing destination file, we may end up
1187 returning early, and hence not copying/moving the file.
1188 This may be due to an interactive `negative' reply to the
1189 prompt about the existing file. It may also be due to the
1190 use of the --reply=no option.
1192 cp and mv treat -i and -f differently. */
1195 if (abandon_move (x, dst_name, &dst_sb)
1196 || (unlink_src && unlink (src_name) == 0))
1198 /* Pretend the rename succeeded, so the caller (mv)
1199 doesn't end up removing the source file. */
1200 if (rename_succeeded)
1201 *rename_succeeded = true;
1202 if (unlink_src && x->verbose)
1203 printf (_("removed %s\n"), quote (src_name));
1208 error (0, errno, _("cannot remove %s"), quote (src_name));
1214 if (! S_ISDIR (src_mode)
1215 && (x->interactive == I_ALWAYS_NO
1216 || (x->interactive == I_ASK_USER
1217 && (overwrite_prompt (dst_name, &dst_sb), 1)
1225 if (!S_ISDIR (dst_sb.st_mode))
1227 if (S_ISDIR (src_mode))
1229 if (x->move_mode && x->backup_type != no_backups)
1231 /* Moving a directory onto an existing
1232 non-directory is ok only with --backup. */
1237 _("cannot overwrite non-directory %s with directory %s"),
1238 quote_n (0, dst_name), quote_n (1, src_name));
1243 /* Don't let the user destroy their data, even if they try hard:
1244 This mv command must fail (likewise for cp):
1245 rm -rf a b c; mkdir a b c; touch a/f b/f; mv a/f b/f c
1246 Otherwise, the contents of b/f would be lost.
1247 In the case of `cp', b/f would be lost if the user simulated
1248 a move using cp and rm.
1249 Note that it works fine if you use --backup=numbered. */
1250 if (command_line_arg
1251 && x->backup_type != numbered_backups
1252 && seen_file (x->dest_info, dst_name, &dst_sb))
1255 _("will not overwrite just-created %s with %s"),
1256 quote_n (0, dst_name), quote_n (1, src_name));
1261 if (!S_ISDIR (src_mode))
1263 if (S_ISDIR (dst_sb.st_mode))
1265 if (x->move_mode && x->backup_type != no_backups)
1267 /* Moving a non-directory onto an existing
1268 directory is ok only with --backup. */
1273 _("cannot overwrite directory %s with non-directory"),
1282 /* Don't allow user to move a directory onto a non-directory. */
1283 if (S_ISDIR (src_sb.st_mode) && !S_ISDIR (dst_sb.st_mode)
1284 && x->backup_type == no_backups)
1287 _("cannot move directory onto non-directory: %s -> %s"),
1288 quote_n (0, src_name), quote_n (0, dst_name));
1293 if (x->backup_type != no_backups
1294 /* Don't try to back up a destination if the last
1295 component of src_name is "." or "..". */
1296 && ! dot_or_dotdot (last_component (src_name))
1297 /* Create a backup of each destination directory in move mode,
1298 but not in copy mode. FIXME: it might make sense to add an
1299 option to suppress backup creation also for move mode.
1300 That would let one use mv to merge new content into an
1301 existing hierarchy. */
1302 && (x->move_mode || ! S_ISDIR (dst_sb.st_mode)))
1304 char *tmp_backup = find_backup_file_name (dst_name,
1307 /* Detect (and fail) when creating the backup file would
1308 destroy the source file. Before, running the commands
1309 cd /tmp; rm -f a a~; : > a; echo A > a~; cp --b=simple a~ a
1310 would leave two zero-length files: a and a~. */
1311 /* FIXME: but simply change e.g., the final a~ to `./a~'
1312 and the source will still be destroyed. */
1313 if (STREQ (tmp_backup, src_name))
1317 ? _("backing up %s would destroy source; %s not moved")
1318 : _("backing up %s would destroy source; %s not copied"));
1320 quote_n (0, dst_name),
1321 quote_n (1, src_name));
1327 Using alloca for a file name that may be arbitrarily
1328 long is not recommended. In fact, even forming such a name
1329 should be discouraged. Eventually, this code will be rewritten
1330 to use fts, so using alloca here will be less of a problem. */
1331 ASSIGN_STRDUPA (dst_backup, tmp_backup);
1333 if (rename (dst_name, dst_backup) != 0)
1335 if (errno != ENOENT)
1337 error (0, errno, _("cannot backup %s"), quote (dst_name));
1347 backup_succeeded = true;
1351 else if (! S_ISDIR (dst_sb.st_mode)
1352 /* Never unlink dst_name when in move mode. */
1354 && (x->unlink_dest_before_opening
1355 || (x->preserve_links && 1 < dst_sb.st_nlink)
1356 || (x->dereference == DEREF_NEVER
1357 && ! S_ISREG (src_sb.st_mode))
1360 if (unlink (dst_name) != 0 && errno != ENOENT)
1362 error (0, errno, _("cannot remove %s"), quote (dst_name));
1367 printf (_("removed %s\n"), quote (dst_name));
1372 /* Ensure we don't try to copy through a symlink that was
1373 created by a prior call to this function. */
1374 if (command_line_arg
1377 && x->backup_type == no_backups)
1379 bool lstat_ok = true;
1380 struct stat tmp_buf;
1381 struct stat *dst_lstat_sb;
1383 /* If we called lstat above, good: use that data.
1384 Otherwise, call lstat here, in case dst_name is a symlink. */
1386 dst_lstat_sb = &dst_sb;
1389 if (lstat (dst_name, &tmp_buf) == 0)
1390 dst_lstat_sb = &tmp_buf;
1395 /* Never copy through a symlink we've just created. */
1397 && S_ISLNK (dst_lstat_sb->st_mode)
1398 && seen_file (x->dest_info, dst_name, dst_lstat_sb))
1401 _("will not copy %s through just-created symlink %s"),
1402 quote_n (0, src_name), quote_n (1, dst_name));
1407 /* If the source is a directory, we don't always create the destination
1408 directory. So --verbose should not announce anything until we're
1409 sure we'll create a directory. */
1410 if (x->verbose && !S_ISDIR (src_mode))
1411 emit_verbose (src_name, dst_name, backup_succeeded ? dst_backup : NULL);
1413 /* Associate the destination file name with the source device and inode
1414 so that if we encounter a matching dev/ino pair in the source tree
1415 we can arrange to create a hard link between the corresponding names
1416 in the destination tree.
1418 Sometimes, when preserving links, we have to record dev/ino even
1419 though st_nlink == 1:
1420 - when in move_mode, since we may be moving a group of N hard-linked
1421 files (via two or more command line arguments) to a different
1422 partition; the links may be distributed among the command line
1423 arguments (possibly hierarchies) so that the link count of
1424 the final, once-linked source file is reduced to 1 when it is
1425 considered below. But in this case (for mv) we don't need to
1426 incur the expense of recording the dev/ino => name mapping; all we
1427 really need is a lookup, to see if the dev/ino pair has already
1429 - when using -H and processing a command line argument;
1430 that command line argument could be a symlink pointing to another
1431 command line argument. With `cp -H --preserve=link', we hard-link
1432 those two destination files.
1433 - likewise for -L except that it applies to all files, not just
1434 command line arguments.
1436 Also record directory dev/ino when using --recursive. We'll use that
1437 info to detect this problem: cp -R dir dir. FIXME-maybe: ideally,
1438 directory info would be recorded in a separate hash table, since
1439 such entries are useful only while a single command line hierarchy
1440 is being copied -- so that separate table could be cleared between
1441 command line args. Using the same hash table to preserve hard
1442 links means that it may not be cleared. */
1444 if (x->move_mode && src_sb.st_nlink == 1)
1446 earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev);
1448 else if ((x->preserve_links
1449 && (1 < src_sb.st_nlink
1450 || (command_line_arg
1451 && x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
1452 || x->dereference == DEREF_ALWAYS))
1453 || (x->recursive && S_ISDIR (src_mode)))
1455 earlier_file = remember_copied (dst_name, src_sb.st_ino, src_sb.st_dev);
1458 /* Did we copy this inode somewhere else (in this command line argument)
1459 and therefore this is a second hard link to the inode? */
1463 /* Avoid damaging the destination file system by refusing to preserve
1464 hard-linked directories (which are found at least in Netapp snapshot
1466 if (S_ISDIR (src_mode))
1468 /* If src_name and earlier_file refer to the same directory entry,
1469 then warn about copying a directory into itself. */
1470 if (same_name (src_name, earlier_file))
1472 error (0, 0, _("cannot copy a directory, %s, into itself, %s"),
1473 quote_n (0, top_level_src_name),
1474 quote_n (1, top_level_dst_name));
1475 *copy_into_self = true;
1478 else if (x->dereference == DEREF_ALWAYS)
1480 /* This happens when e.g., encountering a directory for the
1481 second or subsequent time via symlinks when cp is invoked
1482 with -R and -L. E.g.,
1483 rm -rf a b c d; mkdir a b c d; ln -s ../c a; ln -s ../c b;
1489 error (0, 0, _("will not create hard link %s to directory %s"),
1490 quote_n (0, dst_name), quote_n (1, earlier_file));
1496 bool link_failed = (link (earlier_file, dst_name) != 0);
1498 /* If the link failed because of an existing destination,
1499 remove that file and then call link again. */
1500 if (link_failed && errno == EEXIST)
1502 if (unlink (dst_name) != 0)
1504 error (0, errno, _("cannot remove %s"), quote (dst_name));
1508 printf (_("removed %s\n"), quote (dst_name));
1509 link_failed = (link (earlier_file, dst_name) != 0);
1514 error (0, errno, _("cannot create hard link %s to %s"),
1515 quote_n (0, dst_name), quote_n (1, earlier_file));
1525 if (rename (src_name, dst_name) == 0)
1527 if (x->verbose && S_ISDIR (src_mode))
1528 emit_verbose (src_name, dst_name,
1529 backup_succeeded ? dst_backup : NULL);
1531 if (rename_succeeded)
1532 *rename_succeeded = true;
1534 if (command_line_arg)
1536 /* Record destination dev/ino/name, so that if we are asked
1537 to overwrite that file again, we can detect it and fail. */
1538 /* It's fine to use the _source_ stat buffer (src_sb) to get the
1539 _destination_ dev/ino, since the rename above can't have
1540 changed those, and `mv' always uses lstat.
1541 We could limit it further by operating
1542 only on non-directories. */
1543 record_file (x->dest_info, dst_name, &src_sb);
1549 /* FIXME: someday, consider what to do when moving a directory into
1550 itself but when source and destination are on different devices. */
1552 /* This happens when attempting to rename a directory to a
1553 subdirectory of itself. */
1554 if (errno == EINVAL)
1556 /* FIXME: this is a little fragile in that it relies on rename(2)
1557 failing with a specific errno value. Expect problems on
1558 non-POSIX systems. */
1559 error (0, 0, _("cannot move %s to a subdirectory of itself, %s"),
1560 quote_n (0, top_level_src_name),
1561 quote_n (1, top_level_dst_name));
1563 /* Note that there is no need to call forget_created here,
1564 (compare with the other calls in this file) since the
1565 destination directory didn't exist before. */
1567 *copy_into_self = true;
1568 /* FIXME-cleanup: Don't return true here; adjust mv.c accordingly.
1569 The only caller that uses this code (mv.c) ends up setting its
1570 exit status to nonzero when copy_into_self is nonzero. */
1574 /* WARNING: there probably exist systems for which an inter-device
1575 rename fails with a value of errno not handled here.
1576 If/as those are reported, add them to the condition below.
1577 If this happens to you, please do the following and send the output
1578 to the bug-reporting address (e.g., in the output of cp --help):
1579 touch k; perl -e 'rename "k","/tmp/k" or print "$!(",$!+0,")\n"'
1580 where your current directory is on one partion and /tmp is the other.
1581 Also, please try to find the E* errno macro name corresponding to
1582 the diagnostic and parenthesized integer, and include that in your
1583 e-mail. One way to do that is to run a command like this
1584 find /usr/include/. -type f \
1585 | xargs grep 'define.*\<E[A-Z]*\>.*\<18\>' /dev/null
1586 where you'd replace `18' with the integer in parentheses that
1587 was output from the perl one-liner above.
1588 If necessary, of course, change `/tmp' to some other directory. */
1591 /* There are many ways this can happen due to a race condition.
1592 When something happens between the initial XSTAT and the
1593 subsequent rename, we can get many different types of errors.
1594 For example, if the destination is initially a non-directory
1595 or non-existent, but it is created as a directory, the rename
1596 fails. If two `mv' commands try to rename the same file at
1597 about the same time, one will succeed and the other will fail.
1598 If the permissions on the directory containing the source or
1599 destination file are made too restrictive, the rename will
1602 _("cannot move %s to %s"),
1603 quote_n (0, src_name), quote_n (1, dst_name));
1604 forget_created (src_sb.st_ino, src_sb.st_dev);
1608 /* The rename attempt has failed. Remove any existing destination
1609 file so that a cross-device `mv' acts as if it were really using
1610 the rename syscall. */
1611 if (unlink (dst_name) != 0 && errno != ENOENT)
1614 _("inter-device move failed: %s to %s; unable to remove target"),
1615 quote_n (0, src_name), quote_n (1, dst_name));
1616 forget_created (src_sb.st_ino, src_sb.st_dev);
1623 /* If the ownership might change, or if it is a directory (whose
1624 special mode bits may change after the directory is created),
1625 omit some permissions at first, so unauthorized users cannot nip
1626 in before the file is ready. */
1627 dst_mode_bits = (x->set_mode ? x->mode : src_mode) & CHMOD_MODE_BITS;
1628 omitted_permissions =
1630 & (x->preserve_ownership ? S_IRWXG | S_IRWXO
1631 : S_ISDIR (src_mode) ? S_IWGRP | S_IWOTH
1636 if (x->preserve_security_context)
1638 security_context_t con;
1640 if (0 <= lgetfilecon (src_name, &con))
1642 if (setfscreatecon (con) < 0)
1645 _("failed to set default file creation context to %s"),
1647 if (x->require_preserve_context)
1657 if (errno != ENOTSUP && errno != ENODATA)
1660 _("failed to get security context of %s"),
1662 if (x->require_preserve_context)
1668 /* In certain modes (cp's --symbolic-link), and for certain file types
1669 (symlinks and hard links) it doesn't make sense to preserve metadata,
1670 or it's possible to preserve only some of it.
1671 In such cases, set this variable to zero. */
1672 preserve_metadata = true;
1674 if (S_ISDIR (src_mode))
1676 struct dir_list *dir;
1678 /* If this directory has been copied before during the
1679 recursion, there is a symbolic link to an ancestor
1680 directory of the symbolic link. It is impossible to
1681 continue to copy this, unless we've got an infinite disk. */
1683 if (is_ancestor (&src_sb, ancestors))
1685 error (0, 0, _("cannot copy cyclic symbolic link %s"),
1690 /* Insert the current directory in the list of parents. */
1692 dir = alloca (sizeof *dir);
1693 dir->parent = ancestors;
1694 dir->ino = src_sb.st_ino;
1695 dir->dev = src_sb.st_dev;
1697 if (new_dst || !S_ISDIR (dst_sb.st_mode))
1699 /* POSIX says mkdir's behavior is implementation-defined when
1700 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
1701 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
1702 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
1703 if (mkdir (dst_name, dst_mode_bits & ~omitted_permissions) != 0)
1705 error (0, errno, _("cannot create directory %s"),
1710 /* We need search and write permissions to the new directory
1711 for writing the directory's contents. Check if these
1712 permissions are there. */
1714 if (lstat (dst_name, &dst_sb) != 0)
1716 error (0, errno, _("cannot stat %s"), quote (dst_name));
1719 else if ((dst_sb.st_mode & S_IRWXU) != S_IRWXU)
1721 /* Make the new directory searchable and writable. */
1723 dst_mode = dst_sb.st_mode;
1724 restore_dst_mode = true;
1726 if (lchmod (dst_name, dst_mode | S_IRWXU) != 0)
1728 error (0, errno, _("setting permissions for %s"),
1734 /* Insert the created directory's inode and device
1735 numbers into the search structure, so that we can
1736 avoid copying it again. */
1738 remember_copied (dst_name, dst_sb.st_ino, dst_sb.st_dev);
1741 emit_verbose (src_name, dst_name, NULL);
1744 /* Decide whether to copy the contents of the directory. */
1745 if (x->one_file_system && device != 0 && device != src_sb.st_dev)
1747 /* Here, we are crossing a file system boundary and cp's -x option
1748 is in effect: so don't copy the contents of this directory. */
1752 /* Copy the contents of the directory. Don't just return if
1753 this fails -- otherwise, the failure to read a single file
1754 in a source directory would cause the containing destination
1755 directory not to have owner/perms set properly. */
1756 delayed_ok = copy_dir (src_name, dst_name, new_dst, &src_sb, dir, x,
1760 else if (x->symbolic_link)
1762 preserve_metadata = false;
1764 if (*src_name != '/')
1766 /* Check that DST_NAME denotes a file in the current directory. */
1768 struct stat dst_parent_sb;
1770 bool in_current_dir;
1772 dst_parent = dir_name (dst_name);
1774 in_current_dir = (STREQ (".", dst_parent)
1775 /* If either stat call fails, it's ok not to report
1776 the failure and say dst_name is in the current
1777 directory. Other things will fail later. */
1778 || stat (".", &dot_sb) != 0
1779 || stat (dst_parent, &dst_parent_sb) != 0
1780 || SAME_INODE (dot_sb, dst_parent_sb));
1783 if (! in_current_dir)
1786 _("%s: can make relative symbolic links only in current directory"),
1791 if (symlink (src_name, dst_name) != 0)
1793 error (0, errno, _("cannot create symbolic link %s to %s"),
1794 quote_n (0, dst_name), quote_n (1, src_name));
1799 else if (x->hard_link
1800 #ifdef LINK_FOLLOWS_SYMLINKS
1801 /* A POSIX-conforming link syscall dereferences a symlink, yet cp,
1802 invoked with `--link --no-dereference', should not. Thus, with
1803 a POSIX-conforming link system call, we can't use link() here,
1804 since that would create a hard link to the referent (effectively
1805 dereferencing the symlink), rather than to the symlink itself.
1806 We can approximate the desired behavior by skipping this hard-link
1807 creating block and instead copying the symlink, via the `S_ISLNK'-
1809 When link operates on the symlinks themselves, we use this block
1810 and just call link(). */
1811 && !(S_ISLNK (src_mode) && x->dereference == DEREF_NEVER)
1815 preserve_metadata = false;
1816 if (link (src_name, dst_name))
1818 error (0, errno, _("cannot create link %s"), quote (dst_name));
1822 else if (S_ISREG (src_mode)
1823 || (x->copy_as_regular && !S_ISLNK (src_mode)))
1825 copied_as_regular = true;
1826 /* POSIX says the permission bits of the source file must be
1827 used as the 3rd argument in the open call. Historical
1828 practice passed all the source mode bits to 'open', but the extra
1829 bits were ignored, so it should be the same either way. */
1830 if (! copy_reg (src_name, dst_name, x, src_mode & S_IRWXUGO,
1831 omitted_permissions, &new_dst, &src_sb))
1834 else if (S_ISFIFO (src_mode))
1836 /* Use mknod, rather than mkfifo, because the former preserves
1837 the special mode bits of a fifo on Solaris 10, while mkfifo
1838 does not. But fall back on mkfifo, because on some BSD systems,
1839 mknod always fails when asked to create a FIFO. */
1840 if (mknod (dst_name, src_mode & ~omitted_permissions, 0) != 0)
1841 if (mkfifo (dst_name, src_mode & ~S_IFIFO & ~omitted_permissions) != 0)
1843 error (0, errno, _("cannot create fifo %s"), quote (dst_name));
1847 else if (S_ISBLK (src_mode) || S_ISCHR (src_mode) || S_ISSOCK (src_mode))
1849 if (mknod (dst_name, src_mode & ~omitted_permissions, src_sb.st_rdev)
1852 error (0, errno, _("cannot create special file %s"),
1857 else if (S_ISLNK (src_mode))
1859 char *src_link_val = areadlink_with_size (src_name, src_sb.st_size);
1860 if (src_link_val == NULL)
1862 error (0, errno, _("cannot read symbolic link %s"), quote (src_name));
1866 if (symlink (src_link_val, dst_name) == 0)
1867 free (src_link_val);
1870 int saved_errno = errno;
1871 bool same_link = false;
1872 if (x->update && !new_dst && S_ISLNK (dst_sb.st_mode)
1873 && dst_sb.st_size == strlen (src_link_val))
1875 /* See if the destination is already the desired symlink.
1876 FIXME: This behavior isn't documented, and seems wrong
1877 in some cases, e.g., if the destination symlink has the
1878 wrong ownership, permissions, or time stamps. */
1879 char *dest_link_val =
1880 areadlink_with_size (dst_name, dst_sb.st_size);
1881 if (dest_link_val && STREQ (dest_link_val, src_link_val))
1883 free (dest_link_val);
1885 free (src_link_val);
1889 error (0, saved_errno, _("cannot create symbolic link %s"),
1895 if (x->preserve_security_context)
1896 restore_default_fscreatecon_or_die ();
1898 /* There's no need to preserve timestamps or permissions. */
1899 preserve_metadata = false;
1901 if (x->preserve_ownership)
1903 /* Preserve the owner and group of the just-`copied'
1904 symbolic link, if possible. */
1906 && lchown (dst_name, src_sb.st_uid, src_sb.st_gid) != 0
1907 && ! chown_failure_ok (x))
1909 error (0, errno, _("failed to preserve ownership for %s"),
1915 /* Can't preserve ownership of symlinks.
1916 FIXME: maybe give a warning or even error for symlinks
1917 in directories with the sticky bit set -- there, not
1918 preserving owner/group is a potential security problem. */
1924 error (0, 0, _("%s has unknown file type"), quote (src_name));
1928 if (command_line_arg && x->dest_info)
1930 /* Now that the destination file is very likely to exist,
1931 add its info to the set. */
1933 if (lstat (dst_name, &sb) == 0)
1934 record_file (x->dest_info, dst_name, &sb);
1937 if ( ! preserve_metadata)
1940 if (copied_as_regular)
1943 /* POSIX says that `cp -p' must restore the following:
1945 - setuid, setgid bits
1947 If it fails to restore any of those, we may give a warning but
1948 the destination must not be removed.
1949 FIXME: implement the above. */
1951 /* Adjust the times (and if possible, ownership) for the copy.
1952 chown turns off set[ug]id bits for non-root,
1953 so do the chmod last. */
1955 if (x->preserve_timestamps)
1957 struct timespec timespec[2];
1958 timespec[0] = get_stat_atime (&src_sb);
1959 timespec[1] = get_stat_mtime (&src_sb);
1961 if (utimens (dst_name, timespec) != 0)
1963 error (0, errno, _("preserving times for %s"), quote (dst_name));
1964 if (x->require_preserve)
1969 /* Avoid calling chown if we know it's not necessary. */
1970 if (x->preserve_ownership
1971 && (new_dst || !SAME_OWNER_AND_GROUP (src_sb, dst_sb)))
1973 switch (set_owner (x, dst_name, -1, &src_sb, new_dst, &dst_sb))
1979 src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX);
1984 set_author (dst_name, -1, &src_sb);
1986 if (x->preserve_mode || x->move_mode)
1988 if (copy_acl (src_name, -1, dst_name, -1, src_mode) != 0
1989 && x->require_preserve)
1992 else if (x->set_mode)
1994 if (set_acl (dst_name, -1, x->mode) != 0)
1999 if (omitted_permissions)
2001 omitted_permissions &= ~ cached_umask ();
2003 if (omitted_permissions && !restore_dst_mode)
2005 /* Permissions were deliberately omitted when the file
2006 was created due to security concerns. See whether
2007 they need to be re-added now. It'd be faster to omit
2008 the lstat, but deducing the current destination mode
2009 is tricky in the presence of implementation-defined
2010 rules for special mode bits. */
2011 if (new_dst && lstat (dst_name, &dst_sb) != 0)
2013 error (0, errno, _("cannot stat %s"), quote (dst_name));
2016 dst_mode = dst_sb.st_mode;
2017 if (omitted_permissions & ~dst_mode)
2018 restore_dst_mode = true;
2022 if (restore_dst_mode)
2024 if (lchmod (dst_name, dst_mode | omitted_permissions) != 0)
2026 error (0, errno, _("preserving permissions for %s"),
2028 if (x->require_preserve)
2038 if (x->preserve_security_context)
2039 restore_default_fscreatecon_or_die ();
2041 /* We have failed to create the destination file.
2042 If we've just added a dev/ino entry via the remember_copied
2043 call above (i.e., unless we've just failed to create a hard link),
2044 remove the entry associating the source dev/ino with the
2045 destination file name, so we don't try to `preserve' a link
2046 to a file we didn't create. */
2047 if (earlier_file == NULL)
2048 forget_created (src_sb.st_ino, src_sb.st_dev);
2052 if (rename (dst_backup, dst_name) != 0)
2053 error (0, errno, _("cannot un-backup %s"), quote (dst_name));
2057 printf (_("%s -> %s (unbackup)\n"),
2058 quote_n (0, dst_backup), quote_n (1, dst_name));
2065 valid_options (const struct cp_options *co)
2067 assert (co != NULL);
2068 assert (VALID_BACKUP_TYPE (co->backup_type));
2069 assert (VALID_SPARSE_MODE (co->sparse_mode));
2070 assert (!(co->hard_link && co->symbolic_link));
2074 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
2075 any type. NONEXISTENT_DST should be true if the file DST_NAME
2076 is known not to exist (e.g., because its parent directory was just
2077 created); NONEXISTENT_DST should be false if DST_NAME might already
2078 exist. OPTIONS is ... FIXME-describe
2079 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
2080 same as) DST_NAME; otherwise, set clear it.
2081 Return true if successful. */
2084 copy (char const *src_name, char const *dst_name,
2085 bool nonexistent_dst, const struct cp_options *options,
2086 bool *copy_into_self, bool *rename_succeeded)
2088 assert (valid_options (options));
2090 /* Record the file names: they're used in case of error, when copying
2091 a directory into itself. I don't like to make these tools do *any*
2092 extra work in the common case when that work is solely to handle
2093 exceptional cases, but in this case, I don't see a way to derive the
2094 top level source and destination directory names where they're used.
2095 An alternative is to use COPY_INTO_SELF and print the diagnostic
2096 from every caller -- but I don't want to do that. */
2097 top_level_src_name = src_name;
2098 top_level_dst_name = dst_name;
2100 return copy_internal (src_name, dst_name, nonexistent_dst, 0, NULL,
2101 options, true, copy_into_self, rename_succeeded);
2104 /* Set *X to the default options for a value of type struct cp_options. */
2107 cp_options_default (struct cp_options *x)
2109 memset (x, 0, sizeof *x);
2110 #ifdef PRIV_FILE_CHOWN
2112 priv_set_t *pset = priv_allocset ();
2115 if (getppriv (PRIV_EFFECTIVE, pset) == 0)
2117 x->chown_privileges = priv_ismember (pset, PRIV_FILE_CHOWN);
2118 x->owner_privileges = priv_ismember (pset, PRIV_FILE_OWNER);
2120 priv_freeset (pset);
2123 x->chown_privileges = x->owner_privileges = (geteuid () == 0);
2127 /* Return true if it's OK for chown to fail, where errno is
2128 the error number that chown failed with and X is the copying
2132 chown_failure_ok (struct cp_options const *x)
2134 /* If non-root uses -p, it's ok if we can't preserve ownership.
2135 But root probably wants to know, e.g. if NFS disallows it,
2136 or if the target system doesn't support file ownership. */
2138 return ((errno == EPERM || errno == EINVAL) && !x->chown_privileges);
2141 /* Similarly, return true if it's OK for chmod and similar operations
2142 to fail, where errno is the error number that chmod failed with and
2143 X is the copying option set. */
2146 owner_failure_ok (struct cp_options const *x)
2148 return ((errno == EPERM || errno == EINVAL) && !x->owner_privileges);
2151 /* Return the user's umask, caching the result. */
2156 static mode_t mask = (mode_t) -1;
2157 if (mask == (mode_t) -1)