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"
36 #include "canonicalize.h"
39 #include "euidaccess.h"
44 #include "filenamecat.h"
45 #include "full-write.h"
46 #include "getpagesize.h"
48 #include "hash-triple.h"
53 #include "stat-time.h"
56 #include "write-any-file.h"
57 #include "areadlink.h"
61 # define HAVE_FCHOWN false
62 # define fchown(fd, uid, gid) (-1)
66 # define HAVE_LCHOWN false
67 # define lchown(name, uid, gid) chown (name, uid, gid)
70 #define SAME_OWNER(A, B) ((A).st_uid == (B).st_uid)
71 #define SAME_GROUP(A, B) ((A).st_gid == (B).st_gid)
72 #define SAME_OWNER_AND_GROUP(A, B) (SAME_OWNER (A, B) && SAME_GROUP (A, B))
76 struct dir_list
*parent
;
81 /* Initial size of the cp.dest_info hash table. */
82 #define DEST_INFO_INITIAL_CAPACITY 61
84 static bool copy_internal (char const *src_name
, char const *dst_name
,
85 bool new_dst
, dev_t device
,
86 struct dir_list
*ancestors
,
87 const struct cp_options
*x
,
88 bool command_line_arg
,
90 bool *rename_succeeded
);
92 /* Pointers to the file names: they're used in the diagnostic that is issued
93 when we detect the user is trying to copy a directory into itself. */
94 static char const *top_level_src_name
;
95 static char const *top_level_dst_name
;
97 /* The invocation name of this program. */
98 extern char *program_name
;
100 /* FIXME: describe */
101 /* FIXME: rewrite this to use a hash table so we avoid the quadratic
102 performance hit that's probably noticeable only on trees deeper
103 than a few hundred levels. See use of active_dir_map in remove.c */
106 is_ancestor (const struct stat
*sb
, const struct dir_list
*ancestors
)
108 while (ancestors
!= 0)
110 if (ancestors
->ino
== sb
->st_ino
&& ancestors
->dev
== sb
->st_dev
)
112 ancestors
= ancestors
->parent
;
117 /* Read the contents of the directory SRC_NAME_IN, and recursively
118 copy the contents to DST_NAME_IN. NEW_DST is true if
119 DST_NAME_IN is a directory that was created previously in the
120 recursion. SRC_SB and ANCESTORS describe SRC_NAME_IN.
121 Set *COPY_INTO_SELF if SRC_NAME_IN is a parent of
122 (or the same as) DST_NAME_IN; otherwise, clear it.
123 Return true if successful. */
126 copy_dir (char const *src_name_in
, char const *dst_name_in
, bool new_dst
,
127 const struct stat
*src_sb
, struct dir_list
*ancestors
,
128 const struct cp_options
*x
, bool *copy_into_self
)
132 struct cp_options non_command_line_options
= *x
;
135 name_space
= savedir (src_name_in
);
136 if (name_space
== NULL
)
138 /* This diagnostic is a bit vague because savedir can fail in
139 several different ways. */
140 error (0, errno
, _("cannot access %s"), quote (src_name_in
));
144 /* For cp's -H option, dereference command line arguments, but do not
145 dereference symlinks that are found via recursive traversal. */
146 if (x
->dereference
== DEREF_COMMAND_LINE_ARGUMENTS
)
147 non_command_line_options
.dereference
= DEREF_NEVER
;
150 while (*namep
!= '\0')
152 bool local_copy_into_self
;
153 char *src_name
= file_name_concat (src_name_in
, namep
, NULL
);
154 char *dst_name
= file_name_concat (dst_name_in
, namep
, NULL
);
156 ok
&= copy_internal (src_name
, dst_name
, new_dst
, src_sb
->st_dev
,
157 ancestors
, &non_command_line_options
, false,
158 &local_copy_into_self
, NULL
);
159 *copy_into_self
|= local_copy_into_self
;
164 namep
+= strlen (namep
) + 1;
170 /* Set the owner and owning group of DEST_DESC to the st_uid and
171 st_gid fields of SRC_SB. If DEST_DESC is undefined (-1), set
172 the owner and owning group of DST_NAME instead; for
173 safety prefer lchown if the system supports it since no
174 symbolic links should be involved. 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 (lchown (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 /* FIXME: Modify the following code so that it does not
215 follow symbolic links. */
217 /* Preserve the st_author field. */
218 file_t file
= (dest_desc
< 0
219 ? file_name_lookup (dst_name
, 0, 0)
220 : getdport (dest_desc
));
221 if (file
== MACH_PORT_NULL
)
222 error (0, errno
, _("failed to lookup file %s"), quote (dst_name
));
225 error_t err
= file_chauthor (file
, src_sb
->st_author
);
227 error (0, err
, _("failed to preserve authorship for %s"),
229 mach_port_deallocate (mach_task_self (), file
);
234 /* Change the file mode bits of the file identified by DESC or NAME to MODE.
235 Use DESC if DESC is valid and fchmod is available, NAME otherwise. */
238 fchmod_or_lchmod (int desc
, char const *name
, mode_t mode
)
242 return fchmod (desc
, mode
);
244 return lchmod (name
, mode
);
247 /* Copy a regular file from SRC_NAME to DST_NAME.
248 If the source file contains holes, copies holes and blocks of zeros
249 in the source file as holes in the destination file.
250 (Holes are read as zeroes by the `read' system call.)
251 When creating the destination, use DST_MODE & ~OMITTED_PERMISSIONS
252 as the third argument in the call to open, adding
253 OMITTED_PERMISSIONS after copying as needed.
254 X provides many option settings.
255 Return true if successful.
256 *NEW_DST is as in copy_internal.
257 SRC_SB is the result of calling XSTAT (aka stat) on SRC_NAME. */
260 copy_reg (char const *src_name
, char const *dst_name
,
261 const struct cp_options
*x
,
262 mode_t dst_mode
, mode_t omitted_permissions
, bool *new_dst
,
263 struct stat
const *src_sb
)
266 char *buf_alloc
= NULL
;
267 char *name_alloc
= NULL
;
268 char const *followed_dest_name
= dst_name
;
272 mode_t src_mode
= src_sb
->st_mode
;
274 struct stat src_open_sb
;
275 bool return_val
= true;
277 source_desc
= open (src_name
,
279 | (x
->dereference
== DEREF_NEVER
? O_NOFOLLOW
: 0)));
282 error (0, errno
, _("cannot open %s for reading"), quote (src_name
));
286 if (fstat (source_desc
, &src_open_sb
) != 0)
288 error (0, errno
, _("cannot fstat %s"), quote (src_name
));
293 /* Compare the source dev/ino from the open file to the incoming,
294 saved ones obtained via a previous call to stat. */
295 if (! SAME_INODE (*src_sb
, src_open_sb
))
298 _("skipping file %s, as it was replaced while being copied"),
304 /* The semantics of the following open calls are mandated
305 by the specs for both cp and mv. */
308 dest_desc
= open (dst_name
, O_WRONLY
| O_TRUNC
| O_BINARY
);
311 /* When using cp --preserve=context to copy to an existing destination,
312 use the default context rather than that of the source. Why?
313 1) the src context may prohibit writing, and
314 2) because it's more consistent to use the same context
315 that is used when the destination file doesn't already exist. */
316 if (x
->preserve_security_context
&& 0 <= dest_desc
)
318 security_context_t con
= NULL
;
319 if (getfscreatecon (&con
) < 0)
321 error (0, errno
, _("failed to get file system create context"));
322 if (x
->require_preserve_context
)
331 if (fsetfilecon (dest_desc
, con
) < 0)
334 _("failed to set the security context of %s to %s"),
335 quote_n (0, dst_name
), quote_n (1, con
));
336 if (x
->require_preserve_context
)
347 if (dest_desc
< 0 && x
->unlink_dest_after_failed_open
)
349 if (unlink (dst_name
) != 0)
351 error (0, errno
, _("cannot remove %s"), quote (dst_name
));
356 printf (_("removed %s\n"), quote (dst_name
));
358 /* Tell caller that the destination file was unlinked. */
365 int open_flags
= O_WRONLY
| O_CREAT
| O_EXCL
| O_BINARY
;
366 dest_desc
= open (dst_name
, open_flags
,
367 dst_mode
& ~omitted_permissions
);
370 /* When trying to copy through a dangling destination symlink,
371 the above open fails with EEXIST. If that happens, and
372 lstat'ing the DST_NAME shows that it is a symlink, repeat
373 the open call, but this time with the name of the final,
374 missing directory entry. */
375 if (dest_desc
< 0 && dest_errno
== EEXIST
)
377 struct stat dangling_link_sb
;
378 if (lstat (dst_name
, &dangling_link_sb
) == 0
379 && S_ISLNK (dangling_link_sb
.st_mode
))
381 /* FIXME: This is way overkill, since all that's needed
382 is to follow the symlink that is the last file name
385 canonicalize_filename_mode (dst_name
, CAN_MISSING
);
388 followed_dest_name
= name_alloc
;
389 dest_desc
= open (followed_dest_name
, open_flags
,
390 dst_mode
& ~omitted_permissions
);
397 omitted_permissions
= 0;
401 error (0, dest_errno
, _("cannot create regular file %s"),
407 if (fstat (dest_desc
, &sb
) != 0)
409 error (0, errno
, _("cannot fstat %s"), quote (dst_name
));
411 goto close_src_and_dst_desc
;
415 typedef uintptr_t word
;
416 off_t n_read_total
= 0;
418 /* Choose a suitable buffer size; it may be adjusted later. */
419 size_t buf_alignment
= lcm (getpagesize (), sizeof (word
));
420 size_t buf_alignment_slop
= sizeof (word
) + buf_alignment
- 1;
421 size_t buf_size
= ST_BLKSIZE (sb
);
423 /* Deal with sparse files. */
424 bool last_write_made_hole
= false;
425 bool make_holes
= false;
427 if (S_ISREG (sb
.st_mode
))
429 /* Even with --sparse=always, try to create holes only
430 if the destination is a regular file. */
431 if (x
->sparse_mode
== SPARSE_ALWAYS
)
434 #if HAVE_STRUCT_STAT_ST_BLOCKS
435 /* Use a heuristic to determine whether SRC_NAME contains any sparse
436 blocks. If the file has fewer blocks than would normally be
437 needed for a file of its size, then at least one of the blocks in
438 the file is a hole. */
439 if (x
->sparse_mode
== SPARSE_AUTO
&& S_ISREG (src_open_sb
.st_mode
)
440 && ST_NBLOCKS (src_open_sb
) < src_open_sb
.st_size
/ ST_NBLOCKSIZE
)
445 /* If not making a sparse file, try to use a more-efficient
449 /* These days there's no point ever messing with buffers smaller
450 than 8 KiB. It would be nice to configure SMALL_BUF_SIZE
451 dynamically for this host and pair of files, but there doesn't
452 seem to be a good way to get readahead info portably. */
453 enum { SMALL_BUF_SIZE
= 8 * 1024 };
455 /* Compute the least common multiple of the input and output
456 buffer sizes, adjusting for outlandish values. */
457 size_t blcm_max
= MIN (SIZE_MAX
, SSIZE_MAX
) - buf_alignment_slop
;
458 size_t blcm
= buffer_lcm (ST_BLKSIZE (src_open_sb
), buf_size
,
461 /* Do not use a block size that is too small. */
462 buf_size
= MAX (SMALL_BUF_SIZE
, blcm
);
464 /* Do not bother with a buffer larger than the input file, plus one
465 byte to make sure the file has not grown while reading it. */
466 if (S_ISREG (src_open_sb
.st_mode
) && src_open_sb
.st_size
< buf_size
)
467 buf_size
= src_open_sb
.st_size
+ 1;
469 /* However, stick with a block size that is a positive multiple of
470 blcm, overriding the above adjustments. Watch out for
472 buf_size
+= blcm
- 1;
473 buf_size
-= buf_size
% blcm
;
474 if (buf_size
== 0 || blcm_max
< buf_size
)
478 /* Make a buffer with space for a sentinel at the end. */
479 buf_alloc
= xmalloc (buf_size
+ buf_alignment_slop
);
480 buf
= ptr_align (buf_alloc
, buf_alignment
);
486 ssize_t n_read
= read (source_desc
, buf
, buf_size
);
493 error (0, errno
, _("reading %s"), quote (src_name
));
495 goto close_src_and_dst_desc
;
500 n_read_total
+= n_read
;
506 /* Sentinel to stop loop. */
509 /* Usually, buf[n_read] is not the byte just before a "word"
510 (aka uintptr_t) boundary. In that case, the word-oriented
511 test below (*wp++ == 0) would read some uninitialized bytes
512 after the sentinel. To avoid false-positive reports about
513 this condition (e.g., from a tool like valgrind), set the
514 remaining bytes -- to any value. */
515 memset (buf
+ n_read
+ 1, 0, sizeof (word
) - 1);
518 /* Find first nonzero *word*, or the word with the sentinel. */
524 /* Find the first nonzero *byte*, or the sentinel. */
526 cp
= (char *) (wp
- 1);
530 if (cp
<= buf
+ n_read
)
531 /* Clear to indicate that a normal write is needed. */
535 /* We found the sentinel, so the whole input block was zero.
537 if (lseek (dest_desc
, n_read
, SEEK_CUR
) < 0)
539 error (0, errno
, _("cannot lseek %s"), quote (dst_name
));
541 goto close_src_and_dst_desc
;
543 last_write_made_hole
= true;
550 if (full_write (dest_desc
, buf
, n
) != n
)
552 error (0, errno
, _("writing %s"), quote (dst_name
));
554 goto close_src_and_dst_desc
;
556 last_write_made_hole
= false;
558 /* A short read on a regular file means EOF. */
559 if (n_read
!= buf_size
&& S_ISREG (src_open_sb
.st_mode
))
564 /* If the file ends with a `hole', we need to do something to record
565 the length of the file. On modern systems, calling ftruncate does
566 the job. On systems without native ftruncate support, we have to
567 write a byte at the ending position. Otherwise the kernel would
568 truncate the file at the end of the last write operation. */
570 if (last_write_made_hole
)
573 ? /* ftruncate sets the file size,
574 so there is no need for a write. */
575 ftruncate (dest_desc
, n_read_total
) < 0
576 : /* Seek backwards one character and write a null. */
577 (lseek (dest_desc
, (off_t
) -1, SEEK_CUR
) < 0L
578 || full_write (dest_desc
, "", 1) != 1))
580 error (0, errno
, _("writing %s"), quote (dst_name
));
582 goto close_src_and_dst_desc
;
587 if (x
->preserve_timestamps
)
589 struct timespec timespec
[2];
590 timespec
[0] = get_stat_atime (src_sb
);
591 timespec
[1] = get_stat_mtime (src_sb
);
593 if (gl_futimens (dest_desc
, followed_dest_name
, timespec
) != 0)
595 error (0, errno
, _("preserving times for %s"), quote (dst_name
));
596 if (x
->require_preserve
)
599 goto close_src_and_dst_desc
;
604 if (x
->preserve_ownership
&& ! SAME_OWNER_AND_GROUP (*src_sb
, sb
))
606 switch (set_owner (x
, followed_dest_name
, dest_desc
,
607 src_sb
->st_uid
, src_sb
->st_gid
))
611 goto close_src_and_dst_desc
;
614 src_mode
&= ~ (S_ISUID
| S_ISGID
| S_ISVTX
);
619 set_author (followed_dest_name
, dest_desc
, src_sb
);
621 if (x
->preserve_mode
|| x
->move_mode
)
623 if (copy_acl (src_name
, source_desc
, followed_dest_name
, dest_desc
, src_mode
) != 0
624 && x
->require_preserve
)
627 else if (x
->set_mode
)
629 if (set_acl (followed_dest_name
, dest_desc
, x
->mode
) != 0)
632 else if (omitted_permissions
)
634 omitted_permissions
&= ~ cached_umask ();
635 if (omitted_permissions
636 && fchmod_or_lchmod (dest_desc
, followed_dest_name
, dst_mode
) != 0)
638 error (0, errno
, _("preserving permissions for %s"),
640 if (x
->require_preserve
)
645 close_src_and_dst_desc
:
646 if (close (dest_desc
) < 0)
648 error (0, errno
, _("closing %s"), quote (dst_name
));
652 if (close (source_desc
) < 0)
654 error (0, errno
, _("closing %s"), quote (src_name
));
663 /* Return true if it's ok that the source and destination
664 files are the `same' by some measure. The goal is to avoid
665 making the `copy' operation remove both copies of the file
666 in that case, while still allowing the user to e.g., move or
667 copy a regular file onto a symlink that points to it.
668 Try to minimize the cost of this function in the common case.
669 Set *RETURN_NOW if we've determined that the caller has no more
670 work to do and should return successfully, right away.
672 Set *UNLINK_SRC if we've determined that the caller wants to do
673 `rename (a, b)' where `a' and `b' are distinct hard links to the same
674 file. In that case, the caller should try to unlink `a' and then return
675 successfully. Ideally, we wouldn't have to do that, and we'd be
676 able to rely on rename to remove the source file. However, POSIX
677 mistakenly requires that such a rename call do *nothing* and return
681 same_file_ok (char const *src_name
, struct stat
const *src_sb
,
682 char const *dst_name
, struct stat
const *dst_sb
,
683 const struct cp_options
*x
, bool *return_now
, bool *unlink_src
)
685 const struct stat
*src_sb_link
;
686 const struct stat
*dst_sb_link
;
687 struct stat tmp_dst_sb
;
688 struct stat tmp_src_sb
;
691 bool same
= SAME_INODE (*src_sb
, *dst_sb
);
696 /* FIXME: this should (at the very least) be moved into the following
697 if-block. More likely, it should be removed, because it inhibits
698 making backups. But removing it will result in a change in behavior
699 that will probably have to be documented -- and tests will have to
701 if (same
&& x
->hard_link
)
707 if (x
->dereference
== DEREF_NEVER
)
711 /* If both the source and destination files are symlinks (and we'll
712 know this here IFF preserving symlinks), then it's ok -- as long
713 as they are distinct. */
714 if (S_ISLNK (src_sb
->st_mode
) && S_ISLNK (dst_sb
->st_mode
))
715 return ! same_name (src_name
, dst_name
);
717 src_sb_link
= src_sb
;
718 dst_sb_link
= dst_sb
;
725 if (lstat (dst_name
, &tmp_dst_sb
) != 0
726 || lstat (src_name
, &tmp_src_sb
) != 0)
729 src_sb_link
= &tmp_src_sb
;
730 dst_sb_link
= &tmp_dst_sb
;
732 same_link
= SAME_INODE (*src_sb_link
, *dst_sb_link
);
734 /* If both are symlinks, then it's ok, but only if the destination
735 will be unlinked before being opened. This is like the test
736 above, but with the addition of the unlink_dest_before_opening
737 conjunct because otherwise, with two symlinks to the same target,
738 we'd end up truncating the source file. */
739 if (S_ISLNK (src_sb_link
->st_mode
) && S_ISLNK (dst_sb_link
->st_mode
)
740 && x
->unlink_dest_before_opening
)
744 /* The backup code ensures there's a copy, so it's usually ok to
745 remove any destination file. One exception is when both
746 source and destination are the same directory entry. In that
747 case, moving the destination file aside (in making the backup)
748 would also rename the source file and result in an error. */
749 if (x
->backup_type
!= no_backups
)
753 /* In copy mode when dereferencing symlinks, if the source is a
754 symlink and the dest is not, then backing up the destination
755 (moving it aside) would make it a dangling symlink, and the
756 subsequent attempt to open it in copy_reg would fail with
757 a misleading diagnostic. Avoid that by returning zero in
758 that case so the caller can make cp (or mv when it has to
759 resort to reading the source file) fail now. */
761 /* FIXME-note: even with the following kludge, we can still provoke
762 the offending diagnostic. It's just a little harder to do :-)
763 $ rm -f a b c; touch c; ln -s c b; ln -s b a; cp -b a b
764 cp: cannot open `a' for reading: No such file or directory
765 That's misleading, since a subsequent `ls' shows that `a'
767 One solution would be to open the source file *before* moving
768 aside the destination, but that'd involve a big rewrite. */
770 && x
->dereference
!= DEREF_NEVER
771 && S_ISLNK (src_sb_link
->st_mode
)
772 && ! S_ISLNK (dst_sb_link
->st_mode
))
778 return ! same_name (src_name
, dst_name
);
782 /* FIXME: use or remove */
784 /* If we're making a backup, we'll detect the problem case in
785 copy_reg because SRC_NAME will no longer exist. Allowing
786 the test to be deferred lets cp do some useful things.
787 But when creating hardlinks and SRC_NAME is a symlink
788 but DST_NAME is not we must test anyway. */
790 || !S_ISLNK (src_sb_link
->st_mode
)
791 || S_ISLNK (dst_sb_link
->st_mode
))
794 if (x
->dereference
!= DEREF_NEVER
)
798 /* They may refer to the same file if we're in move mode and the
799 target is a symlink. That is ok, since we remove any existing
800 destination file before opening it -- via `rename' if they're on
801 the same file system, via `unlink (DST_NAME)' otherwise.
802 It's also ok if they're distinct hard links to the same file. */
803 if (x
->move_mode
|| x
->unlink_dest_before_opening
)
805 if (S_ISLNK (dst_sb_link
->st_mode
))
809 && 1 < dst_sb_link
->st_nlink
810 && ! same_name (src_name
, dst_name
))
821 /* If neither is a symlink, then it's ok as long as they aren't
822 hard links to the same file. */
823 if (!S_ISLNK (src_sb_link
->st_mode
) && !S_ISLNK (dst_sb_link
->st_mode
))
825 if (!SAME_INODE (*src_sb_link
, *dst_sb_link
))
828 /* If they are the same file, it's ok if we're making hard links. */
836 /* It's ok to remove a destination symlink. But that works only when we
837 unlink before opening the destination and when the source and destination
838 files are on the same partition. */
839 if (x
->unlink_dest_before_opening
840 && S_ISLNK (dst_sb_link
->st_mode
))
841 return dst_sb_link
->st_dev
== src_sb_link
->st_dev
;
843 if (x
->dereference
== DEREF_NEVER
)
845 if ( ! S_ISLNK (src_sb_link
->st_mode
))
846 tmp_src_sb
= *src_sb_link
;
847 else if (stat (src_name
, &tmp_src_sb
) != 0)
850 if ( ! S_ISLNK (dst_sb_link
->st_mode
))
851 tmp_dst_sb
= *dst_sb_link
;
852 else if (stat (dst_name
, &tmp_dst_sb
) != 0)
855 if ( ! SAME_INODE (tmp_src_sb
, tmp_dst_sb
))
858 /* FIXME: shouldn't this be testing whether we're making symlinks? */
869 /* Return true if FILE, with mode MODE, is writable in the sense of 'mv'.
870 Always consider a symbolic link to be writable. */
872 writable_destination (char const *file
, mode_t mode
)
874 return (S_ISLNK (mode
)
875 || can_write_any_file ()
876 || euidaccess (file
, W_OK
) == 0);
880 overwrite_prompt (char const *dst_name
, struct stat
const *dst_sb
)
882 if (! writable_destination (dst_name
, dst_sb
->st_mode
))
884 char perms
[12]; /* "-rwxrwxrwx " ls-style modes. */
885 strmode (dst_sb
->st_mode
, perms
);
888 _("%s: try to overwrite %s, overriding mode %04lo (%s)? "),
889 program_name
, quote (dst_name
),
890 (unsigned long int) (dst_sb
->st_mode
& CHMOD_MODE_BITS
),
895 fprintf (stderr
, _("%s: overwrite %s? "),
896 program_name
, quote (dst_name
));
900 /* Initialize the hash table implementing a set of F_triple entries
901 corresponding to destination files. */
903 dest_info_init (struct cp_options
*x
)
906 = hash_initialize (DEST_INFO_INITIAL_CAPACITY
,
913 /* Initialize the hash table implementing a set of F_triple entries
914 corresponding to source files listed on the command line. */
916 src_info_init (struct cp_options
*x
)
919 /* Note that we use triple_hash_no_name here.
920 Contrast with the use of triple_hash above.
921 That is necessary because a source file may be specified
922 in many different ways. We want to warn about this
928 = hash_initialize (DEST_INFO_INITIAL_CAPACITY
,
935 /* When effecting a move (e.g., for mv(1)), and given the name DST_NAME
936 of the destination and a corresponding stat buffer, DST_SB, return
937 true if the logical `move' operation should _not_ proceed.
938 Otherwise, return false.
939 Depending on options specified in X, this code may issue an
940 interactive prompt asking whether it's ok to overwrite DST_NAME. */
942 abandon_move (const struct cp_options
*x
,
943 char const *dst_name
,
944 struct stat
const *dst_sb
)
946 assert (x
->move_mode
);
947 return (x
->interactive
== I_ALWAYS_NO
948 || ((x
->interactive
== I_ASK_USER
949 || (x
->interactive
== I_UNSPECIFIED
951 && ! writable_destination (dst_name
, dst_sb
->st_mode
)))
952 && (overwrite_prompt (dst_name
, dst_sb
), 1)
956 /* Print --verbose output on standard output, e.g. `new' -> `old'.
957 If BACKUP_DST_NAME is non-NULL, then also indicate that it is
958 the name of a backup file. */
960 emit_verbose (char const *src
, char const *dst
, char const *backup_dst_name
)
962 printf ("%s -> %s", quote_n (0, src
), quote_n (1, dst
));
964 printf (_(" (backup: %s)"), quote (backup_dst_name
));
968 /* A wrapper around "setfscreatecon (NULL)" that exits upon failure. */
970 restore_default_fscreatecon_or_die (void)
972 if (setfscreatecon (NULL
) != 0)
973 error (EXIT_FAILURE
, errno
,
974 _("failed to restore the default file creation context"));
977 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
978 any type. NEW_DST should be true if the file DST_NAME cannot
979 exist because its parent directory was just created; NEW_DST should
980 be false if DST_NAME might already exist. DEVICE is the device
981 number of the parent directory, or 0 if the parent of this file is
982 not known. ANCESTORS points to a linked, null terminated list of
983 devices and inodes of parent directories of SRC_NAME. COMMAND_LINE_ARG
984 is true iff SRC_NAME was specified on the command line.
985 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
986 same as) DST_NAME; otherwise, clear it.
987 Return true if successful. */
989 copy_internal (char const *src_name
, char const *dst_name
,
992 struct dir_list
*ancestors
,
993 const struct cp_options
*x
,
994 bool command_line_arg
,
995 bool *copy_into_self
,
996 bool *rename_succeeded
)
1001 mode_t dst_mode
IF_LINT (= 0);
1002 mode_t dst_mode_bits
;
1003 mode_t omitted_permissions
;
1004 bool restore_dst_mode
= false;
1005 char *earlier_file
= NULL
;
1006 char *dst_backup
= NULL
;
1007 bool backup_succeeded
= false;
1009 bool copied_as_regular
= false;
1010 bool preserve_metadata
;
1011 bool have_dst_lstat
= false;
1013 if (x
->move_mode
&& rename_succeeded
)
1014 *rename_succeeded
= false;
1016 *copy_into_self
= false;
1018 if (XSTAT (x
, src_name
, &src_sb
) != 0)
1020 error (0, errno
, _("cannot stat %s"), quote (src_name
));
1024 src_mode
= src_sb
.st_mode
;
1026 if (S_ISDIR (src_mode
) && !x
->recursive
)
1028 error (0, 0, _("omitting directory %s"), quote (src_name
));
1032 /* Detect the case in which the same source file appears more than
1033 once on the command line and no backup option has been selected.
1034 If so, simply warn and don't copy it the second time.
1035 This check is enabled only if x->src_info is non-NULL. */
1036 if (command_line_arg
)
1038 if ( ! S_ISDIR (src_sb
.st_mode
)
1039 && x
->backup_type
== no_backups
1040 && seen_file (x
->src_info
, src_name
, &src_sb
))
1042 error (0, 0, _("warning: source file %s specified more than once"),
1047 record_file (x
->src_info
, src_name
, &src_sb
);
1052 /* Regular files can be created by writing through symbolic
1053 links, but other files cannot. So use stat on the
1054 destination when copying a regular file, and lstat otherwise.
1055 However, if we intend to unlink or remove the destination
1056 first, use lstat, since a copy won't actually be made to the
1057 destination in that case. */
1059 ((S_ISREG (src_mode
)
1060 || (x
->copy_as_regular
1061 && ! (S_ISDIR (src_mode
) || S_ISLNK (src_mode
))))
1062 && ! (x
->move_mode
|| x
->symbolic_link
|| x
->hard_link
1063 || x
->backup_type
!= no_backups
1064 || x
->unlink_dest_before_opening
));
1066 ? stat (dst_name
, &dst_sb
)
1067 : lstat (dst_name
, &dst_sb
))
1070 if (errno
!= ENOENT
)
1072 error (0, errno
, _("cannot stat %s"), quote (dst_name
));
1081 { /* Here, we know that dst_name exists, at least to the point
1082 that it is stat'able or lstat'able. */
1086 have_dst_lstat
= !use_stat
;
1087 if (! same_file_ok (src_name
, &src_sb
, dst_name
, &dst_sb
,
1088 x
, &return_now
, &unlink_src
))
1090 error (0, 0, _("%s and %s are the same file"),
1091 quote_n (0, src_name
), quote_n (1, dst_name
));
1095 if (!S_ISDIR (src_mode
) && x
->update
)
1097 /* When preserving time stamps (but not moving within a file
1098 system), don't worry if the destination time stamp is
1099 less than the source merely because of time stamp
1101 int options
= ((x
->preserve_timestamps
1103 && dst_sb
.st_dev
== src_sb
.st_dev
))
1104 ? UTIMECMP_TRUNCATE_SOURCE
1107 if (0 <= utimecmp (dst_name
, &dst_sb
, &src_sb
, options
))
1109 /* We're using --update and the destination is not older
1110 than the source, so do not copy or move. Pretend the
1111 rename succeeded, so the caller (if it's mv) doesn't
1112 end up removing the source file. */
1113 if (rename_succeeded
)
1114 *rename_succeeded
= true;
1119 /* When there is an existing destination file, we may end up
1120 returning early, and hence not copying/moving the file.
1121 This may be due to an interactive `negative' reply to the
1122 prompt about the existing file. It may also be due to the
1123 use of the --reply=no option.
1125 cp and mv treat -i and -f differently. */
1128 if (abandon_move (x
, dst_name
, &dst_sb
)
1129 || (unlink_src
&& unlink (src_name
) == 0))
1131 /* Pretend the rename succeeded, so the caller (mv)
1132 doesn't end up removing the source file. */
1133 if (rename_succeeded
)
1134 *rename_succeeded
= true;
1135 if (unlink_src
&& x
->verbose
)
1136 printf (_("removed %s\n"), quote (src_name
));
1141 error (0, errno
, _("cannot remove %s"), quote (src_name
));
1147 if (! S_ISDIR (src_mode
)
1148 && (x
->interactive
== I_ALWAYS_NO
1149 || (x
->interactive
== I_ASK_USER
1150 && (overwrite_prompt (dst_name
, &dst_sb
), 1)
1158 if (!S_ISDIR (dst_sb
.st_mode
))
1160 if (S_ISDIR (src_mode
))
1162 if (x
->move_mode
&& x
->backup_type
!= no_backups
)
1164 /* Moving a directory onto an existing
1165 non-directory is ok only with --backup. */
1170 _("cannot overwrite non-directory %s with directory %s"),
1171 quote_n (0, dst_name
), quote_n (1, src_name
));
1176 /* Don't let the user destroy their data, even if they try hard:
1177 This mv command must fail (likewise for cp):
1178 rm -rf a b c; mkdir a b c; touch a/f b/f; mv a/f b/f c
1179 Otherwise, the contents of b/f would be lost.
1180 In the case of `cp', b/f would be lost if the user simulated
1181 a move using cp and rm.
1182 Note that it works fine if you use --backup=numbered. */
1183 if (command_line_arg
1184 && x
->backup_type
!= numbered_backups
1185 && seen_file (x
->dest_info
, dst_name
, &dst_sb
))
1188 _("will not overwrite just-created %s with %s"),
1189 quote_n (0, dst_name
), quote_n (1, src_name
));
1194 if (!S_ISDIR (src_mode
))
1196 if (S_ISDIR (dst_sb
.st_mode
))
1198 if (x
->move_mode
&& x
->backup_type
!= no_backups
)
1200 /* Moving a non-directory onto an existing
1201 directory is ok only with --backup. */
1206 _("cannot overwrite directory %s with non-directory"),
1215 /* Don't allow user to move a directory onto a non-directory. */
1216 if (S_ISDIR (src_sb
.st_mode
) && !S_ISDIR (dst_sb
.st_mode
)
1217 && x
->backup_type
== no_backups
)
1220 _("cannot move directory onto non-directory: %s -> %s"),
1221 quote_n (0, src_name
), quote_n (0, dst_name
));
1226 if (x
->backup_type
!= no_backups
1227 /* Don't try to back up a destination if the last
1228 component of src_name is "." or "..". */
1229 && ! dot_or_dotdot (last_component (src_name
))
1230 /* Create a backup of each destination directory in move mode,
1231 but not in copy mode. FIXME: it might make sense to add an
1232 option to suppress backup creation also for move mode.
1233 That would let one use mv to merge new content into an
1234 existing hierarchy. */
1235 && (x
->move_mode
|| ! S_ISDIR (dst_sb
.st_mode
)))
1237 char *tmp_backup
= find_backup_file_name (dst_name
,
1240 /* Detect (and fail) when creating the backup file would
1241 destroy the source file. Before, running the commands
1242 cd /tmp; rm -f a a~; : > a; echo A > a~; cp --b=simple a~ a
1243 would leave two zero-length files: a and a~. */
1244 /* FIXME: but simply change e.g., the final a~ to `./a~'
1245 and the source will still be destroyed. */
1246 if (STREQ (tmp_backup
, src_name
))
1250 ? _("backing up %s would destroy source; %s not moved")
1251 : _("backing up %s would destroy source; %s not copied"));
1253 quote_n (0, dst_name
),
1254 quote_n (1, src_name
));
1260 Using alloca for a file name that may be arbitrarily
1261 long is not recommended. In fact, even forming such a name
1262 should be discouraged. Eventually, this code will be rewritten
1263 to use fts, so using alloca here will be less of a problem. */
1264 ASSIGN_STRDUPA (dst_backup
, tmp_backup
);
1266 if (rename (dst_name
, dst_backup
) != 0)
1268 if (errno
!= ENOENT
)
1270 error (0, errno
, _("cannot backup %s"), quote (dst_name
));
1280 backup_succeeded
= true;
1284 else if (! S_ISDIR (dst_sb
.st_mode
)
1285 && (x
->unlink_dest_before_opening
1286 || (x
->preserve_links
&& 1 < dst_sb
.st_nlink
)
1288 && x
->dereference
== DEREF_NEVER
1289 && S_ISLNK (src_sb
.st_mode
))
1292 if (unlink (dst_name
) != 0 && errno
!= ENOENT
)
1294 error (0, errno
, _("cannot remove %s"), quote (dst_name
));
1299 printf (_("removed %s\n"), quote (dst_name
));
1304 /* Ensure we don't try to copy through a symlink that was
1305 created by a prior call to this function. */
1306 if (command_line_arg
1309 && x
->backup_type
== no_backups
)
1311 bool lstat_ok
= true;
1312 struct stat tmp_buf
;
1313 struct stat
*dst_lstat_sb
;
1315 /* If we called lstat above, good: use that data.
1316 Otherwise, call lstat here, in case dst_name is a symlink. */
1318 dst_lstat_sb
= &dst_sb
;
1321 if (lstat (dst_name
, &tmp_buf
) == 0)
1322 dst_lstat_sb
= &tmp_buf
;
1327 /* Never copy through a symlink we've just created. */
1329 && S_ISLNK (dst_lstat_sb
->st_mode
)
1330 && seen_file (x
->dest_info
, dst_name
, dst_lstat_sb
))
1333 _("will not copy %s through just-created symlink %s"),
1334 quote_n (0, src_name
), quote_n (1, dst_name
));
1339 /* If the source is a directory, we don't always create the destination
1340 directory. So --verbose should not announce anything until we're
1341 sure we'll create a directory. */
1342 if (x
->verbose
&& !S_ISDIR (src_mode
))
1343 emit_verbose (src_name
, dst_name
, backup_succeeded
? dst_backup
: NULL
);
1345 /* Associate the destination file name with the source device and inode
1346 so that if we encounter a matching dev/ino pair in the source tree
1347 we can arrange to create a hard link between the corresponding names
1348 in the destination tree.
1350 Sometimes, when preserving links, we have to record dev/ino even
1351 though st_nlink == 1:
1352 - when in move_mode, since we may be moving a group of N hard-linked
1353 files (via two or more command line arguments) to a different
1354 partition; the links may be distributed among the command line
1355 arguments (possibly hierarchies) so that the link count of
1356 the final, once-linked source file is reduced to 1 when it is
1357 considered below. But in this case (for mv) we don't need to
1358 incur the expense of recording the dev/ino => name mapping; all we
1359 really need is a lookup, to see if the dev/ino pair has already
1361 - when using -H and processing a command line argument;
1362 that command line argument could be a symlink pointing to another
1363 command line argument. With `cp -H --preserve=link', we hard-link
1364 those two destination files.
1365 - likewise for -L except that it applies to all files, not just
1366 command line arguments.
1368 Also record directory dev/ino when using --recursive. We'll use that
1369 info to detect this problem: cp -R dir dir. FIXME-maybe: ideally,
1370 directory info would be recorded in a separate hash table, since
1371 such entries are useful only while a single command line hierarchy
1372 is being copied -- so that separate table could be cleared between
1373 command line args. Using the same hash table to preserve hard
1374 links means that it may not be cleared. */
1376 if (x
->move_mode
&& src_sb
.st_nlink
== 1)
1378 earlier_file
= src_to_dest_lookup (src_sb
.st_ino
, src_sb
.st_dev
);
1380 else if ((x
->preserve_links
1381 && (1 < src_sb
.st_nlink
1382 || (command_line_arg
1383 && x
->dereference
== DEREF_COMMAND_LINE_ARGUMENTS
)
1384 || x
->dereference
== DEREF_ALWAYS
))
1385 || (x
->recursive
&& S_ISDIR (src_mode
)))
1387 earlier_file
= remember_copied (dst_name
, src_sb
.st_ino
, src_sb
.st_dev
);
1390 /* Did we copy this inode somewhere else (in this command line argument)
1391 and therefore this is a second hard link to the inode? */
1395 /* Avoid damaging the destination file system by refusing to preserve
1396 hard-linked directories (which are found at least in Netapp snapshot
1398 if (S_ISDIR (src_mode
))
1400 /* If src_name and earlier_file refer to the same directory entry,
1401 then warn about copying a directory into itself. */
1402 if (same_name (src_name
, earlier_file
))
1404 error (0, 0, _("cannot copy a directory, %s, into itself, %s"),
1405 quote_n (0, top_level_src_name
),
1406 quote_n (1, top_level_dst_name
));
1407 *copy_into_self
= true;
1410 else if (x
->dereference
== DEREF_ALWAYS
)
1412 /* This happens when e.g., encountering a directory for the
1413 second or subsequent time via symlinks when cp is invoked
1414 with -R and -L. E.g.,
1415 rm -rf a b c d; mkdir a b c d; ln -s ../c a; ln -s ../c b;
1421 error (0, 0, _("will not create hard link %s to directory %s"),
1422 quote_n (0, dst_name
), quote_n (1, earlier_file
));
1428 bool link_failed
= (link (earlier_file
, dst_name
) != 0);
1430 /* If the link failed because of an existing destination,
1431 remove that file and then call link again. */
1432 if (link_failed
&& errno
== EEXIST
)
1434 if (unlink (dst_name
) != 0)
1436 error (0, errno
, _("cannot remove %s"), quote (dst_name
));
1440 printf (_("removed %s\n"), quote (dst_name
));
1441 link_failed
= (link (earlier_file
, dst_name
) != 0);
1446 error (0, errno
, _("cannot create hard link %s to %s"),
1447 quote_n (0, dst_name
), quote_n (1, earlier_file
));
1457 if (rename (src_name
, dst_name
) == 0)
1459 if (x
->verbose
&& S_ISDIR (src_mode
))
1460 emit_verbose (src_name
, dst_name
,
1461 backup_succeeded
? dst_backup
: NULL
);
1463 if (rename_succeeded
)
1464 *rename_succeeded
= true;
1466 if (command_line_arg
)
1468 /* Record destination dev/ino/name, so that if we are asked
1469 to overwrite that file again, we can detect it and fail. */
1470 /* It's fine to use the _source_ stat buffer (src_sb) to get the
1471 _destination_ dev/ino, since the rename above can't have
1472 changed those, and `mv' always uses lstat.
1473 We could limit it further by operating
1474 only on non-directories. */
1475 record_file (x
->dest_info
, dst_name
, &src_sb
);
1481 /* FIXME: someday, consider what to do when moving a directory into
1482 itself but when source and destination are on different devices. */
1484 /* This happens when attempting to rename a directory to a
1485 subdirectory of itself. */
1486 if (errno
== EINVAL
)
1488 /* FIXME: this is a little fragile in that it relies on rename(2)
1489 failing with a specific errno value. Expect problems on
1490 non-POSIX systems. */
1491 error (0, 0, _("cannot move %s to a subdirectory of itself, %s"),
1492 quote_n (0, top_level_src_name
),
1493 quote_n (1, top_level_dst_name
));
1495 /* Note that there is no need to call forget_created here,
1496 (compare with the other calls in this file) since the
1497 destination directory didn't exist before. */
1499 *copy_into_self
= true;
1500 /* FIXME-cleanup: Don't return true here; adjust mv.c accordingly.
1501 The only caller that uses this code (mv.c) ends up setting its
1502 exit status to nonzero when copy_into_self is nonzero. */
1506 /* WARNING: there probably exist systems for which an inter-device
1507 rename fails with a value of errno not handled here.
1508 If/as those are reported, add them to the condition below.
1509 If this happens to you, please do the following and send the output
1510 to the bug-reporting address (e.g., in the output of cp --help):
1511 touch k; perl -e 'rename "k","/tmp/k" or print "$!(",$!+0,")\n"'
1512 where your current directory is on one partion and /tmp is the other.
1513 Also, please try to find the E* errno macro name corresponding to
1514 the diagnostic and parenthesized integer, and include that in your
1515 e-mail. One way to do that is to run a command like this
1516 find /usr/include/. -type f \
1517 | xargs grep 'define.*\<E[A-Z]*\>.*\<18\>' /dev/null
1518 where you'd replace `18' with the integer in parentheses that
1519 was output from the perl one-liner above.
1520 If necessary, of course, change `/tmp' to some other directory. */
1523 /* There are many ways this can happen due to a race condition.
1524 When something happens between the initial XSTAT and the
1525 subsequent rename, we can get many different types of errors.
1526 For example, if the destination is initially a non-directory
1527 or non-existent, but it is created as a directory, the rename
1528 fails. If two `mv' commands try to rename the same file at
1529 about the same time, one will succeed and the other will fail.
1530 If the permissions on the directory containing the source or
1531 destination file are made too restrictive, the rename will
1534 _("cannot move %s to %s"),
1535 quote_n (0, src_name
), quote_n (1, dst_name
));
1536 forget_created (src_sb
.st_ino
, src_sb
.st_dev
);
1540 /* The rename attempt has failed. Remove any existing destination
1541 file so that a cross-device `mv' acts as if it were really using
1542 the rename syscall. */
1543 if (unlink (dst_name
) != 0 && errno
!= ENOENT
)
1546 _("inter-device move failed: %s to %s; unable to remove target"),
1547 quote_n (0, src_name
), quote_n (1, dst_name
));
1548 forget_created (src_sb
.st_ino
, src_sb
.st_dev
);
1555 /* If the ownership might change, or if it is a directory (whose
1556 special mode bits may change after the directory is created),
1557 omit some permissions at first, so unauthorized users cannot nip
1558 in before the file is ready. */
1559 dst_mode_bits
= (x
->set_mode
? x
->mode
: src_mode
) & CHMOD_MODE_BITS
;
1560 omitted_permissions
=
1562 & (x
->preserve_ownership
? S_IRWXG
| S_IRWXO
1563 : S_ISDIR (src_mode
) ? S_IWGRP
| S_IWOTH
1568 if (x
->preserve_security_context
)
1570 security_context_t con
;
1572 if (0 <= lgetfilecon (src_name
, &con
))
1574 if (setfscreatecon (con
) < 0)
1577 _("failed to set default file creation context to %s"),
1579 if (x
->require_preserve_context
)
1589 if (errno
!= ENOTSUP
&& errno
!= ENODATA
)
1592 _("failed to get security context of %s"),
1594 if (x
->require_preserve_context
)
1600 /* In certain modes (cp's --symbolic-link), and for certain file types
1601 (symlinks and hard links) it doesn't make sense to preserve metadata,
1602 or it's possible to preserve only some of it.
1603 In such cases, set this variable to zero. */
1604 preserve_metadata
= true;
1606 if (S_ISDIR (src_mode
))
1608 struct dir_list
*dir
;
1610 /* If this directory has been copied before during the
1611 recursion, there is a symbolic link to an ancestor
1612 directory of the symbolic link. It is impossible to
1613 continue to copy this, unless we've got an infinite disk. */
1615 if (is_ancestor (&src_sb
, ancestors
))
1617 error (0, 0, _("cannot copy cyclic symbolic link %s"),
1622 /* Insert the current directory in the list of parents. */
1624 dir
= alloca (sizeof *dir
);
1625 dir
->parent
= ancestors
;
1626 dir
->ino
= src_sb
.st_ino
;
1627 dir
->dev
= src_sb
.st_dev
;
1629 if (new_dst
|| !S_ISDIR (dst_sb
.st_mode
))
1631 /* POSIX says mkdir's behavior is implementation-defined when
1632 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
1633 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
1634 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
1635 if (mkdir (dst_name
, dst_mode_bits
& ~omitted_permissions
) != 0)
1637 error (0, errno
, _("cannot create directory %s"),
1642 /* We need search and write permissions to the new directory
1643 for writing the directory's contents. Check if these
1644 permissions are there. */
1646 if (lstat (dst_name
, &dst_sb
) != 0)
1648 error (0, errno
, _("cannot stat %s"), quote (dst_name
));
1651 else if ((dst_sb
.st_mode
& S_IRWXU
) != S_IRWXU
)
1653 /* Make the new directory searchable and writable. */
1655 dst_mode
= dst_sb
.st_mode
;
1656 restore_dst_mode
= true;
1658 if (lchmod (dst_name
, dst_mode
| S_IRWXU
) != 0)
1660 error (0, errno
, _("setting permissions for %s"),
1666 /* Insert the created directory's inode and device
1667 numbers into the search structure, so that we can
1668 avoid copying it again. */
1670 remember_copied (dst_name
, dst_sb
.st_ino
, dst_sb
.st_dev
);
1673 emit_verbose (src_name
, dst_name
, NULL
);
1676 /* Decide whether to copy the contents of the directory. */
1677 if (x
->one_file_system
&& device
!= 0 && device
!= src_sb
.st_dev
)
1679 /* Here, we are crossing a file system boundary and cp's -x option
1680 is in effect: so don't copy the contents of this directory. */
1684 /* Copy the contents of the directory. Don't just return if
1685 this fails -- otherwise, the failure to read a single file
1686 in a source directory would cause the containing destination
1687 directory not to have owner/perms set properly. */
1688 delayed_ok
= copy_dir (src_name
, dst_name
, new_dst
, &src_sb
, dir
, x
,
1692 else if (x
->symbolic_link
)
1694 preserve_metadata
= false;
1696 if (*src_name
!= '/')
1698 /* Check that DST_NAME denotes a file in the current directory. */
1700 struct stat dst_parent_sb
;
1702 bool in_current_dir
;
1704 dst_parent
= dir_name (dst_name
);
1706 in_current_dir
= (STREQ (".", dst_parent
)
1707 /* If either stat call fails, it's ok not to report
1708 the failure and say dst_name is in the current
1709 directory. Other things will fail later. */
1710 || stat (".", &dot_sb
) != 0
1711 || stat (dst_parent
, &dst_parent_sb
) != 0
1712 || SAME_INODE (dot_sb
, dst_parent_sb
));
1715 if (! in_current_dir
)
1718 _("%s: can make relative symbolic links only in current directory"),
1723 if (symlink (src_name
, dst_name
) != 0)
1725 error (0, errno
, _("cannot create symbolic link %s to %s"),
1726 quote_n (0, dst_name
), quote_n (1, src_name
));
1731 else if (x
->hard_link
1732 #ifdef LINK_FOLLOWS_SYMLINKS
1733 /* A POSIX-conforming link syscall dereferences a symlink, yet cp,
1734 invoked with `--link --no-dereference', should not. Thus, with
1735 a POSIX-conforming link system call, we can't use link() here,
1736 since that would create a hard link to the referent (effectively
1737 dereferencing the symlink), rather than to the symlink itself.
1738 We can approximate the desired behavior by skipping this hard-link
1739 creating block and instead copying the symlink, via the `S_ISLNK'-
1741 When link operates on the symlinks themselves, we use this block
1742 and just call link(). */
1743 && !(S_ISLNK (src_mode
) && x
->dereference
== DEREF_NEVER
)
1747 preserve_metadata
= false;
1748 if (link (src_name
, dst_name
))
1750 error (0, errno
, _("cannot create link %s"), quote (dst_name
));
1754 else if (S_ISREG (src_mode
)
1755 || (x
->copy_as_regular
&& !S_ISLNK (src_mode
)))
1757 copied_as_regular
= true;
1758 /* POSIX says the permission bits of the source file must be
1759 used as the 3rd argument in the open call. Historical
1760 practice passed all the source mode bits to 'open', but the extra
1761 bits were ignored, so it should be the same either way. */
1762 if (! copy_reg (src_name
, dst_name
, x
, src_mode
& S_IRWXUGO
,
1763 omitted_permissions
, &new_dst
, &src_sb
))
1766 else if (S_ISFIFO (src_mode
))
1768 /* Use mknod, rather than mkfifo, because the former preserves
1769 the special mode bits of a fifo on Solaris 10, while mkfifo
1770 does not. But fall back on mkfifo, because on some BSD systems,
1771 mknod always fails when asked to create a FIFO. */
1772 if (mknod (dst_name
, src_mode
& ~omitted_permissions
, 0) != 0)
1774 if (mkfifo (dst_name
, src_mode
& ~S_IFIFO
& ~omitted_permissions
) != 0)
1777 error (0, errno
, _("cannot create fifo %s"), quote (dst_name
));
1781 else if (S_ISBLK (src_mode
) || S_ISCHR (src_mode
) || S_ISSOCK (src_mode
))
1783 if (mknod (dst_name
, src_mode
& ~omitted_permissions
, src_sb
.st_rdev
)
1786 error (0, errno
, _("cannot create special file %s"),
1791 else if (S_ISLNK (src_mode
))
1793 char *src_link_val
= areadlink_with_size (src_name
, src_sb
.st_size
);
1794 if (src_link_val
== NULL
)
1796 error (0, errno
, _("cannot read symbolic link %s"), quote (src_name
));
1800 if (symlink (src_link_val
, dst_name
) == 0)
1801 free (src_link_val
);
1804 int saved_errno
= errno
;
1805 bool same_link
= false;
1806 if (x
->update
&& !new_dst
&& S_ISLNK (dst_sb
.st_mode
)
1807 && dst_sb
.st_size
== strlen (src_link_val
))
1809 /* See if the destination is already the desired symlink.
1810 FIXME: This behavior isn't documented, and seems wrong
1811 in some cases, e.g., if the destination symlink has the
1812 wrong ownership, permissions, or time stamps. */
1813 char *dest_link_val
=
1814 areadlink_with_size (dst_name
, dst_sb
.st_size
);
1815 if (dest_link_val
&& STREQ (dest_link_val
, src_link_val
))
1817 free (dest_link_val
);
1819 free (src_link_val
);
1823 error (0, saved_errno
, _("cannot create symbolic link %s"),
1829 if (x
->preserve_security_context
)
1830 restore_default_fscreatecon_or_die ();
1832 /* There's no need to preserve timestamps or permissions. */
1833 preserve_metadata
= false;
1835 if (x
->preserve_ownership
)
1837 /* Preserve the owner and group of the just-`copied'
1838 symbolic link, if possible. */
1840 && lchown (dst_name
, src_sb
.st_uid
, src_sb
.st_gid
) != 0
1841 && ! chown_failure_ok (x
))
1843 error (0, errno
, _("failed to preserve ownership for %s"),
1849 /* Can't preserve ownership of symlinks.
1850 FIXME: maybe give a warning or even error for symlinks
1851 in directories with the sticky bit set -- there, not
1852 preserving owner/group is a potential security problem. */
1858 error (0, 0, _("%s has unknown file type"), quote (src_name
));
1862 if (command_line_arg
&& x
->dest_info
)
1864 /* Now that the destination file is very likely to exist,
1865 add its info to the set. */
1867 if (lstat (dst_name
, &sb
) == 0)
1868 record_file (x
->dest_info
, dst_name
, &sb
);
1871 if ( ! preserve_metadata
)
1874 if (copied_as_regular
)
1877 /* POSIX says that `cp -p' must restore the following:
1879 - setuid, setgid bits
1881 If it fails to restore any of those, we may give a warning but
1882 the destination must not be removed.
1883 FIXME: implement the above. */
1885 /* Adjust the times (and if possible, ownership) for the copy.
1886 chown turns off set[ug]id bits for non-root,
1887 so do the chmod last. */
1889 if (x
->preserve_timestamps
)
1891 struct timespec timespec
[2];
1892 timespec
[0] = get_stat_atime (&src_sb
);
1893 timespec
[1] = get_stat_mtime (&src_sb
);
1895 if (utimens (dst_name
, timespec
) != 0)
1897 error (0, errno
, _("preserving times for %s"), quote (dst_name
));
1898 if (x
->require_preserve
)
1903 /* Avoid calling chown if we know it's not necessary. */
1904 if (x
->preserve_ownership
1905 && (new_dst
|| !SAME_OWNER_AND_GROUP (src_sb
, dst_sb
)))
1907 switch (set_owner (x
, dst_name
, -1, src_sb
.st_uid
, src_sb
.st_gid
))
1913 src_mode
&= ~ (S_ISUID
| S_ISGID
| S_ISVTX
);
1918 set_author (dst_name
, -1, &src_sb
);
1920 if (x
->preserve_mode
|| x
->move_mode
)
1922 if (copy_acl (src_name
, -1, dst_name
, -1, src_mode
) != 0
1923 && x
->require_preserve
)
1926 else if (x
->set_mode
)
1928 if (set_acl (dst_name
, -1, x
->mode
) != 0)
1933 if (omitted_permissions
)
1935 omitted_permissions
&= ~ cached_umask ();
1937 if (omitted_permissions
&& !restore_dst_mode
)
1939 /* Permissions were deliberately omitted when the file
1940 was created due to security concerns. See whether
1941 they need to be re-added now. It'd be faster to omit
1942 the lstat, but deducing the current destination mode
1943 is tricky in the presence of implementation-defined
1944 rules for special mode bits. */
1945 if (new_dst
&& lstat (dst_name
, &dst_sb
) != 0)
1947 error (0, errno
, _("cannot stat %s"), quote (dst_name
));
1950 dst_mode
= dst_sb
.st_mode
;
1951 if (omitted_permissions
& ~dst_mode
)
1952 restore_dst_mode
= true;
1956 if (restore_dst_mode
)
1958 if (lchmod (dst_name
, dst_mode
| omitted_permissions
) != 0)
1960 error (0, errno
, _("preserving permissions for %s"),
1962 if (x
->require_preserve
)
1972 if (x
->preserve_security_context
)
1973 restore_default_fscreatecon_or_die ();
1975 /* We have failed to create the destination file.
1976 If we've just added a dev/ino entry via the remember_copied
1977 call above (i.e., unless we've just failed to create a hard link),
1978 remove the entry associating the source dev/ino with the
1979 destination file name, so we don't try to `preserve' a link
1980 to a file we didn't create. */
1981 if (earlier_file
== NULL
)
1982 forget_created (src_sb
.st_ino
, src_sb
.st_dev
);
1986 if (rename (dst_backup
, dst_name
) != 0)
1987 error (0, errno
, _("cannot un-backup %s"), quote (dst_name
));
1991 printf (_("%s -> %s (unbackup)\n"),
1992 quote_n (0, dst_backup
), quote_n (1, dst_name
));
1999 valid_options (const struct cp_options
*co
)
2001 assert (co
!= NULL
);
2002 assert (VALID_BACKUP_TYPE (co
->backup_type
));
2003 assert (VALID_SPARSE_MODE (co
->sparse_mode
));
2004 assert (!(co
->hard_link
&& co
->symbolic_link
));
2008 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
2009 any type. NONEXISTENT_DST should be true if the file DST_NAME
2010 is known not to exist (e.g., because its parent directory was just
2011 created); NONEXISTENT_DST should be false if DST_NAME might already
2012 exist. OPTIONS is ... FIXME-describe
2013 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
2014 same as) DST_NAME; otherwise, set clear it.
2015 Return true if successful. */
2018 copy (char const *src_name
, char const *dst_name
,
2019 bool nonexistent_dst
, const struct cp_options
*options
,
2020 bool *copy_into_self
, bool *rename_succeeded
)
2022 assert (valid_options (options
));
2024 /* Record the file names: they're used in case of error, when copying
2025 a directory into itself. I don't like to make these tools do *any*
2026 extra work in the common case when that work is solely to handle
2027 exceptional cases, but in this case, I don't see a way to derive the
2028 top level source and destination directory names where they're used.
2029 An alternative is to use COPY_INTO_SELF and print the diagnostic
2030 from every caller -- but I don't want to do that. */
2031 top_level_src_name
= src_name
;
2032 top_level_dst_name
= dst_name
;
2034 return copy_internal (src_name
, dst_name
, nonexistent_dst
, 0, NULL
,
2035 options
, true, copy_into_self
, rename_succeeded
);
2038 /* Return true if this process has appropriate privileges to chown a
2039 file whose owner is not the effective user ID. */
2042 chown_privileges (void)
2044 #ifdef PRIV_FILE_CHOWN
2046 priv_set_t
*pset
= priv_allocset ();
2049 result
= (getppriv (PRIV_EFFECTIVE
, pset
) == 0
2050 && priv_ismember (pset
, PRIV_FILE_CHOWN
));
2051 priv_freeset (pset
);
2054 return (geteuid () == 0);
2058 /* Return true if it's OK for chown to fail, where errno is
2059 the error number that chown failed with and X is the copying
2063 chown_failure_ok (struct cp_options
const *x
)
2065 /* If non-root uses -p, it's ok if we can't preserve ownership.
2066 But root probably wants to know, e.g. if NFS disallows it,
2067 or if the target system doesn't support file ownership. */
2069 return ((errno
== EPERM
|| errno
== EINVAL
) && !x
->chown_privileges
);
2072 /* Return the user's umask, caching the result. */
2077 static mode_t mask
= (mode_t
) -1;
2078 if (mask
== (mode_t
) -1)