1 /* copy.c -- core functions for copying files and directories
2 Copyright (C) 89, 90, 91, 1995-2007 Free Software Foundation.
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, or (at your option)
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, write to the Free Software Foundation,
16 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
18 /* Extracted from cp.c and librarified by Jim Meyering. */
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 "euidaccess.h"
44 #include "filenamecat.h"
45 #include "full-write.h"
46 #include "getpagesize.h"
53 #include "stat-time.h"
56 #include "write-any-file.h"
57 #include "mreadlink.h"
61 # define HAVE_FCHOWN false
62 # define fchown(fd, uid, gid) (-1)
66 # define HAVE_LCHOWN false
67 # define lchown(name, uid, gid) chown (name, uid, gid)
70 #define SAME_OWNER(A, B) ((A).st_uid == (B).st_uid)
71 #define SAME_GROUP(A, B) ((A).st_gid == (B).st_gid)
72 #define SAME_OWNER_AND_GROUP(A, B) (SAME_OWNER (A, B) && SAME_GROUP (A, B))
76 struct dir_list *parent;
81 /* Describe a just-created or just-renamed destination file. */
89 /* Initial size of the above hash table. */
90 #define DEST_INFO_INITIAL_CAPACITY 61
92 static bool copy_internal (char const *src_name, char const *dst_name,
93 bool new_dst, dev_t device,
94 struct dir_list *ancestors,
95 const struct cp_options *x,
96 bool command_line_arg,
98 bool *rename_succeeded);
100 /* Pointers to the file names: they're used in the diagnostic that is issued
101 when we detect the user is trying to copy a directory into itself. */
102 static char const *top_level_src_name;
103 static char const *top_level_dst_name;
105 /* The invocation name of this program. */
106 extern char *program_name;
108 /* FIXME: describe */
109 /* FIXME: rewrite this to use a hash table so we avoid the quadratic
110 performance hit that's probably noticeable only on trees deeper
111 than a few hundred levels. See use of active_dir_map in remove.c */
114 is_ancestor (const struct stat *sb, const struct dir_list *ancestors)
116 while (ancestors != 0)
118 if (ancestors->ino == sb->st_ino && ancestors->dev == sb->st_dev)
120 ancestors = ancestors->parent;
125 /* Read the contents of the directory SRC_NAME_IN, and recursively
126 copy the contents to DST_NAME_IN. NEW_DST is true if
127 DST_NAME_IN is a directory that was created previously in the
128 recursion. SRC_SB and ANCESTORS describe SRC_NAME_IN.
129 Set *COPY_INTO_SELF if SRC_NAME_IN is a parent of
130 (or the same as) DST_NAME_IN; otherwise, clear it.
131 Return true if successful. */
134 copy_dir (char const *src_name_in, char const *dst_name_in, bool new_dst,
135 const struct stat *src_sb, struct dir_list *ancestors,
136 const struct cp_options *x, bool *copy_into_self)
140 struct cp_options non_command_line_options = *x;
143 name_space = savedir (src_name_in);
144 if (name_space == NULL)
146 /* This diagnostic is a bit vague because savedir can fail in
147 several different ways. */
148 error (0, errno, _("cannot access %s"), quote (src_name_in));
152 /* For cp's -H option, dereference command line arguments, but do not
153 dereference symlinks that are found via recursive traversal. */
154 if (x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
155 non_command_line_options.dereference = DEREF_NEVER;
158 while (*namep != '\0')
160 bool local_copy_into_self;
161 char *src_name = file_name_concat (src_name_in, namep, NULL);
162 char *dst_name = file_name_concat (dst_name_in, namep, NULL);
164 ok &= copy_internal (src_name, dst_name, new_dst, src_sb->st_dev,
165 ancestors, &non_command_line_options, false,
166 &local_copy_into_self, NULL);
167 *copy_into_self |= local_copy_into_self;
172 namep += strlen (namep) + 1;
178 /* Set the owner and owning group of DEST_DESC to the st_uid and
179 st_gid fields of SRC_SB. If DEST_DESC is undefined (-1), set
180 the owner and owning group of DST_NAME instead; for
181 safety prefer lchown if the system supports it since no
182 symbolic links should be involved. DEST_DESC must
183 refer to the same file as DEST_NAME if defined.
184 Return 1 if the syscall succeeds, 0 if it fails but it's OK
185 not to preserve ownership, -1 otherwise. */
188 set_owner (const struct cp_options *x, char const *dst_name, int dest_desc,
189 uid_t uid, gid_t gid)
191 if (HAVE_FCHOWN && dest_desc != -1)
193 if (fchown (dest_desc, uid, gid) == 0)
198 if (lchown (dst_name, uid, gid) == 0)
202 if (! chown_failure_ok (x))
204 error (0, errno, _("failed to preserve ownership for %s"),
206 if (x->require_preserve)
213 /* Set the st_author field of DEST_DESC to the st_author field of
214 SRC_SB. If DEST_DESC is undefined (-1), set the st_author field
215 of DST_NAME instead. DEST_DESC must refer to the same file as
216 DEST_NAME if defined. */
219 set_author (const char *dst_name, int dest_desc, const struct stat *src_sb)
221 #if HAVE_STRUCT_STAT_ST_AUTHOR
222 /* FIXME: Modify the following code so that it does not
223 follow symbolic links. */
225 /* Preserve the st_author field. */
226 file_t file = (dest_desc < 0
227 ? file_name_lookup (dst_name, 0, 0)
228 : getdport (dest_desc));
229 if (file == MACH_PORT_NULL)
230 error (0, errno, _("failed to lookup file %s"), quote (dst_name));
233 error_t err = file_chauthor (file, src_sb->st_author);
235 error (0, err, _("failed to preserve authorship for %s"),
237 mach_port_deallocate (mach_task_self (), file);
242 /* Change the file mode bits of the file identified by DESC or NAME to MODE.
243 Use DESC if DESC is valid and fchmod is available, NAME otherwise. */
246 fchmod_or_lchmod (int desc, char const *name, mode_t mode)
250 return fchmod (desc, mode);
252 return lchmod (name, mode);
255 /* Copy a regular file from SRC_NAME to DST_NAME.
256 If the source file contains holes, copies holes and blocks of zeros
257 in the source file as holes in the destination file.
258 (Holes are read as zeroes by the `read' system call.)
259 When creating the destination, use DST_MODE & ~OMITTED_PERMISSIONS
260 as the third argument in the call to open, adding
261 OMITTED_PERMISSIONS after copying as needed.
262 X provides many option settings.
263 Return true if successful.
264 *NEW_DST is as in copy_internal.
265 SRC_SB is the result of calling XSTAT (aka stat) on SRC_NAME. */
268 copy_reg (char const *src_name, char const *dst_name,
269 const struct cp_options *x,
270 mode_t dst_mode, mode_t omitted_permissions, bool *new_dst,
271 struct stat const *src_sb)
274 char *buf_alloc = NULL;
275 char *name_alloc = NULL;
276 char const *followed_dest_name = dst_name;
280 mode_t src_mode = src_sb->st_mode;
282 struct stat src_open_sb;
283 bool return_val = true;
285 source_desc = open (src_name,
287 | (x->dereference == DEREF_NEVER ? O_NOFOLLOW : 0)));
290 error (0, errno, _("cannot open %s for reading"), quote (src_name));
294 if (fstat (source_desc, &src_open_sb) != 0)
296 error (0, errno, _("cannot fstat %s"), quote (src_name));
301 /* Compare the source dev/ino from the open file to the incoming,
302 saved ones obtained via a previous call to stat. */
303 if (! SAME_INODE (*src_sb, src_open_sb))
306 _("skipping file %s, as it was replaced while being copied"),
312 /* The semantics of the following open calls are mandated
313 by the specs for both cp and mv. */
316 dest_desc = open (dst_name, O_WRONLY | O_TRUNC | O_BINARY);
319 /* When using cp --preserve=context to copy to an existing destination,
320 use the default context rather than that of the source. Why?
321 1) the src context may prohibit writing, and
322 2) because it's more consistent to use the same context
323 that is used when the destination file doesn't already exist. */
324 if (x->preserve_security_context && 0 <= dest_desc)
326 security_context_t con = NULL;
327 if (getfscreatecon (&con) < 0)
329 error (0, errno, _("failed to get file system create context"));
330 if (x->require_preserve_context)
339 if (fsetfilecon (dest_desc, con) < 0)
342 _("failed to set the security context of %s to %s"),
343 quote_n (0, dst_name), quote_n (1, con));
344 if (x->require_preserve_context)
355 if (dest_desc < 0 && x->unlink_dest_after_failed_open)
357 if (unlink (dst_name) != 0)
359 error (0, errno, _("cannot remove %s"), quote (dst_name));
364 printf (_("removed %s\n"), quote (dst_name));
366 /* Tell caller that the destination file was unlinked. */
373 int open_flags = O_WRONLY | O_CREAT | O_EXCL | O_BINARY;
374 dest_desc = open (dst_name, open_flags,
375 dst_mode & ~omitted_permissions);
378 /* When trying to copy through a dangling destination symlink,
379 the above open fails with EEXIST. If that happens, and
380 lstat'ing the DST_NAME shows that it is a symlink, repeat
381 the open call, but this time with the name of the final,
382 missing directory entry. */
383 if (dest_desc < 0 && dest_errno == EEXIST)
385 struct stat dangling_link_sb;
386 if (lstat (dst_name, &dangling_link_sb) == 0
387 && S_ISLNK (dangling_link_sb.st_mode))
389 /* FIXME: This is way overkill, since all that's needed
390 is to follow the symlink that is the last file name
393 canonicalize_filename_mode (dst_name, CAN_MISSING);
396 followed_dest_name = name_alloc;
397 dest_desc = open (followed_dest_name, open_flags,
398 dst_mode & ~omitted_permissions);
405 omitted_permissions = 0;
409 error (0, dest_errno, _("cannot create regular file %s"),
415 if (fstat (dest_desc, &sb) != 0)
417 error (0, errno, _("cannot fstat %s"), quote (dst_name));
419 goto close_src_and_dst_desc;
422 if (! (S_ISREG (src_open_sb.st_mode) && src_open_sb.st_size == 0))
424 typedef uintptr_t word;
425 off_t n_read_total = 0;
427 /* Choose a suitable buffer size; it may be adjusted later. */
428 size_t buf_alignment = lcm (getpagesize (), sizeof (word));
429 size_t buf_alignment_slop = sizeof (word) + buf_alignment - 1;
430 size_t buf_size = ST_BLKSIZE (sb);
432 /* Deal with sparse files. */
433 bool last_write_made_hole = false;
434 bool make_holes = false;
436 if (S_ISREG (sb.st_mode))
438 /* Even with --sparse=always, try to create holes only
439 if the destination is a regular file. */
440 if (x->sparse_mode == SPARSE_ALWAYS)
443 #if HAVE_STRUCT_STAT_ST_BLOCKS
444 /* Use a heuristic to determine whether SRC_NAME contains any sparse
445 blocks. If the file has fewer blocks than would normally be
446 needed for a file of its size, then at least one of the blocks in
447 the file is a hole. */
448 if (x->sparse_mode == SPARSE_AUTO && S_ISREG (src_open_sb.st_mode)
449 && ST_NBLOCKS (src_open_sb) < src_open_sb.st_size / ST_NBLOCKSIZE)
454 /* If not making a sparse file, try to use a more-efficient
458 /* These days there's no point ever messing with buffers smaller
459 than 8 KiB. It would be nice to configure SMALL_BUF_SIZE
460 dynamically for this host and pair of files, but there doesn't
461 seem to be a good way to get readahead info portably. */
462 enum { SMALL_BUF_SIZE = 8 * 1024 };
464 /* Compute the least common multiple of the input and output
465 buffer sizes, adjusting for outlandish values. */
466 size_t blcm_max = MIN (SIZE_MAX, SSIZE_MAX) - buf_alignment_slop;
467 size_t blcm = buffer_lcm (ST_BLKSIZE (src_open_sb), buf_size,
470 /* Do not use a block size that is too small. */
471 buf_size = MAX (SMALL_BUF_SIZE, blcm);
473 /* Do not bother with a buffer larger than the input file, plus one
474 byte to make sure the file has not grown while reading it. */
475 if (S_ISREG (src_open_sb.st_mode) && src_open_sb.st_size < buf_size)
476 buf_size = src_open_sb.st_size + 1;
478 /* However, stick with a block size that is a positive multiple of
479 blcm, overriding the above adjustments. Watch out for
481 buf_size += blcm - 1;
482 buf_size -= buf_size % blcm;
483 if (buf_size == 0 || blcm_max < buf_size)
487 /* Make a buffer with space for a sentinel at the end. */
488 buf_alloc = xmalloc (buf_size + buf_alignment_slop);
489 buf = ptr_align (buf_alloc, buf_alignment);
495 ssize_t n_read = read (source_desc, buf, buf_size);
502 error (0, errno, _("reading %s"), quote (src_name));
504 goto close_src_and_dst_desc;
509 n_read_total += n_read;
515 /* Sentinel to stop loop. */
518 /* Usually, buf[n_read] is not the byte just before a "word"
519 (aka uintptr_t) boundary. In that case, the word-oriented
520 test below (*wp++ == 0) would read some uninitialized bytes
521 after the sentinel. To avoid false-positive reports about
522 this condition (e.g., from a tool like valgrind), set the
523 remaining bytes -- to any value. */
524 memset (buf + n_read + 1, 0, sizeof (word) - 1);
527 /* Find first nonzero *word*, or the word with the sentinel. */
533 /* Find the first nonzero *byte*, or the sentinel. */
535 cp = (char *) (wp - 1);
539 if (cp <= buf + n_read)
540 /* Clear to indicate that a normal write is needed. */
544 /* We found the sentinel, so the whole input block was zero.
546 if (lseek (dest_desc, n_read, SEEK_CUR) < 0)
548 error (0, errno, _("cannot lseek %s"), quote (dst_name));
550 goto close_src_and_dst_desc;
552 last_write_made_hole = true;
559 if (full_write (dest_desc, buf, n) != n)
561 error (0, errno, _("writing %s"), quote (dst_name));
563 goto close_src_and_dst_desc;
565 last_write_made_hole = false;
567 /* A short read on a regular file means EOF. */
568 if (n_read != buf_size && S_ISREG (src_open_sb.st_mode))
573 /* If the file ends with a `hole', we need to do something to record
574 the length of the file. On modern systems, calling ftruncate does
575 the job. On systems without native ftruncate support, we have to
576 write a byte at the ending position. Otherwise the kernel would
577 truncate the file at the end of the last write operation. */
579 if (last_write_made_hole)
582 ? /* ftruncate sets the file size,
583 so there is no need for a write. */
584 ftruncate (dest_desc, n_read_total) < 0
585 : /* Seek backwards one character and write a null. */
586 (lseek (dest_desc, (off_t) -1, SEEK_CUR) < 0L
587 || full_write (dest_desc, "", 1) != 1))
589 error (0, errno, _("writing %s"), quote (dst_name));
591 goto close_src_and_dst_desc;
596 if (x->preserve_timestamps)
598 struct timespec timespec[2];
599 timespec[0] = get_stat_atime (src_sb);
600 timespec[1] = get_stat_mtime (src_sb);
602 if (gl_futimens (dest_desc, followed_dest_name, timespec) != 0)
604 error (0, errno, _("preserving times for %s"), quote (dst_name));
605 if (x->require_preserve)
608 goto close_src_and_dst_desc;
613 if (x->preserve_ownership && ! SAME_OWNER_AND_GROUP (*src_sb, sb))
615 switch (set_owner (x, followed_dest_name, dest_desc,
616 src_sb->st_uid, src_sb->st_gid))
620 goto close_src_and_dst_desc;
623 src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX);
628 set_author (followed_dest_name, dest_desc, src_sb);
630 if (x->preserve_mode || x->move_mode)
632 if (copy_acl (src_name, source_desc, followed_dest_name, dest_desc, src_mode) != 0
633 && x->require_preserve)
636 else if (x->set_mode)
638 if (set_acl (followed_dest_name, dest_desc, x->mode) != 0)
641 else if (omitted_permissions)
643 omitted_permissions &= ~ cached_umask ();
644 if (omitted_permissions
645 && fchmod_or_lchmod (dest_desc, followed_dest_name, dst_mode) != 0)
647 error (0, errno, _("preserving permissions for %s"),
649 if (x->require_preserve)
654 close_src_and_dst_desc:
655 if (close (dest_desc) < 0)
657 error (0, errno, _("closing %s"), quote (dst_name));
661 if (close (source_desc) < 0)
663 error (0, errno, _("closing %s"), quote (src_name));
672 /* Return true if it's ok that the source and destination
673 files are the `same' by some measure. The goal is to avoid
674 making the `copy' operation remove both copies of the file
675 in that case, while still allowing the user to e.g., move or
676 copy a regular file onto a symlink that points to it.
677 Try to minimize the cost of this function in the common case.
678 Set *RETURN_NOW if we've determined that the caller has no more
679 work to do and should return successfully, right away.
681 Set *UNLINK_SRC if we've determined that the caller wants to do
682 `rename (a, b)' where `a' and `b' are distinct hard links to the same
683 file. In that case, the caller should try to unlink `a' and then return
684 successfully. Ideally, we wouldn't have to do that, and we'd be
685 able to rely on rename to remove the source file. However, POSIX
686 mistakenly requires that such a rename call do *nothing* and return
690 same_file_ok (char const *src_name, struct stat const *src_sb,
691 char const *dst_name, struct stat const *dst_sb,
692 const struct cp_options *x, bool *return_now, bool *unlink_src)
694 const struct stat *src_sb_link;
695 const struct stat *dst_sb_link;
696 struct stat tmp_dst_sb;
697 struct stat tmp_src_sb;
700 bool same = SAME_INODE (*src_sb, *dst_sb);
705 /* FIXME: this should (at the very least) be moved into the following
706 if-block. More likely, it should be removed, because it inhibits
707 making backups. But removing it will result in a change in behavior
708 that will probably have to be documented -- and tests will have to
710 if (same && x->hard_link)
716 if (x->dereference == DEREF_NEVER)
720 /* If both the source and destination files are symlinks (and we'll
721 know this here IFF preserving symlinks), then it's ok -- as long
722 as they are distinct. */
723 if (S_ISLNK (src_sb->st_mode) && S_ISLNK (dst_sb->st_mode))
724 return ! same_name (src_name, dst_name);
726 src_sb_link = src_sb;
727 dst_sb_link = dst_sb;
734 if (lstat (dst_name, &tmp_dst_sb) != 0
735 || lstat (src_name, &tmp_src_sb) != 0)
738 src_sb_link = &tmp_src_sb;
739 dst_sb_link = &tmp_dst_sb;
741 same_link = SAME_INODE (*src_sb_link, *dst_sb_link);
743 /* If both are symlinks, then it's ok, but only if the destination
744 will be unlinked before being opened. This is like the test
745 above, but with the addition of the unlink_dest_before_opening
746 conjunct because otherwise, with two symlinks to the same target,
747 we'd end up truncating the source file. */
748 if (S_ISLNK (src_sb_link->st_mode) && S_ISLNK (dst_sb_link->st_mode)
749 && x->unlink_dest_before_opening)
753 /* The backup code ensures there's a copy, so it's usually ok to
754 remove any destination file. One exception is when both
755 source and destination are the same directory entry. In that
756 case, moving the destination file aside (in making the backup)
757 would also rename the source file and result in an error. */
758 if (x->backup_type != no_backups)
762 /* In copy mode when dereferencing symlinks, if the source is a
763 symlink and the dest is not, then backing up the destination
764 (moving it aside) would make it a dangling symlink, and the
765 subsequent attempt to open it in copy_reg would fail with
766 a misleading diagnostic. Avoid that by returning zero in
767 that case so the caller can make cp (or mv when it has to
768 resort to reading the source file) fail now. */
770 /* FIXME-note: even with the following kludge, we can still provoke
771 the offending diagnostic. It's just a little harder to do :-)
772 $ rm -f a b c; touch c; ln -s c b; ln -s b a; cp -b a b
773 cp: cannot open `a' for reading: No such file or directory
774 That's misleading, since a subsequent `ls' shows that `a'
776 One solution would be to open the source file *before* moving
777 aside the destination, but that'd involve a big rewrite. */
779 && x->dereference != DEREF_NEVER
780 && S_ISLNK (src_sb_link->st_mode)
781 && ! S_ISLNK (dst_sb_link->st_mode))
787 return ! same_name (src_name, dst_name);
791 /* FIXME: use or remove */
793 /* If we're making a backup, we'll detect the problem case in
794 copy_reg because SRC_NAME will no longer exist. Allowing
795 the test to be deferred lets cp do some useful things.
796 But when creating hardlinks and SRC_NAME is a symlink
797 but DST_NAME is not we must test anyway. */
799 || !S_ISLNK (src_sb_link->st_mode)
800 || S_ISLNK (dst_sb_link->st_mode))
803 if (x->dereference != DEREF_NEVER)
807 /* They may refer to the same file if we're in move mode and the
808 target is a symlink. That is ok, since we remove any existing
809 destination file before opening it -- via `rename' if they're on
810 the same file system, via `unlink (DST_NAME)' otherwise.
811 It's also ok if they're distinct hard links to the same file. */
812 if (x->move_mode || x->unlink_dest_before_opening)
814 if (S_ISLNK (dst_sb_link->st_mode))
818 && 1 < dst_sb_link->st_nlink
819 && ! same_name (src_name, dst_name))
830 /* If neither is a symlink, then it's ok as long as they aren't
831 hard links to the same file. */
832 if (!S_ISLNK (src_sb_link->st_mode) && !S_ISLNK (dst_sb_link->st_mode))
834 if (!SAME_INODE (*src_sb_link, *dst_sb_link))
837 /* If they are the same file, it's ok if we're making hard links. */
845 /* It's ok to remove a destination symlink. But that works only when we
846 unlink before opening the destination and when the source and destination
847 files are on the same partition. */
848 if (x->unlink_dest_before_opening
849 && S_ISLNK (dst_sb_link->st_mode))
850 return dst_sb_link->st_dev == src_sb_link->st_dev;
852 if (x->dereference == DEREF_NEVER)
854 if ( ! S_ISLNK (src_sb_link->st_mode))
855 tmp_src_sb = *src_sb_link;
856 else if (stat (src_name, &tmp_src_sb) != 0)
859 if ( ! S_ISLNK (dst_sb_link->st_mode))
860 tmp_dst_sb = *dst_sb_link;
861 else if (stat (dst_name, &tmp_dst_sb) != 0)
864 if ( ! SAME_INODE (tmp_src_sb, tmp_dst_sb))
867 /* FIXME: shouldn't this be testing whether we're making symlinks? */
878 /* Return true if FILE, with mode MODE, is writable in the sense of 'mv'.
879 Always consider a symbolic link to be writable. */
881 writable_destination (char const *file, mode_t mode)
883 return (S_ISLNK (mode)
884 || can_write_any_file ()
885 || euidaccess (file, W_OK) == 0);
889 overwrite_prompt (char const *dst_name, struct stat const *dst_sb)
891 if (! writable_destination (dst_name, dst_sb->st_mode))
893 char perms[12]; /* "-rwxrwxrwx " ls-style modes. */
894 strmode (dst_sb->st_mode, perms);
897 _("%s: try to overwrite %s, overriding mode %04lo (%s)? "),
898 program_name, quote (dst_name),
899 (unsigned long int) (dst_sb->st_mode & CHMOD_MODE_BITS),
904 fprintf (stderr, _("%s: overwrite %s? "),
905 program_name, quote (dst_name));
909 /* Hash an F_triple. */
911 triple_hash (void const *x, size_t table_size)
913 struct F_triple const *p = x;
915 /* Also take the name into account, so that when moving N hard links to the
916 same file (all listed on the command line) all into the same directory,
917 we don't experience any N^2 behavior. */
918 /* FIXME-maybe: is it worth the overhead of doing this
919 just to avoid N^2 in such an unusual case? N would have
920 to be very large to make the N^2 factor noticable, and
921 one would probably encounter a limit on the length of
922 a command line before it became a problem. */
923 size_t tmp = hash_pjw (p->name, table_size);
925 /* Ignoring the device number here should be fine. */
926 return (tmp | p->st_ino) % table_size;
929 /* Hash an F_triple. */
931 triple_hash_no_name (void const *x, size_t table_size)
933 struct F_triple const *p = x;
935 /* Ignoring the device number here should be fine. */
936 return p->st_ino % table_size;
939 /* Compare two F_triple structs. */
941 triple_compare (void const *x, void const *y)
943 struct F_triple const *a = x;
944 struct F_triple const *b = y;
945 return (SAME_INODE (*a, *b) && same_name (a->name, b->name)) ? true : false;
948 /* Free an F_triple. */
950 triple_free (void *x)
952 struct F_triple *a = x;
957 /* Initialize the hash table implementing a set of F_triple entries
958 corresponding to destination files. */
960 dest_info_init (struct cp_options *x)
963 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
970 /* Initialize the hash table implementing a set of F_triple entries
971 corresponding to source files listed on the command line. */
973 src_info_init (struct cp_options *x)
976 /* Note that we use triple_hash_no_name here.
977 Contrast with the use of triple_hash above.
978 That is necessary because a source file may be specified
979 in many different ways. We want to warn about this
985 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
992 /* Return true if there is an entry in hash table, HT,
993 for the file described by FILE and STATS. */
995 seen_file (Hash_table const *ht, char const *file,
996 struct stat const *stats)
998 struct F_triple new_ent;
1003 new_ent.name = (char *) file;
1004 new_ent.st_ino = stats->st_ino;
1005 new_ent.st_dev = stats->st_dev;
1007 return !!hash_lookup (ht, &new_ent);
1010 /* Record destination file, FILE, and dev/ino from *STATS,
1011 in the hash table, HT. If HT is NULL, return immediately.
1012 If STATS is NULL, call lstat on FILE to get the device
1013 and inode numbers. If that lstat fails, simply return.
1014 If memory allocation fails, exit immediately. */
1016 record_file (Hash_table *ht, char const *file,
1017 struct stat const *stats)
1019 struct F_triple *ent;
1024 ent = xmalloc (sizeof *ent);
1025 ent->name = xstrdup (file);
1028 ent->st_ino = stats->st_ino;
1029 ent->st_dev = stats->st_dev;
1034 if (lstat (file, &sb) != 0)
1036 ent->st_ino = sb.st_ino;
1037 ent->st_dev = sb.st_dev;
1041 struct F_triple *ent_from_table = hash_insert (ht, ent);
1042 if (ent_from_table == NULL)
1044 /* Insertion failed due to lack of memory. */
1048 if (ent_from_table != ent)
1050 /* There was alread a matching entry in the table, so ENT was
1051 not inserted. Free it. */
1057 /* When effecting a move (e.g., for mv(1)), and given the name DST_NAME
1058 of the destination and a corresponding stat buffer, DST_SB, return
1059 true if the logical `move' operation should _not_ proceed.
1060 Otherwise, return false.
1061 Depending on options specified in X, this code may issue an
1062 interactive prompt asking whether it's ok to overwrite DST_NAME. */
1064 abandon_move (const struct cp_options *x,
1065 char const *dst_name,
1066 struct stat const *dst_sb)
1068 assert (x->move_mode);
1069 return (x->interactive == I_ALWAYS_NO
1070 || ((x->interactive == I_ASK_USER
1071 || (x->interactive == I_UNSPECIFIED
1073 && ! writable_destination (dst_name, dst_sb->st_mode)))
1074 && (overwrite_prompt (dst_name, dst_sb), 1)
1078 /* Print --verbose output on standard output, e.g. `new' -> `old'.
1079 If BACKUP_DST_NAME is non-NULL, then also indicate that it is
1080 the name of a backup file. */
1082 emit_verbose (char const *src, char const *dst, char const *backup_dst_name)
1084 printf ("%s -> %s", quote_n (0, src), quote_n (1, dst));
1085 if (backup_dst_name)
1086 printf (_(" (backup: %s)"), quote (backup_dst_name));
1090 /* A wrapper around "setfscreatecon (NULL)" that exits upon failure. */
1092 restore_default_fscreatecon_or_die (void)
1094 if (setfscreatecon (NULL) != 0)
1095 error (EXIT_FAILURE, errno,
1096 _("failed to restore the default file creation context"));
1099 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
1100 any type. NEW_DST should be true if the file DST_NAME cannot
1101 exist because its parent directory was just created; NEW_DST should
1102 be false if DST_NAME might already exist. DEVICE is the device
1103 number of the parent directory, or 0 if the parent of this file is
1104 not known. ANCESTORS points to a linked, null terminated list of
1105 devices and inodes of parent directories of SRC_NAME. COMMAND_LINE_ARG
1106 is true iff SRC_NAME was specified on the command line.
1107 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
1108 same as) DST_NAME; otherwise, clear it.
1109 Return true if successful. */
1111 copy_internal (char const *src_name, char const *dst_name,
1114 struct dir_list *ancestors,
1115 const struct cp_options *x,
1116 bool command_line_arg,
1117 bool *copy_into_self,
1118 bool *rename_succeeded)
1123 mode_t dst_mode IF_LINT (= 0);
1124 mode_t dst_mode_bits;
1125 mode_t omitted_permissions;
1126 bool restore_dst_mode = false;
1127 char *earlier_file = NULL;
1128 char *dst_backup = NULL;
1129 bool backup_succeeded = false;
1131 bool copied_as_regular = false;
1132 bool preserve_metadata;
1134 if (x->move_mode && rename_succeeded)
1135 *rename_succeeded = false;
1137 *copy_into_self = false;
1139 if (XSTAT (x, src_name, &src_sb) != 0)
1141 error (0, errno, _("cannot stat %s"), quote (src_name));
1145 src_mode = src_sb.st_mode;
1147 if (S_ISDIR (src_mode) && !x->recursive)
1149 error (0, 0, _("omitting directory %s"), quote (src_name));
1153 /* Detect the case in which the same source file appears more than
1154 once on the command line and no backup option has been selected.
1155 If so, simply warn and don't copy it the second time.
1156 This check is enabled only if x->src_info is non-NULL. */
1157 if (command_line_arg)
1159 if ( ! S_ISDIR (src_sb.st_mode)
1160 && x->backup_type == no_backups
1161 && seen_file (x->src_info, src_name, &src_sb))
1163 error (0, 0, _("warning: source file %s specified more than once"),
1168 record_file (x->src_info, src_name, &src_sb);
1173 /* Regular files can be created by writing through symbolic
1174 links, but other files cannot. So use stat on the
1175 destination when copying a regular file, and lstat otherwise.
1176 However, if we intend to unlink or remove the destination
1177 first, use lstat, since a copy won't actually be made to the
1178 destination in that case. */
1179 if ((((S_ISREG (src_mode)
1180 || (x->copy_as_regular
1181 && ! (S_ISDIR (src_mode) || S_ISLNK (src_mode))))
1182 && ! (x->move_mode || x->symbolic_link || x->hard_link
1183 || x->backup_type != no_backups
1184 || x->unlink_dest_before_opening))
1185 ? stat (dst_name, &dst_sb)
1186 : lstat (dst_name, &dst_sb))
1189 if (errno != ENOENT)
1191 error (0, errno, _("cannot stat %s"), quote (dst_name));
1200 { /* Here, we know that dst_name exists, at least to the point
1201 that it is stat'able or lstat'table. */
1205 if (! same_file_ok (src_name, &src_sb, dst_name, &dst_sb,
1206 x, &return_now, &unlink_src))
1208 error (0, 0, _("%s and %s are the same file"),
1209 quote_n (0, src_name), quote_n (1, dst_name));
1213 if (!S_ISDIR (src_mode) && x->update)
1215 /* When preserving time stamps (but not moving within a file
1216 system), don't worry if the destination time stamp is
1217 less than the source merely because of time stamp
1219 int options = ((x->preserve_timestamps
1221 && dst_sb.st_dev == src_sb.st_dev))
1222 ? UTIMECMP_TRUNCATE_SOURCE
1225 if (0 <= utimecmp (dst_name, &dst_sb, &src_sb, options))
1227 /* We're using --update and the destination is not older
1228 than the source, so do not copy or move. Pretend the
1229 rename succeeded, so the caller (if it's mv) doesn't
1230 end up removing the source file. */
1231 if (rename_succeeded)
1232 *rename_succeeded = true;
1237 /* When there is an existing destination file, we may end up
1238 returning early, and hence not copying/moving the file.
1239 This may be due to an interactive `negative' reply to the
1240 prompt about the existing file. It may also be due to the
1241 use of the --reply=no option.
1243 cp and mv treat -i and -f differently. */
1246 if (abandon_move (x, dst_name, &dst_sb)
1247 || (unlink_src && unlink (src_name) == 0))
1249 /* Pretend the rename succeeded, so the caller (mv)
1250 doesn't end up removing the source file. */
1251 if (rename_succeeded)
1252 *rename_succeeded = true;
1253 if (unlink_src && x->verbose)
1254 printf (_("removed %s\n"), quote (src_name));
1259 error (0, errno, _("cannot remove %s"), quote (src_name));
1265 if (! S_ISDIR (src_mode)
1266 && (x->interactive == I_ALWAYS_NO
1267 || (x->interactive == I_ASK_USER
1268 && (overwrite_prompt (dst_name, &dst_sb), 1)
1276 if (!S_ISDIR (dst_sb.st_mode))
1278 if (S_ISDIR (src_mode))
1280 if (x->move_mode && x->backup_type != no_backups)
1282 /* Moving a directory onto an existing
1283 non-directory is ok only with --backup. */
1288 _("cannot overwrite non-directory %s with directory %s"),
1289 quote_n (0, dst_name), quote_n (1, src_name));
1294 /* Don't let the user destroy their data, even if they try hard:
1295 This mv command must fail (likewise for cp):
1296 rm -rf a b c; mkdir a b c; touch a/f b/f; mv a/f b/f c
1297 Otherwise, the contents of b/f would be lost.
1298 In the case of `cp', b/f would be lost if the user simulated
1299 a move using cp and rm.
1300 Note that it works fine if you use --backup=numbered. */
1301 if (command_line_arg
1302 && x->backup_type != numbered_backups
1303 && seen_file (x->dest_info, dst_name, &dst_sb))
1306 _("will not overwrite just-created %s with %s"),
1307 quote_n (0, dst_name), quote_n (1, src_name));
1312 if (!S_ISDIR (src_mode))
1314 if (S_ISDIR (dst_sb.st_mode))
1316 if (x->move_mode && x->backup_type != no_backups)
1318 /* Moving a non-directory onto an existing
1319 directory is ok only with --backup. */
1324 _("cannot overwrite directory %s with non-directory"),
1333 /* Don't allow user to move a directory onto a non-directory. */
1334 if (S_ISDIR (src_sb.st_mode) && !S_ISDIR (dst_sb.st_mode)
1335 && x->backup_type == no_backups)
1338 _("cannot move directory onto non-directory: %s -> %s"),
1339 quote_n (0, src_name), quote_n (0, dst_name));
1344 if (x->backup_type != no_backups
1345 /* Don't try to back up a destination if the last
1346 component of src_name is "." or "..". */
1347 && ! dot_or_dotdot (last_component (src_name))
1348 /* Create a backup of each destination directory in move mode,
1349 but not in copy mode. FIXME: it might make sense to add an
1350 option to suppress backup creation also for move mode.
1351 That would let one use mv to merge new content into an
1352 existing hierarchy. */
1353 && (x->move_mode || ! S_ISDIR (dst_sb.st_mode)))
1355 char *tmp_backup = find_backup_file_name (dst_name,
1358 /* Detect (and fail) when creating the backup file would
1359 destroy the source file. Before, running the commands
1360 cd /tmp; rm -f a a~; : > a; echo A > a~; cp --b=simple a~ a
1361 would leave two zero-length files: a and a~. */
1362 /* FIXME: but simply change e.g., the final a~ to `./a~'
1363 and the source will still be destroyed. */
1364 if (STREQ (tmp_backup, src_name))
1368 ? _("backing up %s would destroy source; %s not moved")
1369 : _("backing up %s would destroy source; %s not copied"));
1371 quote_n (0, dst_name),
1372 quote_n (1, src_name));
1378 Using alloca for a file name that may be arbitrarily
1379 long is not recommended. In fact, even forming such a name
1380 should be discouraged. Eventually, this code will be rewritten
1381 to use fts, so using alloca here will be less of a problem. */
1382 ASSIGN_STRDUPA (dst_backup, tmp_backup);
1384 if (rename (dst_name, dst_backup) != 0)
1386 if (errno != ENOENT)
1388 error (0, errno, _("cannot backup %s"), quote (dst_name));
1398 backup_succeeded = true;
1402 else if (! S_ISDIR (dst_sb.st_mode)
1403 && (x->unlink_dest_before_opening
1404 || (x->preserve_links && 1 < dst_sb.st_nlink)
1406 && x->dereference == DEREF_NEVER
1407 && S_ISLNK (src_sb.st_mode))
1410 if (unlink (dst_name) != 0 && errno != ENOENT)
1412 error (0, errno, _("cannot remove %s"), quote (dst_name));
1417 printf (_("removed %s\n"), quote (dst_name));
1422 /* If the source is a directory, we don't always create the destination
1423 directory. So --verbose should not announce anything until we're
1424 sure we'll create a directory. */
1425 if (x->verbose && !S_ISDIR (src_mode))
1426 emit_verbose (src_name, dst_name, backup_succeeded ? dst_backup : NULL);
1428 /* Associate the destination file name with the source device and inode
1429 so that if we encounter a matching dev/ino pair in the source tree
1430 we can arrange to create a hard link between the corresponding names
1431 in the destination tree.
1433 Sometimes, when preserving links, we have to record dev/ino even
1434 though st_nlink == 1:
1435 - when in move_mode, since we may be moving a group of N hard-linked
1436 files (via two or more command line arguments) to a different
1437 partition; the links may be distributed among the command line
1438 arguments (possibly hierarchies) so that the link count of
1439 the final, once-linked source file is reduced to 1 when it is
1440 considered below. But in this case (for mv) we don't need to
1441 incur the expense of recording the dev/ino => name mapping; all we
1442 really need is a lookup, to see if the dev/ino pair has already
1444 - when using -H and processing a command line argument;
1445 that command line argument could be a symlink pointing to another
1446 command line argument. With `cp -H --preserve=link', we hard-link
1447 those two destination files.
1448 - likewise for -L except that it applies to all files, not just
1449 command line arguments.
1451 Also record directory dev/ino when using --recursive. We'll use that
1452 info to detect this problem: cp -R dir dir. FIXME-maybe: ideally,
1453 directory info would be recorded in a separate hash table, since
1454 such entries are useful only while a single command line hierarchy
1455 is being copied -- so that separate table could be cleared between
1456 command line args. Using the same hash table to preserve hard
1457 links means that it may not be cleared. */
1459 if (x->move_mode && src_sb.st_nlink == 1)
1461 earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev);
1463 else if ((x->preserve_links
1464 && (1 < src_sb.st_nlink
1465 || (command_line_arg
1466 && x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
1467 || x->dereference == DEREF_ALWAYS))
1468 || (x->recursive && S_ISDIR (src_mode)))
1470 earlier_file = remember_copied (dst_name, src_sb.st_ino, src_sb.st_dev);
1473 /* Did we copy this inode somewhere else (in this command line argument)
1474 and therefore this is a second hard link to the inode? */
1478 /* Avoid damaging the destination file system by refusing to preserve
1479 hard-linked directories (which are found at least in Netapp snapshot
1481 if (S_ISDIR (src_mode))
1483 /* If src_name and earlier_file refer to the same directory entry,
1484 then warn about copying a directory into itself. */
1485 if (same_name (src_name, earlier_file))
1487 error (0, 0, _("cannot copy a directory, %s, into itself, %s"),
1488 quote_n (0, top_level_src_name),
1489 quote_n (1, top_level_dst_name));
1490 *copy_into_self = true;
1493 else if (x->dereference == DEREF_ALWAYS)
1495 /* This happens when e.g., encountering a directory for the
1496 second or subsequent time via symlinks when cp is invoked
1497 with -R and -L. E.g.,
1498 rm -rf a b c d; mkdir a b c d; ln -s ../c a; ln -s ../c b;
1504 error (0, 0, _("will not create hard link %s to directory %s"),
1505 quote_n (0, dst_name), quote_n (1, earlier_file));
1511 bool link_failed = (link (earlier_file, dst_name) != 0);
1513 /* If the link failed because of an existing destination,
1514 remove that file and then call link again. */
1515 if (link_failed && errno == EEXIST)
1517 if (unlink (dst_name) != 0)
1519 error (0, errno, _("cannot remove %s"), quote (dst_name));
1523 printf (_("removed %s\n"), quote (dst_name));
1524 link_failed = (link (earlier_file, dst_name) != 0);
1529 error (0, errno, _("cannot create hard link %s to %s"),
1530 quote_n (0, dst_name), quote_n (1, earlier_file));
1540 if (rename (src_name, dst_name) == 0)
1542 if (x->verbose && S_ISDIR (src_mode))
1543 emit_verbose (src_name, dst_name,
1544 backup_succeeded ? dst_backup : NULL);
1546 if (rename_succeeded)
1547 *rename_succeeded = true;
1549 if (command_line_arg)
1551 /* Record destination dev/ino/name, so that if we are asked
1552 to overwrite that file again, we can detect it and fail. */
1553 /* It's fine to use the _source_ stat buffer (src_sb) to get the
1554 _destination_ dev/ino, since the rename above can't have
1555 changed those, and `mv' always uses lstat.
1556 We could limit it further by operating
1557 only on non-directories. */
1558 record_file (x->dest_info, dst_name, &src_sb);
1564 /* FIXME: someday, consider what to do when moving a directory into
1565 itself but when source and destination are on different devices. */
1567 /* This happens when attempting to rename a directory to a
1568 subdirectory of itself. */
1569 if (errno == EINVAL)
1571 /* FIXME: this is a little fragile in that it relies on rename(2)
1572 failing with a specific errno value. Expect problems on
1573 non-POSIX systems. */
1574 error (0, 0, _("cannot move %s to a subdirectory of itself, %s"),
1575 quote_n (0, top_level_src_name),
1576 quote_n (1, top_level_dst_name));
1578 /* Note that there is no need to call forget_created here,
1579 (compare with the other calls in this file) since the
1580 destination directory didn't exist before. */
1582 *copy_into_self = true;
1583 /* FIXME-cleanup: Don't return true here; adjust mv.c accordingly.
1584 The only caller that uses this code (mv.c) ends up setting its
1585 exit status to nonzero when copy_into_self is nonzero. */
1589 /* WARNING: there probably exist systems for which an inter-device
1590 rename fails with a value of errno not handled here.
1591 If/as those are reported, add them to the condition below.
1592 If this happens to you, please do the following and send the output
1593 to the bug-reporting address (e.g., in the output of cp --help):
1594 touch k; perl -e 'rename "k","/tmp/k" or print "$!(",$!+0,")\n"'
1595 where your current directory is on one partion and /tmp is the other.
1596 Also, please try to find the E* errno macro name corresponding to
1597 the diagnostic and parenthesized integer, and include that in your
1598 e-mail. One way to do that is to run a command like this
1599 find /usr/include/. -type f \
1600 | xargs grep 'define.*\<E[A-Z]*\>.*\<18\>' /dev/null
1601 where you'd replace `18' with the integer in parentheses that
1602 was output from the perl one-liner above.
1603 If necessary, of course, change `/tmp' to some other directory. */
1606 /* There are many ways this can happen due to a race condition.
1607 When something happens between the initial XSTAT and the
1608 subsequent rename, we can get many different types of errors.
1609 For example, if the destination is initially a non-directory
1610 or non-existent, but it is created as a directory, the rename
1611 fails. If two `mv' commands try to rename the same file at
1612 about the same time, one will succeed and the other will fail.
1613 If the permissions on the directory containing the source or
1614 destination file are made too restrictive, the rename will
1617 _("cannot move %s to %s"),
1618 quote_n (0, src_name), quote_n (1, dst_name));
1619 forget_created (src_sb.st_ino, src_sb.st_dev);
1623 /* The rename attempt has failed. Remove any existing destination
1624 file so that a cross-device `mv' acts as if it were really using
1625 the rename syscall. */
1626 if (unlink (dst_name) != 0 && errno != ENOENT)
1629 _("inter-device move failed: %s to %s; unable to remove target"),
1630 quote_n (0, src_name), quote_n (1, dst_name));
1631 forget_created (src_sb.st_ino, src_sb.st_dev);
1638 /* If the ownership might change, or if it is a directory (whose
1639 special mode bits may change after the directory is created),
1640 omit some permissions at first, so unauthorized users cannot nip
1641 in before the file is ready. */
1642 dst_mode_bits = (x->set_mode ? x->mode : src_mode) & CHMOD_MODE_BITS;
1643 omitted_permissions =
1645 & (x->preserve_ownership ? S_IRWXG | S_IRWXO
1646 : S_ISDIR (src_mode) ? S_IWGRP | S_IWOTH
1651 if (x->preserve_security_context)
1653 security_context_t con;
1655 if (0 <= lgetfilecon (src_name, &con))
1657 if (setfscreatecon (con) < 0)
1660 _("failed to set default file creation context to %s"),
1662 if (x->require_preserve_context)
1672 if (errno != ENOTSUP && errno != ENODATA)
1675 _("failed to get security context of %s"),
1677 if (x->require_preserve_context)
1683 /* In certain modes (cp's --symbolic-link), and for certain file types
1684 (symlinks and hard links) it doesn't make sense to preserve metadata,
1685 or it's possible to preserve only some of it.
1686 In such cases, set this variable to zero. */
1687 preserve_metadata = true;
1689 if (S_ISDIR (src_mode))
1691 struct dir_list *dir;
1693 /* If this directory has been copied before during the
1694 recursion, there is a symbolic link to an ancestor
1695 directory of the symbolic link. It is impossible to
1696 continue to copy this, unless we've got an infinite disk. */
1698 if (is_ancestor (&src_sb, ancestors))
1700 error (0, 0, _("cannot copy cyclic symbolic link %s"),
1705 /* Insert the current directory in the list of parents. */
1707 dir = alloca (sizeof *dir);
1708 dir->parent = ancestors;
1709 dir->ino = src_sb.st_ino;
1710 dir->dev = src_sb.st_dev;
1712 if (new_dst || !S_ISDIR (dst_sb.st_mode))
1714 /* POSIX says mkdir's behavior is implementation-defined when
1715 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
1716 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
1717 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
1718 if (mkdir (dst_name, dst_mode_bits & ~omitted_permissions) != 0)
1720 error (0, errno, _("cannot create directory %s"),
1725 /* We need search and write permissions to the new directory
1726 for writing the directory's contents. Check if these
1727 permissions are there. */
1729 if (lstat (dst_name, &dst_sb) != 0)
1731 error (0, errno, _("cannot stat %s"), quote (dst_name));
1734 else if ((dst_sb.st_mode & S_IRWXU) != S_IRWXU)
1736 /* Make the new directory searchable and writable. */
1738 dst_mode = dst_sb.st_mode;
1739 restore_dst_mode = true;
1741 if (lchmod (dst_name, dst_mode | S_IRWXU) != 0)
1743 error (0, errno, _("setting permissions for %s"),
1749 /* Insert the created directory's inode and device
1750 numbers into the search structure, so that we can
1751 avoid copying it again. */
1753 remember_copied (dst_name, dst_sb.st_ino, dst_sb.st_dev);
1756 emit_verbose (src_name, dst_name, NULL);
1759 /* Decide whether to copy the contents of the directory. */
1760 if (x->one_file_system && device != 0 && device != src_sb.st_dev)
1762 /* Here, we are crossing a file system boundary and cp's -x option
1763 is in effect: so don't copy the contents of this directory. */
1767 /* Copy the contents of the directory. Don't just return if
1768 this fails -- otherwise, the failure to read a single file
1769 in a source directory would cause the containing destination
1770 directory not to have owner/perms set properly. */
1771 delayed_ok = copy_dir (src_name, dst_name, new_dst, &src_sb, dir, x,
1775 else if (x->symbolic_link)
1777 preserve_metadata = false;
1779 if (*src_name != '/')
1781 /* Check that DST_NAME denotes a file in the current directory. */
1783 struct stat dst_parent_sb;
1785 bool in_current_dir;
1787 dst_parent = dir_name (dst_name);
1789 in_current_dir = (STREQ (".", dst_parent)
1790 /* If either stat call fails, it's ok not to report
1791 the failure and say dst_name is in the current
1792 directory. Other things will fail later. */
1793 || stat (".", &dot_sb) != 0
1794 || stat (dst_parent, &dst_parent_sb) != 0
1795 || SAME_INODE (dot_sb, dst_parent_sb));
1798 if (! in_current_dir)
1801 _("%s: can make relative symbolic links only in current directory"),
1806 if (symlink (src_name, dst_name) != 0)
1808 error (0, errno, _("cannot create symbolic link %s to %s"),
1809 quote_n (0, dst_name), quote_n (1, src_name));
1814 else if (x->hard_link
1815 #ifdef LINK_FOLLOWS_SYMLINKS
1816 /* A POSIX-conforming link syscall dereferences a symlink, yet cp,
1817 invoked with `--link --no-dereference', should not. Thus, with
1818 a POSIX-conforming link system call, we can't use link() here,
1819 since that would create a hard link to the referent (effectively
1820 dereferencing the symlink), rather than to the symlink itself.
1821 We can approximate the desired behavior by skipping this hard-link
1822 creating block and instead copying the symlink, via the `S_ISLNK'-
1824 When link operates on the symlinks themselves, we use this block
1825 and just call link(). */
1826 && !(S_ISLNK (src_mode) && x->dereference == DEREF_NEVER)
1830 preserve_metadata = false;
1831 if (link (src_name, dst_name))
1833 error (0, errno, _("cannot create link %s"), quote (dst_name));
1837 else if (S_ISREG (src_mode)
1838 || (x->copy_as_regular && !S_ISLNK (src_mode)))
1840 copied_as_regular = true;
1841 /* POSIX says the permission bits of the source file must be
1842 used as the 3rd argument in the open call. Historical
1843 practice passed all the source mode bits to 'open', but the extra
1844 bits were ignored, so it should be the same either way. */
1845 if (! copy_reg (src_name, dst_name, x, src_mode & S_IRWXUGO,
1846 omitted_permissions, &new_dst, &src_sb))
1849 else if (S_ISFIFO (src_mode))
1851 /* Use mknod, rather than mkfifo, because the former preserves
1852 the special mode bits of a fifo on Solaris 10, while mkfifo
1853 does not. But fall back on mkfifo, because on some BSD systems,
1854 mknod always fails when asked to create a FIFO. */
1855 if (mknod (dst_name, src_mode & ~omitted_permissions, 0) != 0)
1857 if (mkfifo (dst_name, src_mode & ~S_IFIFO & ~omitted_permissions) != 0)
1860 error (0, errno, _("cannot create fifo %s"), quote (dst_name));
1864 else if (S_ISBLK (src_mode) || S_ISCHR (src_mode) || S_ISSOCK (src_mode))
1866 if (mknod (dst_name, src_mode & ~omitted_permissions, src_sb.st_rdev)
1869 error (0, errno, _("cannot create special file %s"),
1874 else if (S_ISLNK (src_mode))
1876 char *src_link_val = mreadlink_with_size (src_name, src_sb.st_size);
1877 if (src_link_val == NULL)
1879 error (0, errno, _("cannot read symbolic link %s"), quote (src_name));
1883 if (symlink (src_link_val, dst_name) == 0)
1884 free (src_link_val);
1887 int saved_errno = errno;
1888 bool same_link = false;
1889 if (x->update && !new_dst && S_ISLNK (dst_sb.st_mode)
1890 && dst_sb.st_size == strlen (src_link_val))
1892 /* See if the destination is already the desired symlink.
1893 FIXME: This behavior isn't documented, and seems wrong
1894 in some cases, e.g., if the destination symlink has the
1895 wrong ownership, permissions, or time stamps. */
1896 char *dest_link_val =
1897 mreadlink_with_size (dst_name, dst_sb.st_size);
1898 if (dest_link_val && STREQ (dest_link_val, src_link_val))
1900 free (dest_link_val);
1902 free (src_link_val);
1906 error (0, saved_errno, _("cannot create symbolic link %s"),
1912 if (x->preserve_security_context)
1913 restore_default_fscreatecon_or_die ();
1915 /* There's no need to preserve timestamps or permissions. */
1916 preserve_metadata = false;
1918 if (x->preserve_ownership)
1920 /* Preserve the owner and group of the just-`copied'
1921 symbolic link, if possible. */
1923 && lchown (dst_name, src_sb.st_uid, src_sb.st_gid) != 0
1924 && ! chown_failure_ok (x))
1926 error (0, errno, _("failed to preserve ownership for %s"),
1932 /* Can't preserve ownership of symlinks.
1933 FIXME: maybe give a warning or even error for symlinks
1934 in directories with the sticky bit set -- there, not
1935 preserving owner/group is a potential security problem. */
1941 error (0, 0, _("%s has unknown file type"), quote (src_name));
1945 if (command_line_arg)
1946 record_file (x->dest_info, dst_name, NULL);
1948 if ( ! preserve_metadata)
1951 if (copied_as_regular)
1954 /* POSIX says that `cp -p' must restore the following:
1956 - setuid, setgid bits
1958 If it fails to restore any of those, we may give a warning but
1959 the destination must not be removed.
1960 FIXME: implement the above. */
1962 /* Adjust the times (and if possible, ownership) for the copy.
1963 chown turns off set[ug]id bits for non-root,
1964 so do the chmod last. */
1966 if (x->preserve_timestamps)
1968 struct timespec timespec[2];
1969 timespec[0] = get_stat_atime (&src_sb);
1970 timespec[1] = get_stat_mtime (&src_sb);
1972 if (utimens (dst_name, timespec) != 0)
1974 error (0, errno, _("preserving times for %s"), quote (dst_name));
1975 if (x->require_preserve)
1980 /* Avoid calling chown if we know it's not necessary. */
1981 if (x->preserve_ownership
1982 && (new_dst || !SAME_OWNER_AND_GROUP (src_sb, dst_sb)))
1984 switch (set_owner (x, dst_name, -1, src_sb.st_uid, src_sb.st_gid))
1990 src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX);
1995 set_author (dst_name, -1, &src_sb);
1997 if (x->preserve_mode || x->move_mode)
1999 if (copy_acl (src_name, -1, dst_name, -1, src_mode) != 0
2000 && x->require_preserve)
2003 else if (x->set_mode)
2005 if (set_acl (dst_name, -1, x->mode) != 0)
2010 if (omitted_permissions)
2012 omitted_permissions &= ~ cached_umask ();
2014 if (omitted_permissions && !restore_dst_mode)
2016 /* Permissions were deliberately omitted when the file
2017 was created due to security concerns. See whether
2018 they need to be re-added now. It'd be faster to omit
2019 the lstat, but deducing the current destination mode
2020 is tricky in the presence of implementation-defined
2021 rules for special mode bits. */
2022 if (new_dst && lstat (dst_name, &dst_sb) != 0)
2024 error (0, errno, _("cannot stat %s"), quote (dst_name));
2027 dst_mode = dst_sb.st_mode;
2028 if (omitted_permissions & ~dst_mode)
2029 restore_dst_mode = true;
2033 if (restore_dst_mode)
2035 if (lchmod (dst_name, dst_mode | omitted_permissions) != 0)
2037 error (0, errno, _("preserving permissions for %s"),
2039 if (x->require_preserve)
2049 if (x->preserve_security_context)
2050 restore_default_fscreatecon_or_die ();
2052 /* We have failed to create the destination file.
2053 If we've just added a dev/ino entry via the remember_copied
2054 call above (i.e., unless we've just failed to create a hard link),
2055 remove the entry associating the source dev/ino with the
2056 destination file name, so we don't try to `preserve' a link
2057 to a file we didn't create. */
2058 if (earlier_file == NULL)
2059 forget_created (src_sb.st_ino, src_sb.st_dev);
2063 if (rename (dst_backup, dst_name) != 0)
2064 error (0, errno, _("cannot un-backup %s"), quote (dst_name));
2068 printf (_("%s -> %s (unbackup)\n"),
2069 quote_n (0, dst_backup), quote_n (1, dst_name));
2076 valid_options (const struct cp_options *co)
2078 assert (co != NULL);
2079 assert (VALID_BACKUP_TYPE (co->backup_type));
2080 assert (VALID_SPARSE_MODE (co->sparse_mode));
2081 assert (!(co->hard_link && co->symbolic_link));
2085 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
2086 any type. NONEXISTENT_DST should be true if the file DST_NAME
2087 is known not to exist (e.g., because its parent directory was just
2088 created); NONEXISTENT_DST should be false if DST_NAME might already
2089 exist. OPTIONS is ... FIXME-describe
2090 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
2091 same as) DST_NAME; otherwise, set clear it.
2092 Return true if successful. */
2095 copy (char const *src_name, char const *dst_name,
2096 bool nonexistent_dst, const struct cp_options *options,
2097 bool *copy_into_self, bool *rename_succeeded)
2099 assert (valid_options (options));
2101 /* Record the file names: they're used in case of error, when copying
2102 a directory into itself. I don't like to make these tools do *any*
2103 extra work in the common case when that work is solely to handle
2104 exceptional cases, but in this case, I don't see a way to derive the
2105 top level source and destination directory names where they're used.
2106 An alternative is to use COPY_INTO_SELF and print the diagnostic
2107 from every caller -- but I don't want to do that. */
2108 top_level_src_name = src_name;
2109 top_level_dst_name = dst_name;
2111 return copy_internal (src_name, dst_name, nonexistent_dst, 0, NULL,
2112 options, true, copy_into_self, rename_succeeded);
2115 /* Return true if this process has appropriate privileges to chown a
2116 file whose owner is not the effective user ID. */
2119 chown_privileges (void)
2121 #ifdef PRIV_FILE_CHOWN
2123 priv_set_t *pset = priv_allocset ();
2126 result = (getppriv (PRIV_EFFECTIVE, pset) == 0
2127 && priv_ismember (pset, PRIV_FILE_CHOWN));
2128 priv_freeset (pset);
2131 return (geteuid () == 0);
2135 /* Return true if it's OK for chown to fail, where errno is
2136 the error number that chown failed with and X is the copying
2140 chown_failure_ok (struct cp_options const *x)
2142 /* If non-root uses -p, it's ok if we can't preserve ownership.
2143 But root probably wants to know, e.g. if NFS disallows it,
2144 or if the target system doesn't support file ownership. */
2146 return ((errno == EPERM || errno == EINVAL) && !x->chown_privileges);
2149 /* Return the user's umask, caching the result. */
2154 static mode_t mask = (mode_t) -1;
2155 if (mask == (mode_t) -1)