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 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"
45 #include "getpagesize.h"
47 #include "hash-triple.h"
52 #include "stat-time.h"
55 #include "write-any-file.h"
56 #include "areadlink.h"
60 # define HAVE_FCHOWN false
61 # define fchown(fd, uid, gid) (-1)
65 # define HAVE_LCHOWN false
66 # define lchown(name, uid, gid) chown (name, uid, gid)
73 #define SAME_OWNER(A, B) ((A).st_uid == (B).st_uid)
74 #define SAME_GROUP(A, B) ((A).st_gid == (B).st_gid)
75 #define SAME_OWNER_AND_GROUP(A, B) (SAME_OWNER (A, B) && SAME_GROUP (A, B))
79 struct dir_list *parent;
84 /* Initial size of the cp.dest_info hash table. */
85 #define DEST_INFO_INITIAL_CAPACITY 61
87 static bool copy_internal (char const *src_name, char const *dst_name,
88 bool new_dst, dev_t device,
89 struct dir_list *ancestors,
90 const struct cp_options *x,
91 bool command_line_arg,
93 bool *rename_succeeded);
94 static bool owner_failure_ok (struct cp_options const *x);
96 /* Pointers to the file names: they're used in the diagnostic that is issued
97 when we detect the user is trying to copy a directory into itself. */
98 static char const *top_level_src_name;
99 static char const *top_level_dst_name;
101 /* The invocation name of this program. */
102 extern char *program_name;
104 /* FIXME: describe */
105 /* FIXME: rewrite this to use a hash table so we avoid the quadratic
106 performance hit that's probably noticeable only on trees deeper
107 than a few hundred levels. See use of active_dir_map in remove.c */
110 is_ancestor (const struct stat *sb, const struct dir_list *ancestors)
112 while (ancestors != 0)
114 if (ancestors->ino == sb->st_ino && ancestors->dev == sb->st_dev)
116 ancestors = ancestors->parent;
121 /* Read the contents of the directory SRC_NAME_IN, and recursively
122 copy the contents to DST_NAME_IN. NEW_DST is true if
123 DST_NAME_IN is a directory that was created previously in the
124 recursion. SRC_SB and ANCESTORS describe SRC_NAME_IN.
125 Set *COPY_INTO_SELF if SRC_NAME_IN is a parent of
126 (or the same as) DST_NAME_IN; otherwise, clear it.
127 Return true if successful. */
130 copy_dir (char const *src_name_in, char const *dst_name_in, bool new_dst,
131 const struct stat *src_sb, struct dir_list *ancestors,
132 const struct cp_options *x, bool *copy_into_self)
136 struct cp_options non_command_line_options = *x;
139 name_space = savedir (src_name_in);
140 if (name_space == NULL)
142 /* This diagnostic is a bit vague because savedir can fail in
143 several different ways. */
144 error (0, errno, _("cannot access %s"), quote (src_name_in));
148 /* For cp's -H option, dereference command line arguments, but do not
149 dereference symlinks that are found via recursive traversal. */
150 if (x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
151 non_command_line_options.dereference = DEREF_NEVER;
154 while (*namep != '\0')
156 bool local_copy_into_self;
157 char *src_name = file_name_concat (src_name_in, namep, NULL);
158 char *dst_name = file_name_concat (dst_name_in, namep, NULL);
160 ok &= copy_internal (src_name, dst_name, new_dst, src_sb->st_dev,
161 ancestors, &non_command_line_options, false,
162 &local_copy_into_self, NULL);
163 *copy_into_self |= local_copy_into_self;
168 namep += strlen (namep) + 1;
174 /* Set the owner and owning group of DEST_DESC to the st_uid and
175 st_gid fields of SRC_SB. If DEST_DESC is undefined (-1), set
176 the owner and owning group of DST_NAME instead; for
177 safety prefer lchown if the system supports it since no
178 symbolic links should be involved. DEST_DESC must
179 refer to the same file as DEST_NAME if defined.
180 Upon failure to set both UID and GID, try to set only the GID.
181 NEW_DST is true if the file was newly created; otherwise,
182 DST_SB is the status of the destination.
183 Return 1 if the initial syscall succeeds, 0 if it fails but it's OK
184 not to preserve ownership, -1 otherwise. */
187 set_owner (const struct cp_options *x, char const *dst_name, int dest_desc,
188 struct stat const *src_sb, bool new_dst,
189 struct stat const *dst_sb)
191 uid_t uid = src_sb->st_uid;
192 gid_t gid = src_sb->st_gid;
194 /* Naively changing the ownership of an already-existing file before
195 changing its permissions would create a window of vulnerability if
196 the file's old permissions are too generous for the new owner and
197 group. Avoid the window by first changing to a restrictive
198 temporary mode if necessary. */
200 if (!new_dst & (x->preserve_mode | x->move_mode | x->set_mode))
202 mode_t old_mode = dst_sb->st_mode;
204 (x->preserve_mode | x->move_mode ? src_sb->st_mode : x->mode);
205 mode_t restrictive_temp_mode = old_mode & new_mode & S_IRWXU;
208 || (old_mode & CHMOD_MODE_BITS
209 & (~new_mode | S_ISUID | S_ISGID | S_ISVTX)))
210 && qset_acl (dst_name, dest_desc, restrictive_temp_mode) != 0)
212 if (! owner_failure_ok (x))
213 error (0, errno, _("clearing permissions for %s"), quote (dst_name));
214 return -x->require_preserve;
218 if (HAVE_FCHOWN && dest_desc != -1)
220 if (fchown (dest_desc, uid, gid) == 0)
222 if (errno == EPERM || errno == EINVAL)
224 /* We've failed to set *both*. Now, try to set just the group
225 ID, but ignore any failure here, and don't change errno. */
226 int saved_errno = errno;
227 (void) fchown (dest_desc, -1, gid);
233 if (lchown (dst_name, uid, gid) == 0)
235 if (errno == EPERM || errno == EINVAL)
237 /* We've failed to set *both*. Now, try to set just the group
238 ID, but ignore any failure here, and don't change errno. */
239 int saved_errno = errno;
240 (void) lchown (dst_name, -1, gid);
245 if (! chown_failure_ok (x))
247 error (0, errno, _("failed to preserve ownership for %s"),
249 if (x->require_preserve)
256 /* Set the st_author field of DEST_DESC to the st_author field of
257 SRC_SB. If DEST_DESC is undefined (-1), set the st_author field
258 of DST_NAME instead. DEST_DESC must refer to the same file as
259 DEST_NAME if defined. */
262 set_author (const char *dst_name, int dest_desc, const struct stat *src_sb)
264 #if HAVE_STRUCT_STAT_ST_AUTHOR
265 /* FIXME: Modify the following code so that it does not
266 follow symbolic links. */
268 /* Preserve the st_author field. */
269 file_t file = (dest_desc < 0
270 ? file_name_lookup (dst_name, 0, 0)
271 : getdport (dest_desc));
272 if (file == MACH_PORT_NULL)
273 error (0, errno, _("failed to lookup file %s"), quote (dst_name));
276 error_t err = file_chauthor (file, src_sb->st_author);
278 error (0, err, _("failed to preserve authorship for %s"),
280 mach_port_deallocate (mach_task_self (), file);
289 /* Change the file mode bits of the file identified by DESC or NAME to MODE.
290 Use DESC if DESC is valid and fchmod is available, NAME otherwise. */
293 fchmod_or_lchmod (int desc, char const *name, mode_t mode)
297 return fchmod (desc, mode);
299 return lchmod (name, mode);
302 /* Copy a regular file from SRC_NAME to DST_NAME.
303 If the source file contains holes, copies holes and blocks of zeros
304 in the source file as holes in the destination file.
305 (Holes are read as zeroes by the `read' system call.)
306 When creating the destination, use DST_MODE & ~OMITTED_PERMISSIONS
307 as the third argument in the call to open, adding
308 OMITTED_PERMISSIONS after copying as needed.
309 X provides many option settings.
310 Return true if successful.
311 *NEW_DST is as in copy_internal.
312 SRC_SB is the result of calling XSTAT (aka stat) on SRC_NAME. */
315 copy_reg (char const *src_name, char const *dst_name,
316 const struct cp_options *x,
317 mode_t dst_mode, mode_t omitted_permissions, bool *new_dst,
318 struct stat const *src_sb)
321 char *buf_alloc = NULL;
322 char *name_alloc = NULL;
326 mode_t src_mode = src_sb->st_mode;
328 struct stat src_open_sb;
329 bool return_val = true;
331 source_desc = open (src_name,
333 | (x->dereference == DEREF_NEVER ? O_NOFOLLOW : 0)));
336 error (0, errno, _("cannot open %s for reading"), quote (src_name));
340 if (fstat (source_desc, &src_open_sb) != 0)
342 error (0, errno, _("cannot fstat %s"), quote (src_name));
347 /* Compare the source dev/ino from the open file to the incoming,
348 saved ones obtained via a previous call to stat. */
349 if (! SAME_INODE (*src_sb, src_open_sb))
352 _("skipping file %s, as it was replaced while being copied"),
358 /* The semantics of the following open calls are mandated
359 by the specs for both cp and mv. */
362 dest_desc = open (dst_name, O_WRONLY | O_TRUNC | O_BINARY);
365 /* When using cp --preserve=context to copy to an existing destination,
366 use the default context rather than that of the source. Why?
367 1) the src context may prohibit writing, and
368 2) because it's more consistent to use the same context
369 that is used when the destination file doesn't already exist. */
370 if (x->preserve_security_context && 0 <= dest_desc)
372 security_context_t con = NULL;
373 if (getfscreatecon (&con) < 0)
375 error (0, errno, _("failed to get file system create context"));
376 if (x->require_preserve_context)
379 goto close_src_and_dst_desc;
385 if (fsetfilecon (dest_desc, con) < 0)
388 _("failed to set the security context of %s to %s"),
389 quote_n (0, dst_name), quote_n (1, con));
390 if (x->require_preserve_context)
394 goto close_src_and_dst_desc;
401 if (dest_desc < 0 && x->unlink_dest_after_failed_open)
403 if (unlink (dst_name) != 0)
405 error (0, errno, _("cannot remove %s"), quote (dst_name));
410 printf (_("removed %s\n"), quote (dst_name));
412 /* Tell caller that the destination file was unlinked. */
419 int open_flags = O_WRONLY | O_CREAT | O_BINARY;
420 dest_desc = open (dst_name, open_flags | O_EXCL ,
421 dst_mode & ~omitted_permissions);
424 /* When trying to copy through a dangling destination symlink,
425 the above open fails with EEXIST. If that happens, and
426 lstat'ing the DST_NAME shows that it is a symlink, then we
427 have a problem: trying to resolve this dangling symlink to
428 a directory/destination-entry pair is fundamentally racy,
429 so punt. If POSIXLY_CORRECT is set, simply call open again,
430 but without O_EXCL (potentially dangerous). If not, fail
431 with a diagnostic. These shenanigans are necessary only
432 when copying, i.e., not in move_mode. */
433 if (dest_desc < 0 && dest_errno == EEXIST && ! x->move_mode)
435 struct stat dangling_link_sb;
436 if (lstat (dst_name, &dangling_link_sb) == 0
437 && S_ISLNK (dangling_link_sb.st_mode))
439 if (x->open_dangling_dest_symlink)
441 dest_desc = open (dst_name, open_flags,
442 dst_mode & ~omitted_permissions);
447 error (0, 0, _("not writing through dangling symlink %s"),
456 omitted_permissions = 0;
460 error (0, dest_errno, _("cannot create regular file %s"),
466 if (fstat (dest_desc, &sb) != 0)
468 error (0, errno, _("cannot fstat %s"), quote (dst_name));
470 goto close_src_and_dst_desc;
474 typedef uintptr_t word;
475 off_t n_read_total = 0;
477 /* Choose a suitable buffer size; it may be adjusted later. */
478 size_t buf_alignment = lcm (getpagesize (), sizeof (word));
479 size_t buf_alignment_slop = sizeof (word) + buf_alignment - 1;
480 size_t buf_size = ST_BLKSIZE (sb);
482 /* Deal with sparse files. */
483 bool last_write_made_hole = false;
484 bool make_holes = false;
486 if (S_ISREG (sb.st_mode))
488 /* Even with --sparse=always, try to create holes only
489 if the destination is a regular file. */
490 if (x->sparse_mode == SPARSE_ALWAYS)
493 #if HAVE_STRUCT_STAT_ST_BLOCKS
494 /* Use a heuristic to determine whether SRC_NAME contains any sparse
495 blocks. If the file has fewer blocks than would normally be
496 needed for a file of its size, then at least one of the blocks in
497 the file is a hole. */
498 if (x->sparse_mode == SPARSE_AUTO && S_ISREG (src_open_sb.st_mode)
499 && ST_NBLOCKS (src_open_sb) < src_open_sb.st_size / ST_NBLOCKSIZE)
504 /* If not making a sparse file, try to use a more-efficient
508 /* These days there's no point ever messing with buffers smaller
509 than 8 KiB. It would be nice to configure SMALL_BUF_SIZE
510 dynamically for this host and pair of files, but there doesn't
511 seem to be a good way to get readahead info portably. */
512 enum { SMALL_BUF_SIZE = 8 * 1024 };
514 /* Compute the least common multiple of the input and output
515 buffer sizes, adjusting for outlandish values. */
516 size_t blcm_max = MIN (SIZE_MAX, SSIZE_MAX) - buf_alignment_slop;
517 size_t blcm = buffer_lcm (ST_BLKSIZE (src_open_sb), buf_size,
520 /* Do not use a block size that is too small. */
521 buf_size = MAX (SMALL_BUF_SIZE, blcm);
523 /* Do not bother with a buffer larger than the input file, plus one
524 byte to make sure the file has not grown while reading it. */
525 if (S_ISREG (src_open_sb.st_mode) && src_open_sb.st_size < buf_size)
526 buf_size = src_open_sb.st_size + 1;
528 /* However, stick with a block size that is a positive multiple of
529 blcm, overriding the above adjustments. Watch out for
531 buf_size += blcm - 1;
532 buf_size -= buf_size % blcm;
533 if (buf_size == 0 || blcm_max < buf_size)
537 /* Make a buffer with space for a sentinel at the end. */
538 buf_alloc = xmalloc (buf_size + buf_alignment_slop);
539 buf = ptr_align (buf_alloc, buf_alignment);
545 ssize_t n_read = read (source_desc, buf, buf_size);
552 error (0, errno, _("reading %s"), quote (src_name));
554 goto close_src_and_dst_desc;
559 n_read_total += n_read;
565 /* Sentinel to stop loop. */
568 /* Usually, buf[n_read] is not the byte just before a "word"
569 (aka uintptr_t) boundary. In that case, the word-oriented
570 test below (*wp++ == 0) would read some uninitialized bytes
571 after the sentinel. To avoid false-positive reports about
572 this condition (e.g., from a tool like valgrind), set the
573 remaining bytes -- to any value. */
574 memset (buf + n_read + 1, 0, sizeof (word) - 1);
577 /* Find first nonzero *word*, or the word with the sentinel. */
583 /* Find the first nonzero *byte*, or the sentinel. */
585 cp = (char *) (wp - 1);
589 if (cp <= buf + n_read)
590 /* Clear to indicate that a normal write is needed. */
594 /* We found the sentinel, so the whole input block was zero.
596 if (lseek (dest_desc, n_read, SEEK_CUR) < 0)
598 error (0, errno, _("cannot lseek %s"), quote (dst_name));
600 goto close_src_and_dst_desc;
602 last_write_made_hole = true;
609 if (full_write (dest_desc, buf, n) != n)
611 error (0, errno, _("writing %s"), quote (dst_name));
613 goto close_src_and_dst_desc;
615 last_write_made_hole = false;
617 /* A short read on a regular file means EOF. */
618 if (n_read != buf_size && S_ISREG (src_open_sb.st_mode))
623 /* If the file ends with a `hole', we need to do something to record
624 the length of the file. On modern systems, calling ftruncate does
625 the job. On systems without native ftruncate support, we have to
626 write a byte at the ending position. Otherwise the kernel would
627 truncate the file at the end of the last write operation. */
629 if (last_write_made_hole)
632 ? /* ftruncate sets the file size,
633 so there is no need for a write. */
634 ftruncate (dest_desc, n_read_total) < 0
635 : /* Seek backwards one character and write a null. */
636 (lseek (dest_desc, (off_t) -1, SEEK_CUR) < 0L
637 || full_write (dest_desc, "", 1) != 1))
639 error (0, errno, _("writing %s"), quote (dst_name));
641 goto close_src_and_dst_desc;
646 if (x->preserve_timestamps)
648 struct timespec timespec[2];
649 timespec[0] = get_stat_atime (src_sb);
650 timespec[1] = get_stat_mtime (src_sb);
652 if (gl_futimens (dest_desc, dst_name, timespec) != 0)
654 error (0, errno, _("preserving times for %s"), quote (dst_name));
655 if (x->require_preserve)
658 goto close_src_and_dst_desc;
663 if (x->preserve_ownership && ! SAME_OWNER_AND_GROUP (*src_sb, sb))
665 switch (set_owner (x, dst_name, dest_desc, src_sb, *new_dst, &sb))
669 goto close_src_and_dst_desc;
672 src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX);
677 set_author (dst_name, dest_desc, src_sb);
679 if (x->preserve_mode || x->move_mode)
681 if (copy_acl (src_name, source_desc, dst_name, dest_desc, src_mode) != 0
682 && x->require_preserve)
685 else if (x->set_mode)
687 if (set_acl (dst_name, dest_desc, x->mode) != 0)
690 else if (omitted_permissions)
692 omitted_permissions &= ~ cached_umask ();
693 if (omitted_permissions
694 && fchmod_or_lchmod (dest_desc, dst_name, dst_mode) != 0)
696 error (0, errno, _("preserving permissions for %s"),
698 if (x->require_preserve)
703 close_src_and_dst_desc:
704 if (close (dest_desc) < 0)
706 error (0, errno, _("closing %s"), quote (dst_name));
710 if (close (source_desc) < 0)
712 error (0, errno, _("closing %s"), quote (src_name));
721 /* Return true if it's ok that the source and destination
722 files are the `same' by some measure. The goal is to avoid
723 making the `copy' operation remove both copies of the file
724 in that case, while still allowing the user to e.g., move or
725 copy a regular file onto a symlink that points to it.
726 Try to minimize the cost of this function in the common case.
727 Set *RETURN_NOW if we've determined that the caller has no more
728 work to do and should return successfully, right away.
730 Set *UNLINK_SRC if we've determined that the caller wants to do
731 `rename (a, b)' where `a' and `b' are distinct hard links to the same
732 file. In that case, the caller should try to unlink `a' and then return
733 successfully. Ideally, we wouldn't have to do that, and we'd be
734 able to rely on rename to remove the source file. However, POSIX
735 mistakenly requires that such a rename call do *nothing* and return
739 same_file_ok (char const *src_name, struct stat const *src_sb,
740 char const *dst_name, struct stat const *dst_sb,
741 const struct cp_options *x, bool *return_now, bool *unlink_src)
743 const struct stat *src_sb_link;
744 const struct stat *dst_sb_link;
745 struct stat tmp_dst_sb;
746 struct stat tmp_src_sb;
749 bool same = SAME_INODE (*src_sb, *dst_sb);
754 /* FIXME: this should (at the very least) be moved into the following
755 if-block. More likely, it should be removed, because it inhibits
756 making backups. But removing it will result in a change in behavior
757 that will probably have to be documented -- and tests will have to
759 if (same && x->hard_link)
765 if (x->dereference == DEREF_NEVER)
769 /* If both the source and destination files are symlinks (and we'll
770 know this here IFF preserving symlinks), then it's ok -- as long
771 as they are distinct. */
772 if (S_ISLNK (src_sb->st_mode) && S_ISLNK (dst_sb->st_mode))
773 return ! same_name (src_name, dst_name);
775 src_sb_link = src_sb;
776 dst_sb_link = dst_sb;
783 if (lstat (dst_name, &tmp_dst_sb) != 0
784 || lstat (src_name, &tmp_src_sb) != 0)
787 src_sb_link = &tmp_src_sb;
788 dst_sb_link = &tmp_dst_sb;
790 same_link = SAME_INODE (*src_sb_link, *dst_sb_link);
792 /* If both are symlinks, then it's ok, but only if the destination
793 will be unlinked before being opened. This is like the test
794 above, but with the addition of the unlink_dest_before_opening
795 conjunct because otherwise, with two symlinks to the same target,
796 we'd end up truncating the source file. */
797 if (S_ISLNK (src_sb_link->st_mode) && S_ISLNK (dst_sb_link->st_mode)
798 && x->unlink_dest_before_opening)
802 /* The backup code ensures there's a copy, so it's usually ok to
803 remove any destination file. One exception is when both
804 source and destination are the same directory entry. In that
805 case, moving the destination file aside (in making the backup)
806 would also rename the source file and result in an error. */
807 if (x->backup_type != no_backups)
811 /* In copy mode when dereferencing symlinks, if the source is a
812 symlink and the dest is not, then backing up the destination
813 (moving it aside) would make it a dangling symlink, and the
814 subsequent attempt to open it in copy_reg would fail with
815 a misleading diagnostic. Avoid that by returning zero in
816 that case so the caller can make cp (or mv when it has to
817 resort to reading the source file) fail now. */
819 /* FIXME-note: even with the following kludge, we can still provoke
820 the offending diagnostic. It's just a little harder to do :-)
821 $ rm -f a b c; touch c; ln -s c b; ln -s b a; cp -b a b
822 cp: cannot open `a' for reading: No such file or directory
823 That's misleading, since a subsequent `ls' shows that `a'
825 One solution would be to open the source file *before* moving
826 aside the destination, but that'd involve a big rewrite. */
828 && x->dereference != DEREF_NEVER
829 && S_ISLNK (src_sb_link->st_mode)
830 && ! S_ISLNK (dst_sb_link->st_mode))
836 return ! same_name (src_name, dst_name);
840 /* FIXME: use or remove */
842 /* If we're making a backup, we'll detect the problem case in
843 copy_reg because SRC_NAME will no longer exist. Allowing
844 the test to be deferred lets cp do some useful things.
845 But when creating hardlinks and SRC_NAME is a symlink
846 but DST_NAME is not we must test anyway. */
848 || !S_ISLNK (src_sb_link->st_mode)
849 || S_ISLNK (dst_sb_link->st_mode))
852 if (x->dereference != DEREF_NEVER)
856 /* They may refer to the same file if we're in move mode and the
857 target is a symlink. That is ok, since we remove any existing
858 destination file before opening it -- via `rename' if they're on
859 the same file system, via `unlink (DST_NAME)' otherwise.
860 It's also ok if they're distinct hard links to the same file. */
861 if (x->move_mode || x->unlink_dest_before_opening)
863 if (S_ISLNK (dst_sb_link->st_mode))
867 && 1 < dst_sb_link->st_nlink
868 && ! same_name (src_name, dst_name))
879 /* If neither is a symlink, then it's ok as long as they aren't
880 hard links to the same file. */
881 if (!S_ISLNK (src_sb_link->st_mode) && !S_ISLNK (dst_sb_link->st_mode))
883 if (!SAME_INODE (*src_sb_link, *dst_sb_link))
886 /* If they are the same file, it's ok if we're making hard links. */
894 /* It's ok to remove a destination symlink. But that works only when we
895 unlink before opening the destination and when the source and destination
896 files are on the same partition. */
897 if (x->unlink_dest_before_opening
898 && S_ISLNK (dst_sb_link->st_mode))
899 return dst_sb_link->st_dev == src_sb_link->st_dev;
901 if (x->dereference == DEREF_NEVER)
903 if ( ! S_ISLNK (src_sb_link->st_mode))
904 tmp_src_sb = *src_sb_link;
905 else if (stat (src_name, &tmp_src_sb) != 0)
908 if ( ! S_ISLNK (dst_sb_link->st_mode))
909 tmp_dst_sb = *dst_sb_link;
910 else if (stat (dst_name, &tmp_dst_sb) != 0)
913 if ( ! SAME_INODE (tmp_src_sb, tmp_dst_sb))
916 /* FIXME: shouldn't this be testing whether we're making symlinks? */
927 /* Return true if FILE, with mode MODE, is writable in the sense of 'mv'.
928 Always consider a symbolic link to be writable. */
930 writable_destination (char const *file, mode_t mode)
932 return (S_ISLNK (mode)
933 || can_write_any_file ()
934 || euidaccess (file, W_OK) == 0);
938 overwrite_prompt (char const *dst_name, struct stat const *dst_sb)
940 if (! writable_destination (dst_name, dst_sb->st_mode))
942 char perms[12]; /* "-rwxrwxrwx " ls-style modes. */
943 strmode (dst_sb->st_mode, perms);
946 _("%s: try to overwrite %s, overriding mode %04lo (%s)? "),
947 program_name, quote (dst_name),
948 (unsigned long int) (dst_sb->st_mode & CHMOD_MODE_BITS),
953 fprintf (stderr, _("%s: overwrite %s? "),
954 program_name, quote (dst_name));
958 /* Initialize the hash table implementing a set of F_triple entries
959 corresponding to destination files. */
961 dest_info_init (struct cp_options *x)
964 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
971 /* Initialize the hash table implementing a set of F_triple entries
972 corresponding to source files listed on the command line. */
974 src_info_init (struct cp_options *x)
977 /* Note that we use triple_hash_no_name here.
978 Contrast with the use of triple_hash above.
979 That is necessary because a source file may be specified
980 in many different ways. We want to warn about this
986 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
993 /* When effecting a move (e.g., for mv(1)), and given the name DST_NAME
994 of the destination and a corresponding stat buffer, DST_SB, return
995 true if the logical `move' operation should _not_ proceed.
996 Otherwise, return false.
997 Depending on options specified in X, this code may issue an
998 interactive prompt asking whether it's ok to overwrite DST_NAME. */
1000 abandon_move (const struct cp_options *x,
1001 char const *dst_name,
1002 struct stat const *dst_sb)
1004 assert (x->move_mode);
1005 return (x->interactive == I_ALWAYS_NO
1006 || ((x->interactive == I_ASK_USER
1007 || (x->interactive == I_UNSPECIFIED
1009 && ! writable_destination (dst_name, dst_sb->st_mode)))
1010 && (overwrite_prompt (dst_name, dst_sb), 1)
1014 /* Print --verbose output on standard output, e.g. `new' -> `old'.
1015 If BACKUP_DST_NAME is non-NULL, then also indicate that it is
1016 the name of a backup file. */
1018 emit_verbose (char const *src, char const *dst, char const *backup_dst_name)
1020 printf ("%s -> %s", quote_n (0, src), quote_n (1, dst));
1021 if (backup_dst_name)
1022 printf (_(" (backup: %s)"), quote (backup_dst_name));
1026 /* A wrapper around "setfscreatecon (NULL)" that exits upon failure. */
1028 restore_default_fscreatecon_or_die (void)
1030 if (setfscreatecon (NULL) != 0)
1031 error (EXIT_FAILURE, errno,
1032 _("failed to restore the default file creation context"));
1035 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
1036 any type. NEW_DST should be true if the file DST_NAME cannot
1037 exist because its parent directory was just created; NEW_DST should
1038 be false if DST_NAME might already exist. DEVICE is the device
1039 number of the parent directory, or 0 if the parent of this file is
1040 not known. ANCESTORS points to a linked, null terminated list of
1041 devices and inodes of parent directories of SRC_NAME. COMMAND_LINE_ARG
1042 is true iff SRC_NAME was specified on the command line.
1043 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
1044 same as) DST_NAME; otherwise, clear it.
1045 Return true if successful. */
1047 copy_internal (char const *src_name, char const *dst_name,
1050 struct dir_list *ancestors,
1051 const struct cp_options *x,
1052 bool command_line_arg,
1053 bool *copy_into_self,
1054 bool *rename_succeeded)
1059 mode_t dst_mode IF_LINT (= 0);
1060 mode_t dst_mode_bits;
1061 mode_t omitted_permissions;
1062 bool restore_dst_mode = false;
1063 char *earlier_file = NULL;
1064 char *dst_backup = NULL;
1065 bool backup_succeeded = false;
1067 bool copied_as_regular = false;
1068 bool preserve_metadata;
1069 bool have_dst_lstat = false;
1071 if (x->move_mode && rename_succeeded)
1072 *rename_succeeded = false;
1074 *copy_into_self = false;
1076 if (XSTAT (x, src_name, &src_sb) != 0)
1078 error (0, errno, _("cannot stat %s"), quote (src_name));
1082 src_mode = src_sb.st_mode;
1084 if (S_ISDIR (src_mode) && !x->recursive)
1086 error (0, 0, _("omitting directory %s"), quote (src_name));
1090 /* Detect the case in which the same source file appears more than
1091 once on the command line and no backup option has been selected.
1092 If so, simply warn and don't copy it the second time.
1093 This check is enabled only if x->src_info is non-NULL. */
1094 if (command_line_arg)
1096 if ( ! S_ISDIR (src_sb.st_mode)
1097 && x->backup_type == no_backups
1098 && seen_file (x->src_info, src_name, &src_sb))
1100 error (0, 0, _("warning: source file %s specified more than once"),
1105 record_file (x->src_info, src_name, &src_sb);
1110 /* Regular files can be created by writing through symbolic
1111 links, but other files cannot. So use stat on the
1112 destination when copying a regular file, and lstat otherwise.
1113 However, if we intend to unlink or remove the destination
1114 first, use lstat, since a copy won't actually be made to the
1115 destination in that case. */
1117 ((S_ISREG (src_mode)
1118 || (x->copy_as_regular
1119 && ! (S_ISDIR (src_mode) || S_ISLNK (src_mode))))
1120 && ! (x->move_mode || x->symbolic_link || x->hard_link
1121 || x->backup_type != no_backups
1122 || x->unlink_dest_before_opening));
1124 ? stat (dst_name, &dst_sb)
1125 : lstat (dst_name, &dst_sb))
1128 if (errno != ENOENT)
1130 error (0, errno, _("cannot stat %s"), quote (dst_name));
1139 { /* Here, we know that dst_name exists, at least to the point
1140 that it is stat'able or lstat'able. */
1144 have_dst_lstat = !use_stat;
1145 if (! same_file_ok (src_name, &src_sb, dst_name, &dst_sb,
1146 x, &return_now, &unlink_src))
1148 error (0, 0, _("%s and %s are the same file"),
1149 quote_n (0, src_name), quote_n (1, dst_name));
1153 if (!S_ISDIR (src_mode) && x->update)
1155 /* When preserving time stamps (but not moving within a file
1156 system), don't worry if the destination time stamp is
1157 less than the source merely because of time stamp
1159 int options = ((x->preserve_timestamps
1161 && dst_sb.st_dev == src_sb.st_dev))
1162 ? UTIMECMP_TRUNCATE_SOURCE
1165 if (0 <= utimecmp (dst_name, &dst_sb, &src_sb, options))
1167 /* We're using --update and the destination is not older
1168 than the source, so do not copy or move. Pretend the
1169 rename succeeded, so the caller (if it's mv) doesn't
1170 end up removing the source file. */
1171 if (rename_succeeded)
1172 *rename_succeeded = true;
1177 /* When there is an existing destination file, we may end up
1178 returning early, and hence not copying/moving the file.
1179 This may be due to an interactive `negative' reply to the
1180 prompt about the existing file. It may also be due to the
1181 use of the --reply=no option.
1183 cp and mv treat -i and -f differently. */
1186 if (abandon_move (x, dst_name, &dst_sb)
1187 || (unlink_src && unlink (src_name) == 0))
1189 /* Pretend the rename succeeded, so the caller (mv)
1190 doesn't end up removing the source file. */
1191 if (rename_succeeded)
1192 *rename_succeeded = true;
1193 if (unlink_src && x->verbose)
1194 printf (_("removed %s\n"), quote (src_name));
1199 error (0, errno, _("cannot remove %s"), quote (src_name));
1205 if (! S_ISDIR (src_mode)
1206 && (x->interactive == I_ALWAYS_NO
1207 || (x->interactive == I_ASK_USER
1208 && (overwrite_prompt (dst_name, &dst_sb), 1)
1216 if (!S_ISDIR (dst_sb.st_mode))
1218 if (S_ISDIR (src_mode))
1220 if (x->move_mode && x->backup_type != no_backups)
1222 /* Moving a directory onto an existing
1223 non-directory is ok only with --backup. */
1228 _("cannot overwrite non-directory %s with directory %s"),
1229 quote_n (0, dst_name), quote_n (1, src_name));
1234 /* Don't let the user destroy their data, even if they try hard:
1235 This mv command must fail (likewise for cp):
1236 rm -rf a b c; mkdir a b c; touch a/f b/f; mv a/f b/f c
1237 Otherwise, the contents of b/f would be lost.
1238 In the case of `cp', b/f would be lost if the user simulated
1239 a move using cp and rm.
1240 Note that it works fine if you use --backup=numbered. */
1241 if (command_line_arg
1242 && x->backup_type != numbered_backups
1243 && seen_file (x->dest_info, dst_name, &dst_sb))
1246 _("will not overwrite just-created %s with %s"),
1247 quote_n (0, dst_name), quote_n (1, src_name));
1252 if (!S_ISDIR (src_mode))
1254 if (S_ISDIR (dst_sb.st_mode))
1256 if (x->move_mode && x->backup_type != no_backups)
1258 /* Moving a non-directory onto an existing
1259 directory is ok only with --backup. */
1264 _("cannot overwrite directory %s with non-directory"),
1273 /* Don't allow user to move a directory onto a non-directory. */
1274 if (S_ISDIR (src_sb.st_mode) && !S_ISDIR (dst_sb.st_mode)
1275 && x->backup_type == no_backups)
1278 _("cannot move directory onto non-directory: %s -> %s"),
1279 quote_n (0, src_name), quote_n (0, dst_name));
1284 if (x->backup_type != no_backups
1285 /* Don't try to back up a destination if the last
1286 component of src_name is "." or "..". */
1287 && ! dot_or_dotdot (last_component (src_name))
1288 /* Create a backup of each destination directory in move mode,
1289 but not in copy mode. FIXME: it might make sense to add an
1290 option to suppress backup creation also for move mode.
1291 That would let one use mv to merge new content into an
1292 existing hierarchy. */
1293 && (x->move_mode || ! S_ISDIR (dst_sb.st_mode)))
1295 char *tmp_backup = find_backup_file_name (dst_name,
1298 /* Detect (and fail) when creating the backup file would
1299 destroy the source file. Before, running the commands
1300 cd /tmp; rm -f a a~; : > a; echo A > a~; cp --b=simple a~ a
1301 would leave two zero-length files: a and a~. */
1302 /* FIXME: but simply change e.g., the final a~ to `./a~'
1303 and the source will still be destroyed. */
1304 if (STREQ (tmp_backup, src_name))
1308 ? _("backing up %s would destroy source; %s not moved")
1309 : _("backing up %s would destroy source; %s not copied"));
1311 quote_n (0, dst_name),
1312 quote_n (1, src_name));
1318 Using alloca for a file name that may be arbitrarily
1319 long is not recommended. In fact, even forming such a name
1320 should be discouraged. Eventually, this code will be rewritten
1321 to use fts, so using alloca here will be less of a problem. */
1322 ASSIGN_STRDUPA (dst_backup, tmp_backup);
1324 if (rename (dst_name, dst_backup) != 0)
1326 if (errno != ENOENT)
1328 error (0, errno, _("cannot backup %s"), quote (dst_name));
1338 backup_succeeded = true;
1342 else if (! S_ISDIR (dst_sb.st_mode)
1343 && (x->unlink_dest_before_opening
1344 || (x->preserve_links && 1 < dst_sb.st_nlink)
1346 && x->dereference == DEREF_NEVER
1347 && S_ISLNK (src_sb.st_mode))
1350 if (unlink (dst_name) != 0 && errno != ENOENT)
1352 error (0, errno, _("cannot remove %s"), quote (dst_name));
1357 printf (_("removed %s\n"), quote (dst_name));
1362 /* Ensure we don't try to copy through a symlink that was
1363 created by a prior call to this function. */
1364 if (command_line_arg
1367 && x->backup_type == no_backups)
1369 bool lstat_ok = true;
1370 struct stat tmp_buf;
1371 struct stat *dst_lstat_sb;
1373 /* If we called lstat above, good: use that data.
1374 Otherwise, call lstat here, in case dst_name is a symlink. */
1376 dst_lstat_sb = &dst_sb;
1379 if (lstat (dst_name, &tmp_buf) == 0)
1380 dst_lstat_sb = &tmp_buf;
1385 /* Never copy through a symlink we've just created. */
1387 && S_ISLNK (dst_lstat_sb->st_mode)
1388 && seen_file (x->dest_info, dst_name, dst_lstat_sb))
1391 _("will not copy %s through just-created symlink %s"),
1392 quote_n (0, src_name), quote_n (1, dst_name));
1397 /* If the source is a directory, we don't always create the destination
1398 directory. So --verbose should not announce anything until we're
1399 sure we'll create a directory. */
1400 if (x->verbose && !S_ISDIR (src_mode))
1401 emit_verbose (src_name, dst_name, backup_succeeded ? dst_backup : NULL);
1403 /* Associate the destination file name with the source device and inode
1404 so that if we encounter a matching dev/ino pair in the source tree
1405 we can arrange to create a hard link between the corresponding names
1406 in the destination tree.
1408 Sometimes, when preserving links, we have to record dev/ino even
1409 though st_nlink == 1:
1410 - when in move_mode, since we may be moving a group of N hard-linked
1411 files (via two or more command line arguments) to a different
1412 partition; the links may be distributed among the command line
1413 arguments (possibly hierarchies) so that the link count of
1414 the final, once-linked source file is reduced to 1 when it is
1415 considered below. But in this case (for mv) we don't need to
1416 incur the expense of recording the dev/ino => name mapping; all we
1417 really need is a lookup, to see if the dev/ino pair has already
1419 - when using -H and processing a command line argument;
1420 that command line argument could be a symlink pointing to another
1421 command line argument. With `cp -H --preserve=link', we hard-link
1422 those two destination files.
1423 - likewise for -L except that it applies to all files, not just
1424 command line arguments.
1426 Also record directory dev/ino when using --recursive. We'll use that
1427 info to detect this problem: cp -R dir dir. FIXME-maybe: ideally,
1428 directory info would be recorded in a separate hash table, since
1429 such entries are useful only while a single command line hierarchy
1430 is being copied -- so that separate table could be cleared between
1431 command line args. Using the same hash table to preserve hard
1432 links means that it may not be cleared. */
1434 if (x->move_mode && src_sb.st_nlink == 1)
1436 earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev);
1438 else if ((x->preserve_links
1439 && (1 < src_sb.st_nlink
1440 || (command_line_arg
1441 && x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
1442 || x->dereference == DEREF_ALWAYS))
1443 || (x->recursive && S_ISDIR (src_mode)))
1445 earlier_file = remember_copied (dst_name, src_sb.st_ino, src_sb.st_dev);
1448 /* Did we copy this inode somewhere else (in this command line argument)
1449 and therefore this is a second hard link to the inode? */
1453 /* Avoid damaging the destination file system by refusing to preserve
1454 hard-linked directories (which are found at least in Netapp snapshot
1456 if (S_ISDIR (src_mode))
1458 /* If src_name and earlier_file refer to the same directory entry,
1459 then warn about copying a directory into itself. */
1460 if (same_name (src_name, earlier_file))
1462 error (0, 0, _("cannot copy a directory, %s, into itself, %s"),
1463 quote_n (0, top_level_src_name),
1464 quote_n (1, top_level_dst_name));
1465 *copy_into_self = true;
1468 else if (x->dereference == DEREF_ALWAYS)
1470 /* This happens when e.g., encountering a directory for the
1471 second or subsequent time via symlinks when cp is invoked
1472 with -R and -L. E.g.,
1473 rm -rf a b c d; mkdir a b c d; ln -s ../c a; ln -s ../c b;
1479 error (0, 0, _("will not create hard link %s to directory %s"),
1480 quote_n (0, dst_name), quote_n (1, earlier_file));
1486 bool link_failed = (link (earlier_file, dst_name) != 0);
1488 /* If the link failed because of an existing destination,
1489 remove that file and then call link again. */
1490 if (link_failed && errno == EEXIST)
1492 if (unlink (dst_name) != 0)
1494 error (0, errno, _("cannot remove %s"), quote (dst_name));
1498 printf (_("removed %s\n"), quote (dst_name));
1499 link_failed = (link (earlier_file, dst_name) != 0);
1504 error (0, errno, _("cannot create hard link %s to %s"),
1505 quote_n (0, dst_name), quote_n (1, earlier_file));
1515 if (rename (src_name, dst_name) == 0)
1517 if (x->verbose && S_ISDIR (src_mode))
1518 emit_verbose (src_name, dst_name,
1519 backup_succeeded ? dst_backup : NULL);
1521 if (rename_succeeded)
1522 *rename_succeeded = true;
1524 if (command_line_arg)
1526 /* Record destination dev/ino/name, so that if we are asked
1527 to overwrite that file again, we can detect it and fail. */
1528 /* It's fine to use the _source_ stat buffer (src_sb) to get the
1529 _destination_ dev/ino, since the rename above can't have
1530 changed those, and `mv' always uses lstat.
1531 We could limit it further by operating
1532 only on non-directories. */
1533 record_file (x->dest_info, dst_name, &src_sb);
1539 /* FIXME: someday, consider what to do when moving a directory into
1540 itself but when source and destination are on different devices. */
1542 /* This happens when attempting to rename a directory to a
1543 subdirectory of itself. */
1544 if (errno == EINVAL)
1546 /* FIXME: this is a little fragile in that it relies on rename(2)
1547 failing with a specific errno value. Expect problems on
1548 non-POSIX systems. */
1549 error (0, 0, _("cannot move %s to a subdirectory of itself, %s"),
1550 quote_n (0, top_level_src_name),
1551 quote_n (1, top_level_dst_name));
1553 /* Note that there is no need to call forget_created here,
1554 (compare with the other calls in this file) since the
1555 destination directory didn't exist before. */
1557 *copy_into_self = true;
1558 /* FIXME-cleanup: Don't return true here; adjust mv.c accordingly.
1559 The only caller that uses this code (mv.c) ends up setting its
1560 exit status to nonzero when copy_into_self is nonzero. */
1564 /* WARNING: there probably exist systems for which an inter-device
1565 rename fails with a value of errno not handled here.
1566 If/as those are reported, add them to the condition below.
1567 If this happens to you, please do the following and send the output
1568 to the bug-reporting address (e.g., in the output of cp --help):
1569 touch k; perl -e 'rename "k","/tmp/k" or print "$!(",$!+0,")\n"'
1570 where your current directory is on one partion and /tmp is the other.
1571 Also, please try to find the E* errno macro name corresponding to
1572 the diagnostic and parenthesized integer, and include that in your
1573 e-mail. One way to do that is to run a command like this
1574 find /usr/include/. -type f \
1575 | xargs grep 'define.*\<E[A-Z]*\>.*\<18\>' /dev/null
1576 where you'd replace `18' with the integer in parentheses that
1577 was output from the perl one-liner above.
1578 If necessary, of course, change `/tmp' to some other directory. */
1581 /* There are many ways this can happen due to a race condition.
1582 When something happens between the initial XSTAT and the
1583 subsequent rename, we can get many different types of errors.
1584 For example, if the destination is initially a non-directory
1585 or non-existent, but it is created as a directory, the rename
1586 fails. If two `mv' commands try to rename the same file at
1587 about the same time, one will succeed and the other will fail.
1588 If the permissions on the directory containing the source or
1589 destination file are made too restrictive, the rename will
1592 _("cannot move %s to %s"),
1593 quote_n (0, src_name), quote_n (1, dst_name));
1594 forget_created (src_sb.st_ino, src_sb.st_dev);
1598 /* The rename attempt has failed. Remove any existing destination
1599 file so that a cross-device `mv' acts as if it were really using
1600 the rename syscall. */
1601 if (unlink (dst_name) != 0 && errno != ENOENT)
1604 _("inter-device move failed: %s to %s; unable to remove target"),
1605 quote_n (0, src_name), quote_n (1, dst_name));
1606 forget_created (src_sb.st_ino, src_sb.st_dev);
1613 /* If the ownership might change, or if it is a directory (whose
1614 special mode bits may change after the directory is created),
1615 omit some permissions at first, so unauthorized users cannot nip
1616 in before the file is ready. */
1617 dst_mode_bits = (x->set_mode ? x->mode : src_mode) & CHMOD_MODE_BITS;
1618 omitted_permissions =
1620 & (x->preserve_ownership ? S_IRWXG | S_IRWXO
1621 : S_ISDIR (src_mode) ? S_IWGRP | S_IWOTH
1626 if (x->preserve_security_context)
1628 security_context_t con;
1630 if (0 <= lgetfilecon (src_name, &con))
1632 if (setfscreatecon (con) < 0)
1635 _("failed to set default file creation context to %s"),
1637 if (x->require_preserve_context)
1647 if (errno != ENOTSUP && errno != ENODATA)
1650 _("failed to get security context of %s"),
1652 if (x->require_preserve_context)
1658 /* In certain modes (cp's --symbolic-link), and for certain file types
1659 (symlinks and hard links) it doesn't make sense to preserve metadata,
1660 or it's possible to preserve only some of it.
1661 In such cases, set this variable to zero. */
1662 preserve_metadata = true;
1664 if (S_ISDIR (src_mode))
1666 struct dir_list *dir;
1668 /* If this directory has been copied before during the
1669 recursion, there is a symbolic link to an ancestor
1670 directory of the symbolic link. It is impossible to
1671 continue to copy this, unless we've got an infinite disk. */
1673 if (is_ancestor (&src_sb, ancestors))
1675 error (0, 0, _("cannot copy cyclic symbolic link %s"),
1680 /* Insert the current directory in the list of parents. */
1682 dir = alloca (sizeof *dir);
1683 dir->parent = ancestors;
1684 dir->ino = src_sb.st_ino;
1685 dir->dev = src_sb.st_dev;
1687 if (new_dst || !S_ISDIR (dst_sb.st_mode))
1689 /* POSIX says mkdir's behavior is implementation-defined when
1690 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
1691 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
1692 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
1693 if (mkdir (dst_name, dst_mode_bits & ~omitted_permissions) != 0)
1695 error (0, errno, _("cannot create directory %s"),
1700 /* We need search and write permissions to the new directory
1701 for writing the directory's contents. Check if these
1702 permissions are there. */
1704 if (lstat (dst_name, &dst_sb) != 0)
1706 error (0, errno, _("cannot stat %s"), quote (dst_name));
1709 else if ((dst_sb.st_mode & S_IRWXU) != S_IRWXU)
1711 /* Make the new directory searchable and writable. */
1713 dst_mode = dst_sb.st_mode;
1714 restore_dst_mode = true;
1716 if (lchmod (dst_name, dst_mode | S_IRWXU) != 0)
1718 error (0, errno, _("setting permissions for %s"),
1724 /* Insert the created directory's inode and device
1725 numbers into the search structure, so that we can
1726 avoid copying it again. */
1728 remember_copied (dst_name, dst_sb.st_ino, dst_sb.st_dev);
1731 emit_verbose (src_name, dst_name, NULL);
1734 /* Decide whether to copy the contents of the directory. */
1735 if (x->one_file_system && device != 0 && device != src_sb.st_dev)
1737 /* Here, we are crossing a file system boundary and cp's -x option
1738 is in effect: so don't copy the contents of this directory. */
1742 /* Copy the contents of the directory. Don't just return if
1743 this fails -- otherwise, the failure to read a single file
1744 in a source directory would cause the containing destination
1745 directory not to have owner/perms set properly. */
1746 delayed_ok = copy_dir (src_name, dst_name, new_dst, &src_sb, dir, x,
1750 else if (x->symbolic_link)
1752 preserve_metadata = false;
1754 if (*src_name != '/')
1756 /* Check that DST_NAME denotes a file in the current directory. */
1758 struct stat dst_parent_sb;
1760 bool in_current_dir;
1762 dst_parent = dir_name (dst_name);
1764 in_current_dir = (STREQ (".", dst_parent)
1765 /* If either stat call fails, it's ok not to report
1766 the failure and say dst_name is in the current
1767 directory. Other things will fail later. */
1768 || stat (".", &dot_sb) != 0
1769 || stat (dst_parent, &dst_parent_sb) != 0
1770 || SAME_INODE (dot_sb, dst_parent_sb));
1773 if (! in_current_dir)
1776 _("%s: can make relative symbolic links only in current directory"),
1781 if (symlink (src_name, dst_name) != 0)
1783 error (0, errno, _("cannot create symbolic link %s to %s"),
1784 quote_n (0, dst_name), quote_n (1, src_name));
1789 else if (x->hard_link
1790 #ifdef LINK_FOLLOWS_SYMLINKS
1791 /* A POSIX-conforming link syscall dereferences a symlink, yet cp,
1792 invoked with `--link --no-dereference', should not. Thus, with
1793 a POSIX-conforming link system call, we can't use link() here,
1794 since that would create a hard link to the referent (effectively
1795 dereferencing the symlink), rather than to the symlink itself.
1796 We can approximate the desired behavior by skipping this hard-link
1797 creating block and instead copying the symlink, via the `S_ISLNK'-
1799 When link operates on the symlinks themselves, we use this block
1800 and just call link(). */
1801 && !(S_ISLNK (src_mode) && x->dereference == DEREF_NEVER)
1805 preserve_metadata = false;
1806 if (link (src_name, dst_name))
1808 error (0, errno, _("cannot create link %s"), quote (dst_name));
1812 else if (S_ISREG (src_mode)
1813 || (x->copy_as_regular && !S_ISLNK (src_mode)))
1815 copied_as_regular = true;
1816 /* POSIX says the permission bits of the source file must be
1817 used as the 3rd argument in the open call. Historical
1818 practice passed all the source mode bits to 'open', but the extra
1819 bits were ignored, so it should be the same either way. */
1820 if (! copy_reg (src_name, dst_name, x, src_mode & S_IRWXUGO,
1821 omitted_permissions, &new_dst, &src_sb))
1824 else if (S_ISFIFO (src_mode))
1826 /* Use mknod, rather than mkfifo, because the former preserves
1827 the special mode bits of a fifo on Solaris 10, while mkfifo
1828 does not. But fall back on mkfifo, because on some BSD systems,
1829 mknod always fails when asked to create a FIFO. */
1830 if (mknod (dst_name, src_mode & ~omitted_permissions, 0) != 0)
1832 if (mkfifo (dst_name, src_mode & ~S_IFIFO & ~omitted_permissions) != 0)
1835 error (0, errno, _("cannot create fifo %s"), quote (dst_name));
1839 else if (S_ISBLK (src_mode) || S_ISCHR (src_mode) || S_ISSOCK (src_mode))
1841 if (mknod (dst_name, src_mode & ~omitted_permissions, src_sb.st_rdev)
1844 error (0, errno, _("cannot create special file %s"),
1849 else if (S_ISLNK (src_mode))
1851 char *src_link_val = areadlink_with_size (src_name, src_sb.st_size);
1852 if (src_link_val == NULL)
1854 error (0, errno, _("cannot read symbolic link %s"), quote (src_name));
1858 if (symlink (src_link_val, dst_name) == 0)
1859 free (src_link_val);
1862 int saved_errno = errno;
1863 bool same_link = false;
1864 if (x->update && !new_dst && S_ISLNK (dst_sb.st_mode)
1865 && dst_sb.st_size == strlen (src_link_val))
1867 /* See if the destination is already the desired symlink.
1868 FIXME: This behavior isn't documented, and seems wrong
1869 in some cases, e.g., if the destination symlink has the
1870 wrong ownership, permissions, or time stamps. */
1871 char *dest_link_val =
1872 areadlink_with_size (dst_name, dst_sb.st_size);
1873 if (dest_link_val && STREQ (dest_link_val, src_link_val))
1875 free (dest_link_val);
1877 free (src_link_val);
1881 error (0, saved_errno, _("cannot create symbolic link %s"),
1887 if (x->preserve_security_context)
1888 restore_default_fscreatecon_or_die ();
1890 /* There's no need to preserve timestamps or permissions. */
1891 preserve_metadata = false;
1893 if (x->preserve_ownership)
1895 /* Preserve the owner and group of the just-`copied'
1896 symbolic link, if possible. */
1898 && lchown (dst_name, src_sb.st_uid, src_sb.st_gid) != 0
1899 && ! chown_failure_ok (x))
1901 error (0, errno, _("failed to preserve ownership for %s"),
1907 /* Can't preserve ownership of symlinks.
1908 FIXME: maybe give a warning or even error for symlinks
1909 in directories with the sticky bit set -- there, not
1910 preserving owner/group is a potential security problem. */
1916 error (0, 0, _("%s has unknown file type"), quote (src_name));
1920 if (command_line_arg && x->dest_info)
1922 /* Now that the destination file is very likely to exist,
1923 add its info to the set. */
1925 if (lstat (dst_name, &sb) == 0)
1926 record_file (x->dest_info, dst_name, &sb);
1929 if ( ! preserve_metadata)
1932 if (copied_as_regular)
1935 /* POSIX says that `cp -p' must restore the following:
1937 - setuid, setgid bits
1939 If it fails to restore any of those, we may give a warning but
1940 the destination must not be removed.
1941 FIXME: implement the above. */
1943 /* Adjust the times (and if possible, ownership) for the copy.
1944 chown turns off set[ug]id bits for non-root,
1945 so do the chmod last. */
1947 if (x->preserve_timestamps)
1949 struct timespec timespec[2];
1950 timespec[0] = get_stat_atime (&src_sb);
1951 timespec[1] = get_stat_mtime (&src_sb);
1953 if (utimens (dst_name, timespec) != 0)
1955 error (0, errno, _("preserving times for %s"), quote (dst_name));
1956 if (x->require_preserve)
1961 /* Avoid calling chown if we know it's not necessary. */
1962 if (x->preserve_ownership
1963 && (new_dst || !SAME_OWNER_AND_GROUP (src_sb, dst_sb)))
1965 switch (set_owner (x, dst_name, -1, &src_sb, new_dst, &dst_sb))
1971 src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX);
1976 set_author (dst_name, -1, &src_sb);
1978 if (x->preserve_mode || x->move_mode)
1980 if (copy_acl (src_name, -1, dst_name, -1, src_mode) != 0
1981 && x->require_preserve)
1984 else if (x->set_mode)
1986 if (set_acl (dst_name, -1, x->mode) != 0)
1991 if (omitted_permissions)
1993 omitted_permissions &= ~ cached_umask ();
1995 if (omitted_permissions && !restore_dst_mode)
1997 /* Permissions were deliberately omitted when the file
1998 was created due to security concerns. See whether
1999 they need to be re-added now. It'd be faster to omit
2000 the lstat, but deducing the current destination mode
2001 is tricky in the presence of implementation-defined
2002 rules for special mode bits. */
2003 if (new_dst && lstat (dst_name, &dst_sb) != 0)
2005 error (0, errno, _("cannot stat %s"), quote (dst_name));
2008 dst_mode = dst_sb.st_mode;
2009 if (omitted_permissions & ~dst_mode)
2010 restore_dst_mode = true;
2014 if (restore_dst_mode)
2016 if (lchmod (dst_name, dst_mode | omitted_permissions) != 0)
2018 error (0, errno, _("preserving permissions for %s"),
2020 if (x->require_preserve)
2030 if (x->preserve_security_context)
2031 restore_default_fscreatecon_or_die ();
2033 /* We have failed to create the destination file.
2034 If we've just added a dev/ino entry via the remember_copied
2035 call above (i.e., unless we've just failed to create a hard link),
2036 remove the entry associating the source dev/ino with the
2037 destination file name, so we don't try to `preserve' a link
2038 to a file we didn't create. */
2039 if (earlier_file == NULL)
2040 forget_created (src_sb.st_ino, src_sb.st_dev);
2044 if (rename (dst_backup, dst_name) != 0)
2045 error (0, errno, _("cannot un-backup %s"), quote (dst_name));
2049 printf (_("%s -> %s (unbackup)\n"),
2050 quote_n (0, dst_backup), quote_n (1, dst_name));
2057 valid_options (const struct cp_options *co)
2059 assert (co != NULL);
2060 assert (VALID_BACKUP_TYPE (co->backup_type));
2061 assert (VALID_SPARSE_MODE (co->sparse_mode));
2062 assert (!(co->hard_link && co->symbolic_link));
2066 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
2067 any type. NONEXISTENT_DST should be true if the file DST_NAME
2068 is known not to exist (e.g., because its parent directory was just
2069 created); NONEXISTENT_DST should be false if DST_NAME might already
2070 exist. OPTIONS is ... FIXME-describe
2071 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
2072 same as) DST_NAME; otherwise, set clear it.
2073 Return true if successful. */
2076 copy (char const *src_name, char const *dst_name,
2077 bool nonexistent_dst, const struct cp_options *options,
2078 bool *copy_into_self, bool *rename_succeeded)
2080 assert (valid_options (options));
2082 /* Record the file names: they're used in case of error, when copying
2083 a directory into itself. I don't like to make these tools do *any*
2084 extra work in the common case when that work is solely to handle
2085 exceptional cases, but in this case, I don't see a way to derive the
2086 top level source and destination directory names where they're used.
2087 An alternative is to use COPY_INTO_SELF and print the diagnostic
2088 from every caller -- but I don't want to do that. */
2089 top_level_src_name = src_name;
2090 top_level_dst_name = dst_name;
2092 return copy_internal (src_name, dst_name, nonexistent_dst, 0, NULL,
2093 options, true, copy_into_self, rename_succeeded);
2096 /* Set *X to the default options for a value of type struct cp_options. */
2099 cp_options_default (struct cp_options *x)
2101 memset (x, 0, sizeof *x);
2102 #ifdef PRIV_FILE_CHOWN
2104 priv_set_t *pset = priv_allocset ();
2107 if (getppriv (PRIV_EFFECTIVE, pset) == 0)
2109 x->chown_privileges = priv_ismember (pset, PRIV_FILE_CHOWN);
2110 x->owner_privileges = priv_ismember (pset, PRIV_FILE_OWNER);
2112 priv_freeset (pset);
2115 x->chown_privileges = x->owner_privileges = (geteuid () == 0);
2119 /* Return true if it's OK for chown to fail, where errno is
2120 the error number that chown failed with and X is the copying
2124 chown_failure_ok (struct cp_options const *x)
2126 /* If non-root uses -p, it's ok if we can't preserve ownership.
2127 But root probably wants to know, e.g. if NFS disallows it,
2128 or if the target system doesn't support file ownership. */
2130 return ((errno == EPERM || errno == EINVAL) && !x->chown_privileges);
2133 /* Similarly, return true if it's OK for chmod and similar operations
2134 to fail, where errno is the error number that chmod failed with and
2135 X is the copying option set. */
2138 owner_failure_ok (struct cp_options const *x)
2140 return ((errno == EPERM || errno == EINVAL) && !x->owner_privileges);
2143 /* Return the user's umask, caching the result. */
2148 static mode_t mask = (mode_t) -1;
2149 if (mask == (mode_t) -1)