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 2, 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"
39 #include "euidaccess.h"
43 #include "filenamecat.h"
44 #include "full-write.h"
45 #include "getpagesize.h"
52 #include "stat-time.h"
55 #include "write-any-file.h"
56 #include "xreadlink.h"
60 # define HAVE_FCHOWN false
61 # define fchown(fd, uid, gid) (-1)
64 #define SAME_OWNER(A, B) ((A).st_uid == (B).st_uid)
65 #define SAME_GROUP(A, B) ((A).st_gid == (B).st_gid)
66 #define SAME_OWNER_AND_GROUP(A, B) (SAME_OWNER (A, B) && SAME_GROUP (A, B))
70 struct dir_list *parent;
75 /* Describe a just-created or just-renamed destination file. */
83 /* Initial size of the above hash table. */
84 #define DEST_INFO_INITIAL_CAPACITY 61
86 static bool copy_internal (char const *src_name, char const *dst_name,
87 bool new_dst, dev_t device,
88 struct dir_list *ancestors,
89 const struct cp_options *x,
90 bool command_line_arg,
92 bool *rename_succeeded);
94 /* Pointers to the file names: they're used in the diagnostic that is issued
95 when we detect the user is trying to copy a directory into itself. */
96 static char const *top_level_src_name;
97 static char const *top_level_dst_name;
99 /* The invocation name of this program. */
100 extern char *program_name;
102 /* FIXME: describe */
103 /* FIXME: rewrite this to use a hash table so we avoid the quadratic
104 performance hit that's probably noticeable only on trees deeper
105 than a few hundred levels. See use of active_dir_map in remove.c */
108 is_ancestor (const struct stat *sb, const struct dir_list *ancestors)
110 while (ancestors != 0)
112 if (ancestors->ino == sb->st_ino && ancestors->dev == sb->st_dev)
114 ancestors = ancestors->parent;
119 /* Read the contents of the directory SRC_NAME_IN, and recursively
120 copy the contents to DST_NAME_IN. NEW_DST is true if
121 DST_NAME_IN is a directory that was created previously in the
122 recursion. SRC_SB and ANCESTORS describe SRC_NAME_IN.
123 Set *COPY_INTO_SELF if SRC_NAME_IN is a parent of
124 (or the same as) DST_NAME_IN; otherwise, clear it.
125 Return true if successful. */
128 copy_dir (char const *src_name_in, char const *dst_name_in, bool new_dst,
129 const struct stat *src_sb, struct dir_list *ancestors,
130 const struct cp_options *x, bool *copy_into_self)
134 struct cp_options non_command_line_options = *x;
137 name_space = savedir (src_name_in);
138 if (name_space == NULL)
140 /* This diagnostic is a bit vague because savedir can fail in
141 several different ways. */
142 error (0, errno, _("cannot access %s"), quote (src_name_in));
146 /* For cp's -H option, dereference command line arguments, but do not
147 dereference symlinks that are found via recursive traversal. */
148 if (x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
149 non_command_line_options.dereference = DEREF_NEVER;
152 while (*namep != '\0')
154 bool local_copy_into_self;
155 char *src_name = file_name_concat (src_name_in, namep, NULL);
156 char *dst_name = file_name_concat (dst_name_in, namep, NULL);
158 ok &= copy_internal (src_name, dst_name, new_dst, src_sb->st_dev,
159 ancestors, &non_command_line_options, false,
160 &local_copy_into_self, NULL);
161 *copy_into_self |= local_copy_into_self;
166 namep += strlen (namep) + 1;
172 /* Set the owner and owning group of DEST_DESC to the st_uid and
173 st_gid fields of SRC_SB. If DEST_DESC is undefined (-1), set
174 the owner and owning group of DST_NAME instead. DEST_DESC must
175 refer to the same file as DEST_NAME if defined.
176 Return 1 if the syscall succeeds, 0 if it fails but it's OK
177 not to preserve ownership, -1 otherwise. */
180 set_owner (const struct cp_options *x, char const *dst_name, int dest_desc,
181 uid_t uid, gid_t gid)
183 if (HAVE_FCHOWN && dest_desc != -1)
185 if (fchown (dest_desc, uid, gid) == 0)
190 if (chown (dst_name, uid, gid) == 0)
194 if (! chown_failure_ok (x))
196 error (0, errno, _("failed to preserve ownership for %s"),
198 if (x->require_preserve)
205 /* Set the st_author field of DEST_DESC to the st_author field of
206 SRC_SB. If DEST_DESC is undefined (-1), set the st_author field
207 of DST_NAME instead. DEST_DESC must refer to the same file as
208 DEST_NAME if defined. */
211 set_author (const char *dst_name, int dest_desc, const struct stat *src_sb)
213 #if HAVE_STRUCT_STAT_ST_AUTHOR
214 /* Preserve the st_author field. */
215 file_t file = (dest_desc < 0
216 ? file_name_lookup (dst_name, 0, 0)
217 : getdport (dest_desc));
218 if (file == MACH_PORT_NULL)
219 error (0, errno, _("failed to lookup file %s"), quote (dst_name));
222 error_t err = file_chauthor (file, src_sb->st_author);
224 error (0, err, _("failed to preserve authorship for %s"),
226 mach_port_deallocate (mach_task_self (), file);
231 /* Change the file mode bits of the file identified by DESC or NAME to MODE.
232 Use DESC if DESC is valid and fchmod is available, NAME otherwise. */
235 fchmod_or_lchmod (int desc, char const *name, mode_t mode)
239 return fchmod (desc, mode);
241 return lchmod (name, mode);
244 /* Copy a regular file from SRC_NAME to DST_NAME.
245 If the source file contains holes, copies holes and blocks of zeros
246 in the source file as holes in the destination file.
247 (Holes are read as zeroes by the `read' system call.)
248 When creating the destination, use DST_MODE & ~OMITTED_PERMISSIONS
249 as the third argument in the call to open, adding
250 OMITTED_PERMISSIONS after copying as needed.
251 X provides many option settings.
252 Return true if successful.
253 *NEW_DST is as in copy_internal.
254 SRC_SB is the result of calling XSTAT (aka stat) on SRC_NAME. */
257 copy_reg (char const *src_name, char const *dst_name,
258 const struct cp_options *x,
259 mode_t dst_mode, mode_t omitted_permissions, bool *new_dst,
260 struct stat const *src_sb)
263 char *buf_alloc = NULL;
266 mode_t src_mode = src_sb->st_mode;
268 struct stat src_open_sb;
269 bool return_val = true;
271 source_desc = open (src_name, O_RDONLY | O_BINARY);
274 error (0, errno, _("cannot open %s for reading"), quote (src_name));
278 if (fstat (source_desc, &src_open_sb) != 0)
280 error (0, errno, _("cannot fstat %s"), quote (src_name));
285 /* Compare the source dev/ino from the open file to the incoming,
286 saved ones obtained via a previous call to stat. */
287 if (! SAME_INODE (*src_sb, src_open_sb))
290 _("skipping file %s, as it was replaced while being copied"),
296 /* The semantics of the following open calls are mandated
297 by the specs for both cp and mv. */
300 dest_desc = open (dst_name, O_WRONLY | O_TRUNC | O_BINARY);
302 /* When using cp --preserve=context to copy to an existing destination,
303 use the default context rather than that of the source. Why?
304 1) the src context may prohibit writing, and
305 2) because it's more consistent to use the same context
306 that is used when the destination file doesn't already exist. */
307 if (x->preserve_security_context && 0 <= dest_desc)
309 security_context_t con = NULL;
310 if (getfscreatecon (&con) < 0)
312 error (0, errno, _("failed to get file system create context"));
313 if (x->require_preserve_context)
322 if (fsetfilecon (dest_desc, con) < 0)
325 _("failed to set the security context of %s to %s"),
326 quote_n (0, dst_name), quote_n (1, con));
327 if (x->require_preserve_context)
338 if (dest_desc < 0 && x->unlink_dest_after_failed_open)
340 if (unlink (dst_name) != 0)
342 error (0, errno, _("cannot remove %s"), quote (dst_name));
347 printf (_("removed %s\n"), quote (dst_name));
349 /* Tell caller that the destination file was unlinked. */
355 dest_desc = open (dst_name, O_WRONLY | O_CREAT | O_EXCL | O_BINARY,
356 dst_mode & ~omitted_permissions);
358 omitted_permissions = 0;
362 error (0, errno, _("cannot create regular file %s"), quote (dst_name));
367 if (fstat (dest_desc, &sb) != 0)
369 error (0, errno, _("cannot fstat %s"), quote (dst_name));
371 goto close_src_and_dst_desc;
374 if (! (S_ISREG (src_open_sb.st_mode) && src_open_sb.st_size == 0))
376 typedef uintptr_t word;
377 off_t n_read_total = 0;
379 /* Choose a suitable buffer size; it may be adjusted later. */
380 size_t buf_alignment = lcm (getpagesize (), sizeof (word));
381 size_t buf_alignment_slop = sizeof (word) + buf_alignment - 1;
382 size_t buf_size = ST_BLKSIZE (sb);
384 /* Deal with sparse files. */
385 bool last_write_made_hole = false;
386 bool make_holes = false;
388 if (S_ISREG (sb.st_mode))
390 /* Even with --sparse=always, try to create holes only
391 if the destination is a regular file. */
392 if (x->sparse_mode == SPARSE_ALWAYS)
395 #if HAVE_STRUCT_STAT_ST_BLOCKS
396 /* Use a heuristic to determine whether SRC_NAME contains any sparse
397 blocks. If the file has fewer blocks than would normally be
398 needed for a file of its size, then at least one of the blocks in
399 the file is a hole. */
400 if (x->sparse_mode == SPARSE_AUTO && S_ISREG (src_open_sb.st_mode)
401 && ST_NBLOCKS (src_open_sb) < src_open_sb.st_size / ST_NBLOCKSIZE)
406 /* If not making a sparse file, try to use a more-efficient
410 /* These days there's no point ever messing with buffers smaller
411 than 8 KiB. It would be nice to configure SMALL_BUF_SIZE
412 dynamically for this host and pair of files, but there doesn't
413 seem to be a good way to get readahead info portably. */
414 enum { SMALL_BUF_SIZE = 8 * 1024 };
416 /* Compute the least common multiple of the input and output
417 buffer sizes, adjusting for outlandish values. */
418 size_t blcm_max = MIN (SIZE_MAX, SSIZE_MAX) - buf_alignment_slop;
419 size_t blcm = buffer_lcm (ST_BLKSIZE (src_open_sb), buf_size,
422 /* Do not use a block size that is too small. */
423 buf_size = MAX (SMALL_BUF_SIZE, blcm);
425 /* Do not bother with a buffer larger than the input file, plus one
426 byte to make sure the file has not grown while reading it. */
427 if (S_ISREG (src_open_sb.st_mode) && src_open_sb.st_size < buf_size)
428 buf_size = src_open_sb.st_size + 1;
430 /* However, stick with a block size that is a positive multiple of
431 blcm, overriding the above adjustments. Watch out for
433 buf_size += blcm - 1;
434 buf_size -= buf_size % blcm;
435 if (buf_size == 0 || blcm_max < buf_size)
439 /* Make a buffer with space for a sentinel at the end. */
440 buf_alloc = xmalloc (buf_size + buf_alignment_slop);
441 buf = ptr_align (buf_alloc, buf_alignment);
447 ssize_t n_read = read (source_desc, buf, buf_size);
454 error (0, errno, _("reading %s"), quote (src_name));
456 goto close_src_and_dst_desc;
461 n_read_total += n_read;
467 /* Sentinel to stop loop. */
470 /* Usually, buf[n_read] is not the byte just before a "word"
471 (aka uintptr_t) boundary. In that case, the word-oriented
472 test below (*wp++ == 0) would read some uninitialized bytes
473 after the sentinel. To avoid false-positive reports about
474 this condition (e.g., from a tool like valgrind), set the
475 remaining bytes -- to any value. */
476 memset (buf + n_read + 1, 0, sizeof (word) - 1);
479 /* Find first nonzero *word*, or the word with the sentinel. */
485 /* Find the first nonzero *byte*, or the sentinel. */
487 cp = (char *) (wp - 1);
491 if (cp <= buf + n_read)
492 /* Clear to indicate that a normal write is needed. */
496 /* We found the sentinel, so the whole input block was zero.
498 if (lseek (dest_desc, n_read, SEEK_CUR) < 0)
500 error (0, errno, _("cannot lseek %s"), quote (dst_name));
502 goto close_src_and_dst_desc;
504 last_write_made_hole = true;
511 if (full_write (dest_desc, buf, n) != n)
513 error (0, errno, _("writing %s"), quote (dst_name));
515 goto close_src_and_dst_desc;
517 last_write_made_hole = false;
519 /* A short read on a regular file means EOF. */
520 if (n_read != buf_size && S_ISREG (src_open_sb.st_mode))
525 /* If the file ends with a `hole', we need to do something to record
526 the length of the file. On modern systems, calling ftruncate does
527 the job. On systems without native ftruncate support, we have to
528 write a byte at the ending position. Otherwise the kernel would
529 truncate the file at the end of the last write operation. */
531 if (last_write_made_hole)
534 ? /* ftruncate sets the file size,
535 so there is no need for a write. */
536 ftruncate (dest_desc, n_read_total) < 0
537 : /* Seek backwards one character and write a null. */
538 (lseek (dest_desc, (off_t) -1, SEEK_CUR) < 0L
539 || full_write (dest_desc, "", 1) != 1))
541 error (0, errno, _("writing %s"), quote (dst_name));
543 goto close_src_and_dst_desc;
548 if (x->preserve_timestamps)
550 struct timespec timespec[2];
551 timespec[0] = get_stat_atime (src_sb);
552 timespec[1] = get_stat_mtime (src_sb);
554 if (futimens (dest_desc, dst_name, timespec) != 0)
556 error (0, errno, _("preserving times for %s"), quote (dst_name));
557 if (x->require_preserve)
560 goto close_src_and_dst_desc;
565 if (x->preserve_ownership && ! SAME_OWNER_AND_GROUP (*src_sb, sb))
567 switch (set_owner (x, dst_name, dest_desc,
568 src_sb->st_uid, src_sb->st_gid))
572 goto close_src_and_dst_desc;
575 src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX);
580 set_author (dst_name, dest_desc, src_sb);
582 if (x->preserve_mode || x->move_mode)
584 if (copy_acl (src_name, source_desc, dst_name, dest_desc, src_mode) != 0
585 && x->require_preserve)
588 else if (x->set_mode)
590 if (set_acl (dst_name, dest_desc, x->mode) != 0)
593 else if (omitted_permissions)
595 omitted_permissions &= ~ cached_umask ();
596 if (omitted_permissions
597 && fchmod_or_lchmod (dest_desc, dst_name, dst_mode) != 0)
599 error (0, errno, _("preserving permissions for %s"),
601 if (x->require_preserve)
606 close_src_and_dst_desc:
607 if (close (dest_desc) < 0)
609 error (0, errno, _("closing %s"), quote (dst_name));
613 if (close (source_desc) < 0)
615 error (0, errno, _("closing %s"), quote (src_name));
623 /* Return true if it's ok that the source and destination
624 files are the `same' by some measure. The goal is to avoid
625 making the `copy' operation remove both copies of the file
626 in that case, while still allowing the user to e.g., move or
627 copy a regular file onto a symlink that points to it.
628 Try to minimize the cost of this function in the common case.
629 Set *RETURN_NOW if we've determined that the caller has no more
630 work to do and should return successfully, right away.
632 Set *UNLINK_SRC if we've determined that the caller wants to do
633 `rename (a, b)' where `a' and `b' are distinct hard links to the same
634 file. In that case, the caller should try to unlink `a' and then return
635 successfully. Ideally, we wouldn't have to do that, and we'd be
636 able to rely on rename to remove the source file. However, POSIX
637 mistakenly requires that such a rename call do *nothing* and return
641 same_file_ok (char const *src_name, struct stat const *src_sb,
642 char const *dst_name, struct stat const *dst_sb,
643 const struct cp_options *x, bool *return_now, bool *unlink_src)
645 const struct stat *src_sb_link;
646 const struct stat *dst_sb_link;
647 struct stat tmp_dst_sb;
648 struct stat tmp_src_sb;
651 bool same = SAME_INODE (*src_sb, *dst_sb);
656 /* FIXME: this should (at the very least) be moved into the following
657 if-block. More likely, it should be removed, because it inhibits
658 making backups. But removing it will result in a change in behavior
659 that will probably have to be documented -- and tests will have to
661 if (same && x->hard_link)
667 if (x->dereference == DEREF_NEVER)
671 /* If both the source and destination files are symlinks (and we'll
672 know this here IFF preserving symlinks), then it's ok -- as long
673 as they are distinct. */
674 if (S_ISLNK (src_sb->st_mode) && S_ISLNK (dst_sb->st_mode))
675 return ! same_name (src_name, dst_name);
677 src_sb_link = src_sb;
678 dst_sb_link = dst_sb;
685 if (lstat (dst_name, &tmp_dst_sb) != 0
686 || lstat (src_name, &tmp_src_sb) != 0)
689 src_sb_link = &tmp_src_sb;
690 dst_sb_link = &tmp_dst_sb;
692 same_link = SAME_INODE (*src_sb_link, *dst_sb_link);
694 /* If both are symlinks, then it's ok, but only if the destination
695 will be unlinked before being opened. This is like the test
696 above, but with the addition of the unlink_dest_before_opening
697 conjunct because otherwise, with two symlinks to the same target,
698 we'd end up truncating the source file. */
699 if (S_ISLNK (src_sb_link->st_mode) && S_ISLNK (dst_sb_link->st_mode)
700 && x->unlink_dest_before_opening)
704 /* The backup code ensures there's a copy, so it's usually ok to
705 remove any destination file. One exception is when both
706 source and destination are the same directory entry. In that
707 case, moving the destination file aside (in making the backup)
708 would also rename the source file and result in an error. */
709 if (x->backup_type != no_backups)
713 /* In copy mode when dereferencing symlinks, if the source is a
714 symlink and the dest is not, then backing up the destination
715 (moving it aside) would make it a dangling symlink, and the
716 subsequent attempt to open it in copy_reg would fail with
717 a misleading diagnostic. Avoid that by returning zero in
718 that case so the caller can make cp (or mv when it has to
719 resort to reading the source file) fail now. */
721 /* FIXME-note: even with the following kludge, we can still provoke
722 the offending diagnostic. It's just a little harder to do :-)
723 $ rm -f a b c; touch c; ln -s c b; ln -s b a; cp -b a b
724 cp: cannot open `a' for reading: No such file or directory
725 That's misleading, since a subsequent `ls' shows that `a'
727 One solution would be to open the source file *before* moving
728 aside the destination, but that'd involve a big rewrite. */
730 && x->dereference != DEREF_NEVER
731 && S_ISLNK (src_sb_link->st_mode)
732 && ! S_ISLNK (dst_sb_link->st_mode))
738 return ! same_name (src_name, dst_name);
742 /* FIXME: use or remove */
744 /* If we're making a backup, we'll detect the problem case in
745 copy_reg because SRC_NAME will no longer exist. Allowing
746 the test to be deferred lets cp do some useful things.
747 But when creating hardlinks and SRC_NAME is a symlink
748 but DST_NAME is not we must test anyway. */
750 || !S_ISLNK (src_sb_link->st_mode)
751 || S_ISLNK (dst_sb_link->st_mode))
754 if (x->dereference != DEREF_NEVER)
758 /* They may refer to the same file if we're in move mode and the
759 target is a symlink. That is ok, since we remove any existing
760 destination file before opening it -- via `rename' if they're on
761 the same file system, via `unlink (DST_NAME)' otherwise.
762 It's also ok if they're distinct hard links to the same file. */
763 if (x->move_mode || x->unlink_dest_before_opening)
765 if (S_ISLNK (dst_sb_link->st_mode))
769 && 1 < dst_sb_link->st_nlink
770 && ! same_name (src_name, dst_name))
781 /* If neither is a symlink, then it's ok as long as they aren't
782 hard links to the same file. */
783 if (!S_ISLNK (src_sb_link->st_mode) && !S_ISLNK (dst_sb_link->st_mode))
785 if (!SAME_INODE (*src_sb_link, *dst_sb_link))
788 /* If they are the same file, it's ok if we're making hard links. */
796 /* It's ok to remove a destination symlink. But that works only when we
797 unlink before opening the destination and when the source and destination
798 files are on the same partition. */
799 if (x->unlink_dest_before_opening
800 && S_ISLNK (dst_sb_link->st_mode))
801 return dst_sb_link->st_dev == src_sb_link->st_dev;
803 if (x->dereference == DEREF_NEVER)
805 if ( ! S_ISLNK (src_sb_link->st_mode))
806 tmp_src_sb = *src_sb_link;
807 else if (stat (src_name, &tmp_src_sb) != 0)
810 if ( ! S_ISLNK (dst_sb_link->st_mode))
811 tmp_dst_sb = *dst_sb_link;
812 else if (stat (dst_name, &tmp_dst_sb) != 0)
815 if ( ! SAME_INODE (tmp_src_sb, tmp_dst_sb))
818 /* FIXME: shouldn't this be testing whether we're making symlinks? */
829 /* Return true if FILE, with mode MODE, is writable in the sense of 'mv'.
830 Always consider a symbolic link to be writable. */
832 writable_destination (char const *file, mode_t mode)
834 return (S_ISLNK (mode)
835 || can_write_any_file ()
836 || euidaccess (file, W_OK) == 0);
840 overwrite_prompt (char const *dst_name, struct stat const *dst_sb)
842 if (! writable_destination (dst_name, dst_sb->st_mode))
844 char perms[12]; /* "-rwxrwxrwx " ls-style modes. */
845 strmode (dst_sb->st_mode, perms);
848 _("%s: try to overwrite %s, overriding mode %04lo (%s)? "),
849 program_name, quote (dst_name),
850 (unsigned long int) (dst_sb->st_mode & CHMOD_MODE_BITS),
855 fprintf (stderr, _("%s: overwrite %s? "),
856 program_name, quote (dst_name));
860 /* Hash an F_triple. */
862 triple_hash (void const *x, size_t table_size)
864 struct F_triple const *p = x;
866 /* Also take the name into account, so that when moving N hard links to the
867 same file (all listed on the command line) all into the same directory,
868 we don't experience any N^2 behavior. */
869 /* FIXME-maybe: is it worth the overhead of doing this
870 just to avoid N^2 in such an unusual case? N would have
871 to be very large to make the N^2 factor noticable, and
872 one would probably encounter a limit on the length of
873 a command line before it became a problem. */
874 size_t tmp = hash_pjw (p->name, table_size);
876 /* Ignoring the device number here should be fine. */
877 return (tmp | p->st_ino) % table_size;
880 /* Hash an F_triple. */
882 triple_hash_no_name (void const *x, size_t table_size)
884 struct F_triple const *p = x;
886 /* Ignoring the device number here should be fine. */
887 return p->st_ino % table_size;
890 /* Compare two F_triple structs. */
892 triple_compare (void const *x, void const *y)
894 struct F_triple const *a = x;
895 struct F_triple const *b = y;
896 return (SAME_INODE (*a, *b) && same_name (a->name, b->name)) ? true : false;
899 /* Free an F_triple. */
901 triple_free (void *x)
903 struct F_triple *a = x;
908 /* Initialize the hash table implementing a set of F_triple entries
909 corresponding to destination files. */
911 dest_info_init (struct cp_options *x)
914 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
921 /* Initialize the hash table implementing a set of F_triple entries
922 corresponding to source files listed on the command line. */
924 src_info_init (struct cp_options *x)
927 /* Note that we use triple_hash_no_name here.
928 Contrast with the use of triple_hash above.
929 That is necessary because a source file may be specified
930 in many different ways. We want to warn about this
936 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
943 /* Return true if there is an entry in hash table, HT,
944 for the file described by FILE and STATS. */
946 seen_file (Hash_table const *ht, char const *file,
947 struct stat const *stats)
949 struct F_triple new_ent;
954 new_ent.name = (char *) file;
955 new_ent.st_ino = stats->st_ino;
956 new_ent.st_dev = stats->st_dev;
958 return !!hash_lookup (ht, &new_ent);
961 /* Record destination file, FILE, and dev/ino from *STATS,
962 in the hash table, HT. If HT is NULL, return immediately.
963 If STATS is NULL, call lstat on FILE to get the device
964 and inode numbers. If that lstat fails, simply return.
965 If memory allocation fails, exit immediately. */
967 record_file (Hash_table *ht, char const *file,
968 struct stat const *stats)
970 struct F_triple *ent;
975 ent = xmalloc (sizeof *ent);
976 ent->name = xstrdup (file);
979 ent->st_ino = stats->st_ino;
980 ent->st_dev = stats->st_dev;
985 if (lstat (file, &sb) != 0)
987 ent->st_ino = sb.st_ino;
988 ent->st_dev = sb.st_dev;
992 struct F_triple *ent_from_table = hash_insert (ht, ent);
993 if (ent_from_table == NULL)
995 /* Insertion failed due to lack of memory. */
999 if (ent_from_table != ent)
1001 /* There was alread a matching entry in the table, so ENT was
1002 not inserted. Free it. */
1008 /* When effecting a move (e.g., for mv(1)), and given the name DST_NAME
1009 of the destination and a corresponding stat buffer, DST_SB, return
1010 true if the logical `move' operation should _not_ proceed.
1011 Otherwise, return false.
1012 Depending on options specified in X, this code may issue an
1013 interactive prompt asking whether it's ok to overwrite DST_NAME. */
1015 abandon_move (const struct cp_options *x,
1016 char const *dst_name,
1017 struct stat const *dst_sb)
1019 assert (x->move_mode);
1020 return (x->interactive == I_ALWAYS_NO
1021 || ((x->interactive == I_ASK_USER
1022 || (x->interactive == I_UNSPECIFIED
1024 && ! writable_destination (dst_name, dst_sb->st_mode)))
1025 && (overwrite_prompt (dst_name, dst_sb), 1)
1029 /* Print --verbose output on standard output, e.g. `new' -> `old'.
1030 If BACKUP_DST_NAME is non-NULL, then also indicate that it is
1031 the name of a backup file. */
1033 emit_verbose (char const *src, char const *dst, char const *backup_dst_name)
1035 printf ("%s -> %s", quote_n (0, src), quote_n (1, dst));
1036 if (backup_dst_name)
1037 printf (_(" (backup: %s)"), quote (backup_dst_name));
1041 /* A wrapper around "setfscreatecon (NULL)" that exits upon failure. */
1043 restore_default_fscreatecon_or_die (void)
1045 if (setfscreatecon (NULL) != 0)
1046 error (EXIT_FAILURE, errno,
1047 _("failed to restore the default file creation context"));
1050 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
1051 any type. NEW_DST should be true if the file DST_NAME cannot
1052 exist because its parent directory was just created; NEW_DST should
1053 be false if DST_NAME might already exist. DEVICE is the device
1054 number of the parent directory, or 0 if the parent of this file is
1055 not known. ANCESTORS points to a linked, null terminated list of
1056 devices and inodes of parent directories of SRC_NAME. COMMAND_LINE_ARG
1057 is true iff SRC_NAME was specified on the command line.
1058 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
1059 same as) DST_NAME; otherwise, clear it.
1060 Return true if successful. */
1062 copy_internal (char const *src_name, char const *dst_name,
1065 struct dir_list *ancestors,
1066 const struct cp_options *x,
1067 bool command_line_arg,
1068 bool *copy_into_self,
1069 bool *rename_succeeded)
1074 mode_t dst_mode IF_LINT (= 0);
1075 mode_t dst_mode_bits;
1076 mode_t omitted_permissions;
1077 bool restore_dst_mode = false;
1078 char *earlier_file = NULL;
1079 char *dst_backup = NULL;
1080 bool backup_succeeded = false;
1082 bool copied_as_regular = false;
1083 bool preserve_metadata;
1085 if (x->move_mode && rename_succeeded)
1086 *rename_succeeded = false;
1088 *copy_into_self = false;
1090 if (XSTAT (x, src_name, &src_sb) != 0)
1092 error (0, errno, _("cannot stat %s"), quote (src_name));
1096 src_mode = src_sb.st_mode;
1098 if (S_ISDIR (src_mode) && !x->recursive)
1100 error (0, 0, _("omitting directory %s"), quote (src_name));
1104 /* Detect the case in which the same source file appears more than
1105 once on the command line and no backup option has been selected.
1106 If so, simply warn and don't copy it the second time.
1107 This check is enabled only if x->src_info is non-NULL. */
1108 if (command_line_arg)
1110 if ( ! S_ISDIR (src_sb.st_mode)
1111 && x->backup_type == no_backups
1112 && seen_file (x->src_info, src_name, &src_sb))
1114 error (0, 0, _("warning: source file %s specified more than once"),
1119 record_file (x->src_info, src_name, &src_sb);
1124 if (XSTAT (x, dst_name, &dst_sb) != 0)
1126 if (errno != ENOENT)
1128 error (0, errno, _("cannot stat %s"), quote (dst_name));
1137 { /* Here, we know that dst_name exists, at least to the point
1138 that it is XSTAT'able. */
1142 if (! same_file_ok (src_name, &src_sb, dst_name, &dst_sb,
1143 x, &return_now, &unlink_src))
1145 error (0, 0, _("%s and %s are the same file"),
1146 quote_n (0, src_name), quote_n (1, dst_name));
1150 /* When there is an existing destination file, we may end up
1151 returning early, and hence not copying/moving the file.
1152 This may be due to an interactive `negative' reply to the
1153 prompt about the existing file. It may also be due to the
1154 use of the --reply=no option.
1156 cp and mv treat -i and -f differently. */
1159 if (abandon_move (x, dst_name, &dst_sb)
1160 || (unlink_src && unlink (src_name) == 0))
1162 /* Pretend the rename succeeded, so the caller (mv)
1163 doesn't end up removing the source file. */
1164 if (rename_succeeded)
1165 *rename_succeeded = true;
1166 if (unlink_src && x->verbose)
1167 printf (_("removed %s\n"), quote (src_name));
1172 error (0, errno, _("cannot remove %s"), quote (src_name));
1178 if (! S_ISDIR (src_mode)
1179 && (x->interactive == I_ALWAYS_NO
1180 || (x->interactive == I_ASK_USER
1181 && (overwrite_prompt (dst_name, &dst_sb), 1)
1189 if (!S_ISDIR (dst_sb.st_mode))
1191 if (S_ISDIR (src_mode))
1193 if (x->move_mode && x->backup_type != no_backups)
1195 /* Moving a directory onto an existing
1196 non-directory is ok only with --backup. */
1201 _("cannot overwrite non-directory %s with directory %s"),
1202 quote_n (0, dst_name), quote_n (1, src_name));
1207 /* Don't let the user destroy their data, even if they try hard:
1208 This mv command must fail (likewise for cp):
1209 rm -rf a b c; mkdir a b c; touch a/f b/f; mv a/f b/f c
1210 Otherwise, the contents of b/f would be lost.
1211 In the case of `cp', b/f would be lost if the user simulated
1212 a move using cp and rm.
1213 Note that it works fine if you use --backup=numbered. */
1214 if (command_line_arg
1215 && x->backup_type != numbered_backups
1216 && seen_file (x->dest_info, dst_name, &dst_sb))
1219 _("will not overwrite just-created %s with %s"),
1220 quote_n (0, dst_name), quote_n (1, src_name));
1225 if (!S_ISDIR (src_mode))
1227 if (S_ISDIR (dst_sb.st_mode))
1229 if (x->move_mode && x->backup_type != no_backups)
1231 /* Moving a non-directory onto an existing
1232 directory is ok only with --backup. */
1237 _("cannot overwrite directory %s with non-directory"),
1245 /* When preserving time stamps (but not moving within a file
1246 system), don't worry if the destination time stamp is
1247 less than the source merely because of time stamp
1249 int options = ((x->preserve_timestamps
1251 && dst_sb.st_dev == src_sb.st_dev))
1252 ? UTIMECMP_TRUNCATE_SOURCE
1255 if (0 <= utimecmp (dst_name, &dst_sb, &src_sb, options))
1257 /* We're using --update and the destination is not older
1258 than the source, so do not copy or move. Pretend the
1259 rename succeeded, so the caller (if it's mv) doesn't
1260 end up removing the source file. */
1261 if (rename_succeeded)
1262 *rename_succeeded = true;
1270 /* Don't allow user to move a directory onto a non-directory. */
1271 if (S_ISDIR (src_sb.st_mode) && !S_ISDIR (dst_sb.st_mode)
1272 && x->backup_type == no_backups)
1275 _("cannot move directory onto non-directory: %s -> %s"),
1276 quote_n (0, src_name), quote_n (0, dst_name));
1281 if (x->backup_type != no_backups
1282 /* Don't try to back up a destination if the last
1283 component of src_name is "." or "..". */
1284 && ! dot_or_dotdot (last_component (src_name))
1285 /* Create a backup of each destination directory in move mode,
1286 but not in copy mode. FIXME: it might make sense to add an
1287 option to suppress backup creation also for move mode.
1288 That would let one use mv to merge new content into an
1289 existing hierarchy. */
1290 && (x->move_mode || ! S_ISDIR (dst_sb.st_mode)))
1292 char *tmp_backup = find_backup_file_name (dst_name,
1295 /* Detect (and fail) when creating the backup file would
1296 destroy the source file. Before, running the commands
1297 cd /tmp; rm -f a a~; : > a; echo A > a~; cp --b=simple a~ a
1298 would leave two zero-length files: a and a~. */
1299 /* FIXME: but simply change e.g., the final a~ to `./a~'
1300 and the source will still be destroyed. */
1301 if (STREQ (tmp_backup, src_name))
1305 ? _("backing up %s would destroy source; %s not moved")
1306 : _("backing up %s would destroy source; %s not copied"));
1308 quote_n (0, dst_name),
1309 quote_n (1, src_name));
1315 Using alloca for a file name that may be arbitrarily
1316 long is not recommended. In fact, even forming such a name
1317 should be discouraged. Eventually, this code will be rewritten
1318 to use fts, so using alloca here will be less of a problem. */
1319 ASSIGN_STRDUPA (dst_backup, tmp_backup);
1321 if (rename (dst_name, dst_backup) != 0)
1323 if (errno != ENOENT)
1325 error (0, errno, _("cannot backup %s"), quote (dst_name));
1335 backup_succeeded = true;
1339 else if (! S_ISDIR (dst_sb.st_mode)
1340 && (x->unlink_dest_before_opening
1341 || (x->preserve_links && 1 < dst_sb.st_nlink)
1343 && x->dereference == DEREF_NEVER
1344 && S_ISLNK (src_sb.st_mode))
1347 if (unlink (dst_name) != 0 && errno != ENOENT)
1349 error (0, errno, _("cannot remove %s"), quote (dst_name));
1354 printf (_("removed %s\n"), quote (dst_name));
1359 /* If the source is a directory, we don't always create the destination
1360 directory. So --verbose should not announce anything until we're
1361 sure we'll create a directory. */
1362 if (x->verbose && !S_ISDIR (src_mode))
1363 emit_verbose (src_name, dst_name, backup_succeeded ? dst_backup : NULL);
1365 /* Associate the destination file name with the source device and inode
1366 so that if we encounter a matching dev/ino pair in the source tree
1367 we can arrange to create a hard link between the corresponding names
1368 in the destination tree.
1370 Sometimes, when preserving links, we have to record dev/ino even
1371 though st_nlink == 1:
1372 - when in move_mode, since we may be moving a group of N hard-linked
1373 files (via two or more command line arguments) to a different
1374 partition; the links may be distributed among the command line
1375 arguments (possibly hierarchies) so that the link count of
1376 the final, once-linked source file is reduced to 1 when it is
1377 considered below. But in this case (for mv) we don't need to
1378 incur the expense of recording the dev/ino => name mapping; all we
1379 really need is a lookup, to see if the dev/ino pair has already
1381 - when using -H and processing a command line argument;
1382 that command line argument could be a symlink pointing to another
1383 command line argument. With `cp -H --preserve=link', we hard-link
1384 those two destination files.
1385 - likewise for -L except that it applies to all files, not just
1386 command line arguments.
1388 Also record directory dev/ino when using --recursive. We'll use that
1389 info to detect this problem: cp -R dir dir. FIXME-maybe: ideally,
1390 directory info would be recorded in a separate hash table, since
1391 such entries are useful only while a single command line hierarchy
1392 is being copied -- so that separate table could be cleared between
1393 command line args. Using the same hash table to preserve hard
1394 links means that it may not be cleared. */
1396 if (x->move_mode && src_sb.st_nlink == 1)
1398 earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev);
1400 else if ((x->preserve_links
1401 && (1 < src_sb.st_nlink
1402 || (command_line_arg
1403 && x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
1404 || x->dereference == DEREF_ALWAYS))
1405 || (x->recursive && S_ISDIR (src_mode)))
1407 earlier_file = remember_copied (dst_name, src_sb.st_ino, src_sb.st_dev);
1410 /* Did we copy this inode somewhere else (in this command line argument)
1411 and therefore this is a second hard link to the inode? */
1415 /* Avoid damaging the destination file system by refusing to preserve
1416 hard-linked directories (which are found at least in Netapp snapshot
1418 if (S_ISDIR (src_mode))
1420 /* If src_name and earlier_file refer to the same directory entry,
1421 then warn about copying a directory into itself. */
1422 if (same_name (src_name, earlier_file))
1424 error (0, 0, _("cannot copy a directory, %s, into itself, %s"),
1425 quote_n (0, top_level_src_name),
1426 quote_n (1, top_level_dst_name));
1427 *copy_into_self = true;
1430 else if (x->dereference == DEREF_ALWAYS)
1432 /* This happens when e.g., encountering a directory for the
1433 second or subsequent time via symlinks when cp is invoked
1434 with -R and -L. E.g.,
1435 rm -rf a b c d; mkdir a b c d; ln -s ../c a; ln -s ../c b;
1441 error (0, 0, _("will not create hard link %s to directory %s"),
1442 quote_n (0, dst_name), quote_n (1, earlier_file));
1448 bool link_failed = (link (earlier_file, dst_name) != 0);
1450 /* If the link failed because of an existing destination,
1451 remove that file and then call link again. */
1452 if (link_failed && errno == EEXIST)
1454 if (unlink (dst_name) != 0)
1456 error (0, errno, _("cannot remove %s"), quote (dst_name));
1460 printf (_("removed %s\n"), quote (dst_name));
1461 link_failed = (link (earlier_file, dst_name) != 0);
1466 error (0, errno, _("cannot create hard link %s to %s"),
1467 quote_n (0, dst_name), quote_n (1, earlier_file));
1477 if (rename (src_name, dst_name) == 0)
1479 if (x->verbose && S_ISDIR (src_mode))
1480 emit_verbose (src_name, dst_name,
1481 backup_succeeded ? dst_backup : NULL);
1483 if (rename_succeeded)
1484 *rename_succeeded = true;
1486 if (command_line_arg)
1488 /* Record destination dev/ino/name, so that if we are asked
1489 to overwrite that file again, we can detect it and fail. */
1490 /* It's fine to use the _source_ stat buffer (src_sb) to get the
1491 _destination_ dev/ino, since the rename above can't have
1492 changed those, and `mv' always uses lstat.
1493 We could limit it further by operating
1494 only on non-directories. */
1495 record_file (x->dest_info, dst_name, &src_sb);
1501 /* FIXME: someday, consider what to do when moving a directory into
1502 itself but when source and destination are on different devices. */
1504 /* This happens when attempting to rename a directory to a
1505 subdirectory of itself. */
1506 if (errno == EINVAL)
1508 /* FIXME: this is a little fragile in that it relies on rename(2)
1509 failing with a specific errno value. Expect problems on
1510 non-POSIX systems. */
1511 error (0, 0, _("cannot move %s to a subdirectory of itself, %s"),
1512 quote_n (0, top_level_src_name),
1513 quote_n (1, top_level_dst_name));
1515 /* Note that there is no need to call forget_created here,
1516 (compare with the other calls in this file) since the
1517 destination directory didn't exist before. */
1519 *copy_into_self = true;
1520 /* FIXME-cleanup: Don't return true here; adjust mv.c accordingly.
1521 The only caller that uses this code (mv.c) ends up setting its
1522 exit status to nonzero when copy_into_self is nonzero. */
1526 /* WARNING: there probably exist systems for which an inter-device
1527 rename fails with a value of errno not handled here.
1528 If/as those are reported, add them to the condition below.
1529 If this happens to you, please do the following and send the output
1530 to the bug-reporting address (e.g., in the output of cp --help):
1531 touch k; perl -e 'rename "k","/tmp/k" or print "$!(",$!+0,")\n"'
1532 where your current directory is on one partion and /tmp is the other.
1533 Also, please try to find the E* errno macro name corresponding to
1534 the diagnostic and parenthesized integer, and include that in your
1535 e-mail. One way to do that is to run a command like this
1536 find /usr/include/. -type f \
1537 | xargs grep 'define.*\<E[A-Z]*\>.*\<18\>' /dev/null
1538 where you'd replace `18' with the integer in parentheses that
1539 was output from the perl one-liner above.
1540 If necessary, of course, change `/tmp' to some other directory. */
1543 /* There are many ways this can happen due to a race condition.
1544 When something happens between the initial XSTAT and the
1545 subsequent rename, we can get many different types of errors.
1546 For example, if the destination is initially a non-directory
1547 or non-existent, but it is created as a directory, the rename
1548 fails. If two `mv' commands try to rename the same file at
1549 about the same time, one will succeed and the other will fail.
1550 If the permissions on the directory containing the source or
1551 destination file are made too restrictive, the rename will
1554 _("cannot move %s to %s"),
1555 quote_n (0, src_name), quote_n (1, dst_name));
1556 forget_created (src_sb.st_ino, src_sb.st_dev);
1560 /* The rename attempt has failed. Remove any existing destination
1561 file so that a cross-device `mv' acts as if it were really using
1562 the rename syscall. */
1563 if (unlink (dst_name) != 0 && errno != ENOENT)
1566 _("inter-device move failed: %s to %s; unable to remove target"),
1567 quote_n (0, src_name), quote_n (1, dst_name));
1568 forget_created (src_sb.st_ino, src_sb.st_dev);
1575 /* If the ownership might change, or if it is a directory (whose
1576 special mode bits may change after the directory is created),
1577 omit some permissions at first, so unauthorized users cannot nip
1578 in before the file is ready. */
1579 dst_mode_bits = (x->set_mode ? x->mode : src_mode) & CHMOD_MODE_BITS;
1580 omitted_permissions =
1582 & (x->preserve_ownership ? S_IRWXG | S_IRWXO
1583 : S_ISDIR (src_mode) ? S_IWGRP | S_IWOTH
1588 if (x->preserve_security_context)
1590 security_context_t con;
1592 if (0 <= lgetfilecon (src_name, &con))
1594 if (setfscreatecon (con) < 0)
1597 _("failed to set default file creation context to %s"),
1599 if (x->require_preserve_context)
1609 if (errno != ENOTSUP && errno != ENODATA)
1612 _("failed to get security context of %s"),
1614 if (x->require_preserve_context)
1620 /* In certain modes (cp's --symbolic-link), and for certain file types
1621 (symlinks and hard links) it doesn't make sense to preserve metadata,
1622 or it's possible to preserve only some of it.
1623 In such cases, set this variable to zero. */
1624 preserve_metadata = true;
1626 if (S_ISDIR (src_mode))
1628 struct dir_list *dir;
1630 /* If this directory has been copied before during the
1631 recursion, there is a symbolic link to an ancestor
1632 directory of the symbolic link. It is impossible to
1633 continue to copy this, unless we've got an infinite disk. */
1635 if (is_ancestor (&src_sb, ancestors))
1637 error (0, 0, _("cannot copy cyclic symbolic link %s"),
1642 /* Insert the current directory in the list of parents. */
1644 dir = alloca (sizeof *dir);
1645 dir->parent = ancestors;
1646 dir->ino = src_sb.st_ino;
1647 dir->dev = src_sb.st_dev;
1649 if (new_dst || !S_ISDIR (dst_sb.st_mode))
1651 /* POSIX says mkdir's behavior is implementation-defined when
1652 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
1653 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
1654 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
1655 if (mkdir (dst_name, dst_mode_bits & ~omitted_permissions) != 0)
1657 error (0, errno, _("cannot create directory %s"),
1662 /* We need search and write permissions to the new directory
1663 for writing the directory's contents. Check if these
1664 permissions are there. */
1666 if (lstat (dst_name, &dst_sb) != 0)
1668 error (0, errno, _("cannot stat %s"), quote (dst_name));
1671 else if ((dst_sb.st_mode & S_IRWXU) != S_IRWXU)
1673 /* Make the new directory searchable and writable. */
1675 dst_mode = dst_sb.st_mode;
1676 restore_dst_mode = true;
1678 if (lchmod (dst_name, dst_mode | S_IRWXU) != 0)
1680 error (0, errno, _("setting permissions for %s"),
1686 /* Insert the created directory's inode and device
1687 numbers into the search structure, so that we can
1688 avoid copying it again. */
1690 remember_copied (dst_name, dst_sb.st_ino, dst_sb.st_dev);
1693 emit_verbose (src_name, dst_name, NULL);
1696 /* Decide whether to copy the contents of the directory. */
1697 if (x->one_file_system && device != 0 && device != src_sb.st_dev)
1699 /* Here, we are crossing a file system boundary and cp's -x option
1700 is in effect: so don't copy the contents of this directory. */
1704 /* Copy the contents of the directory. Don't just return if
1705 this fails -- otherwise, the failure to read a single file
1706 in a source directory would cause the containing destination
1707 directory not to have owner/perms set properly. */
1708 delayed_ok = copy_dir (src_name, dst_name, new_dst, &src_sb, dir, x,
1712 else if (x->symbolic_link)
1714 preserve_metadata = false;
1716 if (*src_name != '/')
1718 /* Check that DST_NAME denotes a file in the current directory. */
1720 struct stat dst_parent_sb;
1722 bool in_current_dir;
1724 dst_parent = dir_name (dst_name);
1726 in_current_dir = (STREQ (".", dst_parent)
1727 /* If either stat call fails, it's ok not to report
1728 the failure and say dst_name is in the current
1729 directory. Other things will fail later. */
1730 || stat (".", &dot_sb) != 0
1731 || stat (dst_parent, &dst_parent_sb) != 0
1732 || SAME_INODE (dot_sb, dst_parent_sb));
1735 if (! in_current_dir)
1738 _("%s: can make relative symbolic links only in current directory"),
1743 if (symlink (src_name, dst_name) != 0)
1745 error (0, errno, _("cannot create symbolic link %s to %s"),
1746 quote_n (0, dst_name), quote_n (1, src_name));
1751 else if (x->hard_link
1752 #ifdef LINK_FOLLOWS_SYMLINKS
1753 /* A POSIX-conforming link syscall dereferences a symlink, yet cp,
1754 invoked with `--link --no-dereference', should not. Thus, with
1755 a POSIX-conforming link system call, we can't use link() here,
1756 since that would create a hard link to the referent (effectively
1757 dereferencing the symlink), rather than to the symlink itself.
1758 We can approximate the desired behavior by skipping this hard-link
1759 creating block and instead copying the symlink, via the `S_ISLNK'-
1761 When link operates on the symlinks themselves, we use this block
1762 and just call link(). */
1763 && !(S_ISLNK (src_mode) && x->dereference == DEREF_NEVER)
1767 preserve_metadata = false;
1768 if (link (src_name, dst_name))
1770 error (0, errno, _("cannot create link %s"), quote (dst_name));
1774 else if (S_ISREG (src_mode)
1775 || (x->copy_as_regular && !S_ISLNK (src_mode)))
1777 copied_as_regular = true;
1778 /* POSIX says the permission bits of the source file must be
1779 used as the 3rd argument in the open call. Historical
1780 practice passed all the source mode bits to 'open', but the extra
1781 bits were ignored, so it should be the same either way. */
1782 if (! copy_reg (src_name, dst_name, x, src_mode & S_IRWXUGO,
1783 omitted_permissions, &new_dst, &src_sb))
1786 else if (S_ISFIFO (src_mode))
1788 /* Use mknod, rather than mkfifo, because the former preserves
1789 the special mode bits of a fifo on Solaris 10, while mkfifo
1790 does not. But fall back on mkfifo, because on some BSD systems,
1791 mknod always fails when asked to create a FIFO. */
1792 if (mknod (dst_name, src_mode & ~omitted_permissions, 0) != 0)
1794 if (mkfifo (dst_name, src_mode & ~S_IFIFO & ~omitted_permissions) != 0)
1797 error (0, errno, _("cannot create fifo %s"), quote (dst_name));
1801 else if (S_ISBLK (src_mode) || S_ISCHR (src_mode) || S_ISSOCK (src_mode))
1803 if (mknod (dst_name, src_mode & ~omitted_permissions, src_sb.st_rdev)
1806 error (0, errno, _("cannot create special file %s"),
1811 else if (S_ISLNK (src_mode))
1813 char *src_link_val = xreadlink_with_size (src_name, src_sb.st_size);
1814 if (src_link_val == NULL)
1816 error (0, errno, _("cannot read symbolic link %s"), quote (src_name));
1820 if (symlink (src_link_val, dst_name) == 0)
1821 free (src_link_val);
1824 int saved_errno = errno;
1825 bool same_link = false;
1826 if (x->update && !new_dst && S_ISLNK (dst_sb.st_mode)
1827 && dst_sb.st_size == strlen (src_link_val))
1829 /* See if the destination is already the desired symlink.
1830 FIXME: This behavior isn't documented, and seems wrong
1831 in some cases, e.g., if the destination symlink has the
1832 wrong ownership, permissions, or time stamps. */
1833 char *dest_link_val =
1834 xreadlink_with_size (dst_name, dst_sb.st_size);
1835 if (STREQ (dest_link_val, src_link_val))
1837 free (dest_link_val);
1839 free (src_link_val);
1843 error (0, saved_errno, _("cannot create symbolic link %s"),
1849 if (x->preserve_security_context)
1850 restore_default_fscreatecon_or_die ();
1852 /* There's no need to preserve timestamps or permissions. */
1853 preserve_metadata = false;
1855 if (x->preserve_ownership)
1857 /* Preserve the owner and group of the just-`copied'
1858 symbolic link, if possible. */
1860 if (lchown (dst_name, src_sb.st_uid, src_sb.st_gid) != 0
1861 && ! chown_failure_ok (x))
1863 error (0, errno, _("failed to preserve ownership for %s"),
1868 /* Can't preserve ownership of symlinks.
1869 FIXME: maybe give a warning or even error for symlinks
1870 in directories with the sticky bit set -- there, not
1871 preserving owner/group is a potential security problem. */
1877 error (0, 0, _("%s has unknown file type"), quote (src_name));
1881 if (command_line_arg)
1882 record_file (x->dest_info, dst_name, NULL);
1884 if ( ! preserve_metadata)
1887 if (copied_as_regular)
1890 /* POSIX says that `cp -p' must restore the following:
1892 - setuid, setgid bits
1894 If it fails to restore any of those, we may give a warning but
1895 the destination must not be removed.
1896 FIXME: implement the above. */
1898 /* Adjust the times (and if possible, ownership) for the copy.
1899 chown turns off set[ug]id bits for non-root,
1900 so do the chmod last. */
1902 if (x->preserve_timestamps)
1904 struct timespec timespec[2];
1905 timespec[0] = get_stat_atime (&src_sb);
1906 timespec[1] = get_stat_mtime (&src_sb);
1908 if (utimens (dst_name, timespec) != 0)
1910 error (0, errno, _("preserving times for %s"), quote (dst_name));
1911 if (x->require_preserve)
1916 /* Avoid calling chown if we know it's not necessary. */
1917 if (x->preserve_ownership
1918 && (new_dst || !SAME_OWNER_AND_GROUP (src_sb, dst_sb)))
1920 switch (set_owner (x, dst_name, -1, src_sb.st_uid, src_sb.st_gid))
1926 src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX);
1931 set_author (dst_name, -1, &src_sb);
1933 if (x->preserve_mode || x->move_mode)
1935 if (copy_acl (src_name, -1, dst_name, -1, src_mode) != 0
1936 && x->require_preserve)
1939 else if (x->set_mode)
1941 if (set_acl (dst_name, -1, x->mode) != 0)
1946 if (omitted_permissions)
1948 omitted_permissions &= ~ cached_umask ();
1950 if (omitted_permissions && !restore_dst_mode)
1952 /* Permissions were deliberately omitted when the file
1953 was created due to security concerns. See whether
1954 they need to be re-added now. It'd be faster to omit
1955 the lstat, but deducing the current destination mode
1956 is tricky in the presence of implementation-defined
1957 rules for special mode bits. */
1958 if (new_dst && lstat (dst_name, &dst_sb) != 0)
1960 error (0, errno, _("cannot stat %s"), quote (dst_name));
1963 dst_mode = dst_sb.st_mode;
1964 if (omitted_permissions & ~dst_mode)
1965 restore_dst_mode = true;
1969 if (restore_dst_mode)
1971 if (lchmod (dst_name, dst_mode | omitted_permissions) != 0)
1973 error (0, errno, _("preserving permissions for %s"),
1975 if (x->require_preserve)
1985 if (x->preserve_security_context)
1986 restore_default_fscreatecon_or_die ();
1988 /* We have failed to create the destination file.
1989 If we've just added a dev/ino entry via the remember_copied
1990 call above (i.e., unless we've just failed to create a hard link),
1991 remove the entry associating the source dev/ino with the
1992 destination file name, so we don't try to `preserve' a link
1993 to a file we didn't create. */
1994 if (earlier_file == NULL)
1995 forget_created (src_sb.st_ino, src_sb.st_dev);
1999 if (rename (dst_backup, dst_name) != 0)
2000 error (0, errno, _("cannot un-backup %s"), quote (dst_name));
2004 printf (_("%s -> %s (unbackup)\n"),
2005 quote_n (0, dst_backup), quote_n (1, dst_name));
2012 valid_options (const struct cp_options *co)
2014 assert (co != NULL);
2015 assert (VALID_BACKUP_TYPE (co->backup_type));
2016 assert (VALID_SPARSE_MODE (co->sparse_mode));
2017 assert (!(co->hard_link && co->symbolic_link));
2021 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
2022 any type. NONEXISTENT_DST should be true if the file DST_NAME
2023 is known not to exist (e.g., because its parent directory was just
2024 created); NONEXISTENT_DST should be false if DST_NAME might already
2025 exist. OPTIONS is ... FIXME-describe
2026 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
2027 same as) DST_NAME; otherwise, set clear it.
2028 Return true if successful. */
2031 copy (char const *src_name, char const *dst_name,
2032 bool nonexistent_dst, const struct cp_options *options,
2033 bool *copy_into_self, bool *rename_succeeded)
2035 assert (valid_options (options));
2037 /* Record the file names: they're used in case of error, when copying
2038 a directory into itself. I don't like to make these tools do *any*
2039 extra work in the common case when that work is solely to handle
2040 exceptional cases, but in this case, I don't see a way to derive the
2041 top level source and destination directory names where they're used.
2042 An alternative is to use COPY_INTO_SELF and print the diagnostic
2043 from every caller -- but I don't want to do that. */
2044 top_level_src_name = src_name;
2045 top_level_dst_name = dst_name;
2047 return copy_internal (src_name, dst_name, nonexistent_dst, 0, NULL,
2048 options, true, copy_into_self, rename_succeeded);
2051 /* Return true if this process has appropriate privileges to chown a
2052 file whose owner is not the effective user ID. */
2055 chown_privileges (void)
2057 #ifdef PRIV_FILE_CHOWN
2059 priv_set_t *pset = priv_allocset ();
2062 result = (getppriv (PRIV_EFFECTIVE, pset) == 0
2063 && priv_ismember (pset, PRIV_FILE_CHOWN));
2064 priv_freeset (pset);
2067 return (geteuid () == 0);
2071 /* Return true if it's OK for chown to fail, where errno is
2072 the error number that chown failed with and X is the copying
2076 chown_failure_ok (struct cp_options const *x)
2078 /* If non-root uses -p, it's ok if we can't preserve ownership.
2079 But root probably wants to know, e.g. if NFS disallows it,
2080 or if the target system doesn't support file ownership. */
2082 return ((errno == EPERM || errno == EINVAL) && !x->chown_privileges);
2085 /* Return the user's umask, caching the result. */
2090 static mode_t mask = (mode_t) -1;
2091 if (mask == (mode_t) -1)