1 /* copy.c -- core functions for copying files and directories
2 Copyright (C) 89, 90, 91, 1995-2009 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 /* Extracted from cp.c and librarified by Jim Meyering. */
22 #include <sys/types.h>
23 #include <selinux/selinux.h>
34 #include "backupfile.h"
35 #include "buffer-lcm.h"
42 #include "filenamecat.h"
43 #include "full-write.h"
45 #include "hash-triple.h"
46 #include "ignore-value.h"
50 #include "stat-time.h"
53 #include "write-any-file.h"
54 #include "areadlink.h"
58 # include <attr/error_context.h>
59 # include <attr/libattr.h>
65 # define HAVE_FCHOWN false
66 # define fchown(fd, uid, gid) (-1)
70 # define HAVE_LCHOWN false
71 # define lchown(name, uid, gid) chown (name, uid, gid)
76 rpl_mkfifo (char const *file
, mode_t mode
)
81 # define mkfifo rpl_mkfifo
88 #define SAME_OWNER(A, B) ((A).st_uid == (B).st_uid)
89 #define SAME_GROUP(A, B) ((A).st_gid == (B).st_gid)
90 #define SAME_OWNER_AND_GROUP(A, B) (SAME_OWNER (A, B) && SAME_GROUP (A, B))
94 struct dir_list
*parent
;
99 /* Initial size of the cp.dest_info hash table. */
100 #define DEST_INFO_INITIAL_CAPACITY 61
102 static bool copy_internal (char const *src_name
, char const *dst_name
,
103 bool new_dst
, dev_t device
,
104 struct dir_list
*ancestors
,
105 const struct cp_options
*x
,
106 bool command_line_arg
,
107 bool *first_dir_created_per_command_line_arg
,
108 bool *copy_into_self
,
109 bool *rename_succeeded
);
110 static bool owner_failure_ok (struct cp_options
const *x
);
112 /* Pointers to the file names: they're used in the diagnostic that is issued
113 when we detect the user is trying to copy a directory into itself. */
114 static char const *top_level_src_name
;
115 static char const *top_level_dst_name
;
117 /* FIXME: describe */
118 /* FIXME: rewrite this to use a hash table so we avoid the quadratic
119 performance hit that's probably noticeable only on trees deeper
120 than a few hundred levels. See use of active_dir_map in remove.c */
123 is_ancestor (const struct stat
*sb
, const struct dir_list
*ancestors
)
125 while (ancestors
!= 0)
127 if (ancestors
->ino
== sb
->st_ino
&& ancestors
->dev
== sb
->st_dev
)
129 ancestors
= ancestors
->parent
;
135 errno_unsupported (int err
)
137 return err
== ENOTSUP
|| err
== ENODATA
;
142 copy_attr_error (struct error_context
*ctx ATTRIBUTE_UNUSED
,
143 char const *fmt
, ...)
148 if (!errno_unsupported (errno
))
149 if (errno
!= ENOTSUP
&& errno
!= ENODATA
)
151 /* use verror module to print error message */
153 verror (0, err
, fmt
, ap
);
159 copy_attr_allerror (struct error_context
*ctx ATTRIBUTE_UNUSED
,
160 char const *fmt
, ...)
165 /* use verror module to print error message */
167 verror (0, err
, fmt
, ap
);
172 copy_attr_quote (struct error_context
*ctx ATTRIBUTE_UNUSED
, char const *str
)
178 copy_attr_free (struct error_context
*ctx ATTRIBUTE_UNUSED
,
179 char const *str ATTRIBUTE_UNUSED
)
184 copy_attr_by_fd (char const *src_path
, int src_fd
,
185 char const *dst_path
, int dst_fd
, const struct cp_options
*x
)
187 struct error_context ctx
=
189 .error
= x
->require_preserve_xattr
? copy_attr_allerror
: copy_attr_error
,
190 .quote
= copy_attr_quote
,
191 .quote_free
= copy_attr_free
193 return 0 == attr_copy_fd (src_path
, src_fd
, dst_path
, dst_fd
, 0,
194 (x
->reduce_diagnostics
195 && !x
->require_preserve_xattr
)? NULL
: &ctx
);
199 copy_attr_by_name (char const *src_path
, char const *dst_path
,
200 const struct cp_options
*x
)
202 struct error_context ctx
=
204 .error
= x
->require_preserve_xattr
? copy_attr_allerror
: copy_attr_error
,
205 .quote
= copy_attr_quote
,
206 .quote_free
= copy_attr_free
208 return 0 == attr_copy_file (src_path
, dst_path
, 0,
209 (x
-> reduce_diagnostics
210 && !x
->require_preserve_xattr
) ? NULL
: &ctx
);
212 #else /* USE_XATTR */
215 copy_attr_by_fd (char const *src_path
, int src_fd
,
216 char const *dst_path
, int dst_fd
, const struct cp_options
*x
)
222 copy_attr_by_name (char const *src_path
, char const *dst_path
,
223 const struct cp_options
*x
)
227 #endif /* USE_XATTR */
229 /* Read the contents of the directory SRC_NAME_IN, and recursively
230 copy the contents to DST_NAME_IN. NEW_DST is true if
231 DST_NAME_IN is a directory that was created previously in the
232 recursion. SRC_SB and ANCESTORS describe SRC_NAME_IN.
233 Set *COPY_INTO_SELF if SRC_NAME_IN is a parent of
234 FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG FIXME
235 (or the same as) DST_NAME_IN; otherwise, clear it.
236 Return true if successful. */
239 copy_dir (char const *src_name_in
, char const *dst_name_in
, bool new_dst
,
240 const struct stat
*src_sb
, struct dir_list
*ancestors
,
241 const struct cp_options
*x
,
242 bool *first_dir_created_per_command_line_arg
,
243 bool *copy_into_self
)
247 struct cp_options non_command_line_options
= *x
;
250 name_space
= savedir (src_name_in
);
251 if (name_space
== NULL
)
253 /* This diagnostic is a bit vague because savedir can fail in
254 several different ways. */
255 error (0, errno
, _("cannot access %s"), quote (src_name_in
));
259 /* For cp's -H option, dereference command line arguments, but do not
260 dereference symlinks that are found via recursive traversal. */
261 if (x
->dereference
== DEREF_COMMAND_LINE_ARGUMENTS
)
262 non_command_line_options
.dereference
= DEREF_NEVER
;
265 while (*namep
!= '\0')
267 bool local_copy_into_self
;
268 char *src_name
= file_name_concat (src_name_in
, namep
, NULL
);
269 char *dst_name
= file_name_concat (dst_name_in
, namep
, NULL
);
271 ok
&= copy_internal (src_name
, dst_name
, new_dst
, src_sb
->st_dev
,
272 ancestors
, &non_command_line_options
, false,
273 first_dir_created_per_command_line_arg
,
274 &local_copy_into_self
, NULL
);
275 *copy_into_self
|= local_copy_into_self
;
280 /* If we're copying into self, there's no point in continuing,
281 and in fact, that would even infloop, now that we record only
282 the first created directory per command line argument. */
283 if (local_copy_into_self
)
286 namep
+= strlen (namep
) + 1;
292 /* Set the owner and owning group of DEST_DESC to the st_uid and
293 st_gid fields of SRC_SB. If DEST_DESC is undefined (-1), set
294 the owner and owning group of DST_NAME instead; for
295 safety prefer lchown if the system supports it since no
296 symbolic links should be involved. DEST_DESC must
297 refer to the same file as DEST_NAME if defined.
298 Upon failure to set both UID and GID, try to set only the GID.
299 NEW_DST is true if the file was newly created; otherwise,
300 DST_SB is the status of the destination.
301 Return 1 if the initial syscall succeeds, 0 if it fails but it's OK
302 not to preserve ownership, -1 otherwise. */
305 set_owner (const struct cp_options
*x
, char const *dst_name
, int dest_desc
,
306 struct stat
const *src_sb
, bool new_dst
,
307 struct stat
const *dst_sb
)
309 uid_t uid
= src_sb
->st_uid
;
310 gid_t gid
= src_sb
->st_gid
;
312 /* Naively changing the ownership of an already-existing file before
313 changing its permissions would create a window of vulnerability if
314 the file's old permissions are too generous for the new owner and
315 group. Avoid the window by first changing to a restrictive
316 temporary mode if necessary. */
318 if (!new_dst
&& (x
->preserve_mode
| x
->move_mode
| x
->set_mode
))
320 mode_t old_mode
= dst_sb
->st_mode
;
322 (x
->preserve_mode
| x
->move_mode
? src_sb
->st_mode
: x
->mode
);
323 mode_t restrictive_temp_mode
= old_mode
& new_mode
& S_IRWXU
;
326 || (old_mode
& CHMOD_MODE_BITS
327 & (~new_mode
| S_ISUID
| S_ISGID
| S_ISVTX
)))
328 && qset_acl (dst_name
, dest_desc
, restrictive_temp_mode
) != 0)
330 if (! owner_failure_ok (x
))
331 error (0, errno
, _("clearing permissions for %s"), quote (dst_name
));
332 return -x
->require_preserve
;
336 if (HAVE_FCHOWN
&& dest_desc
!= -1)
338 if (fchown (dest_desc
, uid
, gid
) == 0)
340 if (errno
== EPERM
|| errno
== EINVAL
)
342 /* We've failed to set *both*. Now, try to set just the group
343 ID, but ignore any failure here, and don't change errno. */
344 int saved_errno
= errno
;
345 ignore_value (fchown (dest_desc
, -1, gid
));
351 if (lchown (dst_name
, uid
, gid
) == 0)
353 if (errno
== EPERM
|| errno
== EINVAL
)
355 /* We've failed to set *both*. Now, try to set just the group
356 ID, but ignore any failure here, and don't change errno. */
357 int saved_errno
= errno
;
358 ignore_value (lchown (dst_name
, -1, gid
));
363 if (! chown_failure_ok (x
))
365 error (0, errno
, _("failed to preserve ownership for %s"),
367 if (x
->require_preserve
)
374 /* Set the st_author field of DEST_DESC to the st_author field of
375 SRC_SB. If DEST_DESC is undefined (-1), set the st_author field
376 of DST_NAME instead. DEST_DESC must refer to the same file as
377 DEST_NAME if defined. */
380 set_author (const char *dst_name
, int dest_desc
, const struct stat
*src_sb
)
382 #if HAVE_STRUCT_STAT_ST_AUTHOR
383 /* FIXME: Modify the following code so that it does not
384 follow symbolic links. */
386 /* Preserve the st_author field. */
387 file_t file
= (dest_desc
< 0
388 ? file_name_lookup (dst_name
, 0, 0)
389 : getdport (dest_desc
));
390 if (file
== MACH_PORT_NULL
)
391 error (0, errno
, _("failed to lookup file %s"), quote (dst_name
));
394 error_t err
= file_chauthor (file
, src_sb
->st_author
);
396 error (0, err
, _("failed to preserve authorship for %s"),
398 mach_port_deallocate (mach_task_self (), file
);
407 /* Change the file mode bits of the file identified by DESC or NAME to MODE.
408 Use DESC if DESC is valid and fchmod is available, NAME otherwise. */
411 fchmod_or_lchmod (int desc
, char const *name
, mode_t mode
)
415 return fchmod (desc
, mode
);
417 return lchmod (name
, mode
);
420 /* Copy a regular file from SRC_NAME to DST_NAME.
421 If the source file contains holes, copies holes and blocks of zeros
422 in the source file as holes in the destination file.
423 (Holes are read as zeroes by the `read' system call.)
424 When creating the destination, use DST_MODE & ~OMITTED_PERMISSIONS
425 as the third argument in the call to open, adding
426 OMITTED_PERMISSIONS after copying as needed.
427 X provides many option settings.
428 Return true if successful.
429 *NEW_DST is as in copy_internal.
430 SRC_SB is the result of calling XSTAT (aka stat) on SRC_NAME. */
433 copy_reg (char const *src_name
, char const *dst_name
,
434 const struct cp_options
*x
,
435 mode_t dst_mode
, mode_t omitted_permissions
, bool *new_dst
,
436 struct stat
const *src_sb
)
439 char *buf_alloc
= NULL
;
440 char *name_alloc
= NULL
;
444 mode_t src_mode
= src_sb
->st_mode
;
446 struct stat src_open_sb
;
447 bool return_val
= true;
449 source_desc
= open (src_name
,
451 | (x
->dereference
== DEREF_NEVER
? O_NOFOLLOW
: 0)));
454 error (0, errno
, _("cannot open %s for reading"), quote (src_name
));
458 if (fstat (source_desc
, &src_open_sb
) != 0)
460 error (0, errno
, _("cannot fstat %s"), quote (src_name
));
465 /* Compare the source dev/ino from the open file to the incoming,
466 saved ones obtained via a previous call to stat. */
467 if (! SAME_INODE (*src_sb
, src_open_sb
))
470 _("skipping file %s, as it was replaced while being copied"),
476 /* The semantics of the following open calls are mandated
477 by the specs for both cp and mv. */
480 dest_desc
= open (dst_name
, O_WRONLY
| O_TRUNC
| O_BINARY
);
483 /* When using cp --preserve=context to copy to an existing destination,
484 use the default context rather than that of the source. Why?
485 1) the src context may prohibit writing, and
486 2) because it's more consistent to use the same context
487 that is used when the destination file doesn't already exist. */
488 if (x
->preserve_security_context
&& 0 <= dest_desc
)
490 security_context_t con
= NULL
;
491 if (getfscreatecon (&con
) < 0)
493 if (!x
->reduce_diagnostics
|| x
->require_preserve_context
)
494 error (0, errno
, _("failed to get file system create context"));
495 if (x
->require_preserve_context
)
498 goto close_src_and_dst_desc
;
504 if (fsetfilecon (dest_desc
, con
) < 0)
506 if (!x
->reduce_diagnostics
|| x
->require_preserve_context
)
508 _("failed to set the security context of %s to %s"),
509 quote_n (0, dst_name
), quote_n (1, con
));
510 if (x
->require_preserve_context
)
514 goto close_src_and_dst_desc
;
521 if (dest_desc
< 0 && x
->unlink_dest_after_failed_open
)
523 if (unlink (dst_name
) != 0)
525 error (0, errno
, _("cannot remove %s"), quote (dst_name
));
530 printf (_("removed %s\n"), quote (dst_name
));
532 /* Tell caller that the destination file was unlinked. */
539 int open_flags
= O_WRONLY
| O_CREAT
| O_BINARY
;
540 dest_desc
= open (dst_name
, open_flags
| O_EXCL
,
541 dst_mode
& ~omitted_permissions
);
544 /* When trying to copy through a dangling destination symlink,
545 the above open fails with EEXIST. If that happens, and
546 lstat'ing the DST_NAME shows that it is a symlink, then we
547 have a problem: trying to resolve this dangling symlink to
548 a directory/destination-entry pair is fundamentally racy,
549 so punt. If POSIXLY_CORRECT is set, simply call open again,
550 but without O_EXCL (potentially dangerous). If not, fail
551 with a diagnostic. These shenanigans are necessary only
552 when copying, i.e., not in move_mode. */
553 if (dest_desc
< 0 && dest_errno
== EEXIST
&& ! x
->move_mode
)
555 struct stat dangling_link_sb
;
556 if (lstat (dst_name
, &dangling_link_sb
) == 0
557 && S_ISLNK (dangling_link_sb
.st_mode
))
559 if (x
->open_dangling_dest_symlink
)
561 dest_desc
= open (dst_name
, open_flags
,
562 dst_mode
& ~omitted_permissions
);
567 error (0, 0, _("not writing through dangling symlink %s"),
576 omitted_permissions
= 0;
580 error (0, dest_errno
, _("cannot create regular file %s"),
586 if (fstat (dest_desc
, &sb
) != 0)
588 error (0, errno
, _("cannot fstat %s"), quote (dst_name
));
590 goto close_src_and_dst_desc
;
594 typedef uintptr_t word
;
595 off_t n_read_total
= 0;
597 /* Choose a suitable buffer size; it may be adjusted later. */
598 size_t buf_alignment
= lcm (getpagesize (), sizeof (word
));
599 size_t buf_alignment_slop
= sizeof (word
) + buf_alignment
- 1;
600 size_t buf_size
= io_blksize (sb
);
602 /* Deal with sparse files. */
603 bool last_write_made_hole
= false;
604 bool make_holes
= false;
606 if (S_ISREG (sb
.st_mode
))
608 /* Even with --sparse=always, try to create holes only
609 if the destination is a regular file. */
610 if (x
->sparse_mode
== SPARSE_ALWAYS
)
613 #if HAVE_STRUCT_STAT_ST_BLOCKS
614 /* Use a heuristic to determine whether SRC_NAME contains any sparse
615 blocks. If the file has fewer blocks than would normally be
616 needed for a file of its size, then at least one of the blocks in
617 the file is a hole. */
618 if (x
->sparse_mode
== SPARSE_AUTO
&& S_ISREG (src_open_sb
.st_mode
)
619 && ST_NBLOCKS (src_open_sb
) < src_open_sb
.st_size
/ ST_NBLOCKSIZE
)
624 /* If not making a sparse file, try to use a more-efficient
628 /* Compute the least common multiple of the input and output
629 buffer sizes, adjusting for outlandish values. */
630 size_t blcm_max
= MIN (SIZE_MAX
, SSIZE_MAX
) - buf_alignment_slop
;
631 size_t blcm
= buffer_lcm (io_blksize (src_open_sb
), buf_size
,
634 /* Do not bother with a buffer larger than the input file, plus one
635 byte to make sure the file has not grown while reading it. */
636 if (S_ISREG (src_open_sb
.st_mode
) && src_open_sb
.st_size
< buf_size
)
637 buf_size
= src_open_sb
.st_size
+ 1;
639 /* However, stick with a block size that is a positive multiple of
640 blcm, overriding the above adjustments. Watch out for
642 buf_size
+= blcm
- 1;
643 buf_size
-= buf_size
% blcm
;
644 if (buf_size
== 0 || blcm_max
< buf_size
)
648 /* Make a buffer with space for a sentinel at the end. */
649 buf_alloc
= xmalloc (buf_size
+ buf_alignment_slop
);
650 buf
= ptr_align (buf_alloc
, buf_alignment
);
656 ssize_t n_read
= read (source_desc
, buf
, buf_size
);
663 error (0, errno
, _("reading %s"), quote (src_name
));
665 goto close_src_and_dst_desc
;
670 n_read_total
+= n_read
;
676 /* Sentinel to stop loop. */
679 /* Usually, buf[n_read] is not the byte just before a "word"
680 (aka uintptr_t) boundary. In that case, the word-oriented
681 test below (*wp++ == 0) would read some uninitialized bytes
682 after the sentinel. To avoid false-positive reports about
683 this condition (e.g., from a tool like valgrind), set the
684 remaining bytes -- to any value. */
685 memset (buf
+ n_read
+ 1, 0, sizeof (word
) - 1);
688 /* Find first nonzero *word*, or the word with the sentinel. */
694 /* Find the first nonzero *byte*, or the sentinel. */
696 cp
= (char *) (wp
- 1);
700 if (cp
<= buf
+ n_read
)
701 /* Clear to indicate that a normal write is needed. */
705 /* We found the sentinel, so the whole input block was zero.
707 if (lseek (dest_desc
, n_read
, SEEK_CUR
) < 0)
709 error (0, errno
, _("cannot lseek %s"), quote (dst_name
));
711 goto close_src_and_dst_desc
;
713 last_write_made_hole
= true;
720 if (full_write (dest_desc
, buf
, n
) != n
)
722 error (0, errno
, _("writing %s"), quote (dst_name
));
724 goto close_src_and_dst_desc
;
726 last_write_made_hole
= false;
728 /* It is tempting to return early here upon a short read from a
729 regular file. That would save the final read syscall for each
730 file. Unfortunately that doesn't work for certain files in
731 /proc with linux kernels from at least 2.6.9 .. 2.6.29. */
735 /* If the file ends with a `hole', we need to do something to record
736 the length of the file. On modern systems, calling ftruncate does
737 the job. On systems without native ftruncate support, we have to
738 write a byte at the ending position. Otherwise the kernel would
739 truncate the file at the end of the last write operation. */
741 if (last_write_made_hole
)
744 ? /* ftruncate sets the file size,
745 so there is no need for a write. */
746 ftruncate (dest_desc
, n_read_total
) < 0
747 : /* Seek backwards one character and write a null. */
748 (lseek (dest_desc
, (off_t
) -1, SEEK_CUR
) < 0L
749 || full_write (dest_desc
, "", 1) != 1))
751 error (0, errno
, _("writing %s"), quote (dst_name
));
753 goto close_src_and_dst_desc
;
758 if (x
->preserve_timestamps
)
760 struct timespec timespec
[2];
761 timespec
[0] = get_stat_atime (src_sb
);
762 timespec
[1] = get_stat_mtime (src_sb
);
764 if (gl_futimens (dest_desc
, dst_name
, timespec
) != 0)
766 error (0, errno
, _("preserving times for %s"), quote (dst_name
));
767 if (x
->require_preserve
)
770 goto close_src_and_dst_desc
;
775 if (x
->preserve_ownership
&& ! SAME_OWNER_AND_GROUP (*src_sb
, sb
))
777 switch (set_owner (x
, dst_name
, dest_desc
, src_sb
, *new_dst
, &sb
))
781 goto close_src_and_dst_desc
;
784 src_mode
&= ~ (S_ISUID
| S_ISGID
| S_ISVTX
);
789 set_author (dst_name
, dest_desc
, src_sb
);
791 if (x
->preserve_xattr
&& ! copy_attr_by_fd (src_name
, source_desc
,
792 dst_name
, dest_desc
, x
)
793 && x
->require_preserve_xattr
)
796 if (x
->preserve_mode
|| x
->move_mode
)
798 if (copy_acl (src_name
, source_desc
, dst_name
, dest_desc
, src_mode
) != 0
799 && x
->require_preserve
)
802 else if (x
->set_mode
)
804 if (set_acl (dst_name
, dest_desc
, x
->mode
) != 0)
807 else if (omitted_permissions
)
809 omitted_permissions
&= ~ cached_umask ();
810 if (omitted_permissions
811 && fchmod_or_lchmod (dest_desc
, dst_name
, dst_mode
) != 0)
813 error (0, errno
, _("preserving permissions for %s"),
815 if (x
->require_preserve
)
820 close_src_and_dst_desc
:
821 if (close (dest_desc
) < 0)
823 error (0, errno
, _("closing %s"), quote (dst_name
));
827 if (close (source_desc
) < 0)
829 error (0, errno
, _("closing %s"), quote (src_name
));
838 /* Return true if it's ok that the source and destination
839 files are the `same' by some measure. The goal is to avoid
840 making the `copy' operation remove both copies of the file
841 in that case, while still allowing the user to e.g., move or
842 copy a regular file onto a symlink that points to it.
843 Try to minimize the cost of this function in the common case.
844 Set *RETURN_NOW if we've determined that the caller has no more
845 work to do and should return successfully, right away.
847 Set *UNLINK_SRC if we've determined that the caller wants to do
848 `rename (a, b)' where `a' and `b' are distinct hard links to the same
849 file. In that case, the caller should try to unlink `a' and then return
850 successfully. Ideally, we wouldn't have to do that, and we'd be
851 able to rely on rename to remove the source file. However, POSIX
852 mistakenly requires that such a rename call do *nothing* and return
856 same_file_ok (char const *src_name
, struct stat
const *src_sb
,
857 char const *dst_name
, struct stat
const *dst_sb
,
858 const struct cp_options
*x
, bool *return_now
, bool *unlink_src
)
860 const struct stat
*src_sb_link
;
861 const struct stat
*dst_sb_link
;
862 struct stat tmp_dst_sb
;
863 struct stat tmp_src_sb
;
866 bool same
= SAME_INODE (*src_sb
, *dst_sb
);
871 /* FIXME: this should (at the very least) be moved into the following
872 if-block. More likely, it should be removed, because it inhibits
873 making backups. But removing it will result in a change in behavior
874 that will probably have to be documented -- and tests will have to
876 if (same
&& x
->hard_link
)
882 if (x
->dereference
== DEREF_NEVER
)
886 /* If both the source and destination files are symlinks (and we'll
887 know this here IFF preserving symlinks), then it's ok -- as long
888 as they are distinct. */
889 if (S_ISLNK (src_sb
->st_mode
) && S_ISLNK (dst_sb
->st_mode
))
890 return ! same_name (src_name
, dst_name
);
892 src_sb_link
= src_sb
;
893 dst_sb_link
= dst_sb
;
900 if (lstat (dst_name
, &tmp_dst_sb
) != 0
901 || lstat (src_name
, &tmp_src_sb
) != 0)
904 src_sb_link
= &tmp_src_sb
;
905 dst_sb_link
= &tmp_dst_sb
;
907 same_link
= SAME_INODE (*src_sb_link
, *dst_sb_link
);
909 /* If both are symlinks, then it's ok, but only if the destination
910 will be unlinked before being opened. This is like the test
911 above, but with the addition of the unlink_dest_before_opening
912 conjunct because otherwise, with two symlinks to the same target,
913 we'd end up truncating the source file. */
914 if (S_ISLNK (src_sb_link
->st_mode
) && S_ISLNK (dst_sb_link
->st_mode
)
915 && x
->unlink_dest_before_opening
)
919 /* The backup code ensures there's a copy, so it's usually ok to
920 remove any destination file. One exception is when both
921 source and destination are the same directory entry. In that
922 case, moving the destination file aside (in making the backup)
923 would also rename the source file and result in an error. */
924 if (x
->backup_type
!= no_backups
)
928 /* In copy mode when dereferencing symlinks, if the source is a
929 symlink and the dest is not, then backing up the destination
930 (moving it aside) would make it a dangling symlink, and the
931 subsequent attempt to open it in copy_reg would fail with
932 a misleading diagnostic. Avoid that by returning zero in
933 that case so the caller can make cp (or mv when it has to
934 resort to reading the source file) fail now. */
936 /* FIXME-note: even with the following kludge, we can still provoke
937 the offending diagnostic. It's just a little harder to do :-)
938 $ rm -f a b c; touch c; ln -s c b; ln -s b a; cp -b a b
939 cp: cannot open `a' for reading: No such file or directory
940 That's misleading, since a subsequent `ls' shows that `a'
942 One solution would be to open the source file *before* moving
943 aside the destination, but that'd involve a big rewrite. */
945 && x
->dereference
!= DEREF_NEVER
946 && S_ISLNK (src_sb_link
->st_mode
)
947 && ! S_ISLNK (dst_sb_link
->st_mode
))
953 return ! same_name (src_name
, dst_name
);
957 /* FIXME: use or remove */
959 /* If we're making a backup, we'll detect the problem case in
960 copy_reg because SRC_NAME will no longer exist. Allowing
961 the test to be deferred lets cp do some useful things.
962 But when creating hardlinks and SRC_NAME is a symlink
963 but DST_NAME is not we must test anyway. */
965 || !S_ISLNK (src_sb_link
->st_mode
)
966 || S_ISLNK (dst_sb_link
->st_mode
))
969 if (x
->dereference
!= DEREF_NEVER
)
973 /* They may refer to the same file if we're in move mode and the
974 target is a symlink. That is ok, since we remove any existing
975 destination file before opening it -- via `rename' if they're on
976 the same file system, via `unlink (DST_NAME)' otherwise.
977 It's also ok if they're distinct hard links to the same file. */
978 if (x
->move_mode
|| x
->unlink_dest_before_opening
)
980 if (S_ISLNK (dst_sb_link
->st_mode
))
984 && 1 < dst_sb_link
->st_nlink
985 && ! same_name (src_name
, dst_name
))
996 /* If neither is a symlink, then it's ok as long as they aren't
997 hard links to the same file. */
998 if (!S_ISLNK (src_sb_link
->st_mode
) && !S_ISLNK (dst_sb_link
->st_mode
))
1000 if (!SAME_INODE (*src_sb_link
, *dst_sb_link
))
1003 /* If they are the same file, it's ok if we're making hard links. */
1011 /* It's ok to remove a destination symlink. But that works only when we
1012 unlink before opening the destination and when the source and destination
1013 files are on the same partition. */
1014 if (x
->unlink_dest_before_opening
1015 && S_ISLNK (dst_sb_link
->st_mode
))
1016 return dst_sb_link
->st_dev
== src_sb_link
->st_dev
;
1018 if (x
->dereference
== DEREF_NEVER
)
1020 if ( ! S_ISLNK (src_sb_link
->st_mode
))
1021 tmp_src_sb
= *src_sb_link
;
1022 else if (stat (src_name
, &tmp_src_sb
) != 0)
1025 if ( ! S_ISLNK (dst_sb_link
->st_mode
))
1026 tmp_dst_sb
= *dst_sb_link
;
1027 else if (stat (dst_name
, &tmp_dst_sb
) != 0)
1030 if ( ! SAME_INODE (tmp_src_sb
, tmp_dst_sb
))
1033 /* FIXME: shouldn't this be testing whether we're making symlinks? */
1044 /* Return true if FILE, with mode MODE, is writable in the sense of 'mv'.
1045 Always consider a symbolic link to be writable. */
1047 writable_destination (char const *file
, mode_t mode
)
1049 return (S_ISLNK (mode
)
1050 || can_write_any_file ()
1051 || euidaccess (file
, W_OK
) == 0);
1055 overwrite_prompt (char const *dst_name
, struct stat
const *dst_sb
)
1057 if (! writable_destination (dst_name
, dst_sb
->st_mode
))
1059 char perms
[12]; /* "-rwxrwxrwx " ls-style modes. */
1060 strmode (dst_sb
->st_mode
, perms
);
1063 _("%s: try to overwrite %s, overriding mode %04lo (%s)? "),
1064 program_name
, quote (dst_name
),
1065 (unsigned long int) (dst_sb
->st_mode
& CHMOD_MODE_BITS
),
1070 fprintf (stderr
, _("%s: overwrite %s? "),
1071 program_name
, quote (dst_name
));
1075 /* Initialize the hash table implementing a set of F_triple entries
1076 corresponding to destination files. */
1078 dest_info_init (struct cp_options
*x
)
1081 = hash_initialize (DEST_INFO_INITIAL_CAPACITY
,
1088 /* Initialize the hash table implementing a set of F_triple entries
1089 corresponding to source files listed on the command line. */
1091 src_info_init (struct cp_options
*x
)
1094 /* Note that we use triple_hash_no_name here.
1095 Contrast with the use of triple_hash above.
1096 That is necessary because a source file may be specified
1097 in many different ways. We want to warn about this
1103 = hash_initialize (DEST_INFO_INITIAL_CAPACITY
,
1105 triple_hash_no_name
,
1110 /* When effecting a move (e.g., for mv(1)), and given the name DST_NAME
1111 of the destination and a corresponding stat buffer, DST_SB, return
1112 true if the logical `move' operation should _not_ proceed.
1113 Otherwise, return false.
1114 Depending on options specified in X, this code may issue an
1115 interactive prompt asking whether it's ok to overwrite DST_NAME. */
1117 abandon_move (const struct cp_options
*x
,
1118 char const *dst_name
,
1119 struct stat
const *dst_sb
)
1121 assert (x
->move_mode
);
1122 return (x
->interactive
== I_ALWAYS_NO
1123 || ((x
->interactive
== I_ASK_USER
1124 || (x
->interactive
== I_UNSPECIFIED
1126 && ! writable_destination (dst_name
, dst_sb
->st_mode
)))
1127 && (overwrite_prompt (dst_name
, dst_sb
), 1)
1131 /* Print --verbose output on standard output, e.g. `new' -> `old'.
1132 If BACKUP_DST_NAME is non-NULL, then also indicate that it is
1133 the name of a backup file. */
1135 emit_verbose (char const *src
, char const *dst
, char const *backup_dst_name
)
1137 printf ("%s -> %s", quote_n (0, src
), quote_n (1, dst
));
1138 if (backup_dst_name
)
1139 printf (_(" (backup: %s)"), quote (backup_dst_name
));
1143 /* A wrapper around "setfscreatecon (NULL)" that exits upon failure. */
1145 restore_default_fscreatecon_or_die (void)
1147 if (setfscreatecon (NULL
) != 0)
1148 error (EXIT_FAILURE
, errno
,
1149 _("failed to restore the default file creation context"));
1152 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
1153 any type. NEW_DST should be true if the file DST_NAME cannot
1154 exist because its parent directory was just created; NEW_DST should
1155 be false if DST_NAME might already exist. DEVICE is the device
1156 number of the parent directory, or 0 if the parent of this file is
1157 not known. ANCESTORS points to a linked, null terminated list of
1158 devices and inodes of parent directories of SRC_NAME. COMMAND_LINE_ARG
1159 is true iff SRC_NAME was specified on the command line.
1160 FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG is both input and output.
1161 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
1162 same as) DST_NAME; otherwise, clear it.
1163 Return true if successful. */
1165 copy_internal (char const *src_name
, char const *dst_name
,
1168 struct dir_list
*ancestors
,
1169 const struct cp_options
*x
,
1170 bool command_line_arg
,
1171 bool *first_dir_created_per_command_line_arg
,
1172 bool *copy_into_self
,
1173 bool *rename_succeeded
)
1178 mode_t dst_mode
IF_LINT (= 0);
1179 mode_t dst_mode_bits
;
1180 mode_t omitted_permissions
;
1181 bool restore_dst_mode
= false;
1182 char *earlier_file
= NULL
;
1183 char *dst_backup
= NULL
;
1184 bool backup_succeeded
= false;
1186 bool copied_as_regular
= false;
1187 bool preserve_metadata
;
1188 bool have_dst_lstat
= false;
1190 if (x
->move_mode
&& rename_succeeded
)
1191 *rename_succeeded
= false;
1193 *copy_into_self
= false;
1195 if (XSTAT (x
, src_name
, &src_sb
) != 0)
1197 error (0, errno
, _("cannot stat %s"), quote (src_name
));
1201 src_mode
= src_sb
.st_mode
;
1203 if (S_ISDIR (src_mode
) && !x
->recursive
)
1205 error (0, 0, _("omitting directory %s"), quote (src_name
));
1209 /* Detect the case in which the same source file appears more than
1210 once on the command line and no backup option has been selected.
1211 If so, simply warn and don't copy it the second time.
1212 This check is enabled only if x->src_info is non-NULL. */
1213 if (command_line_arg
)
1215 if ( ! S_ISDIR (src_sb
.st_mode
)
1216 && x
->backup_type
== no_backups
1217 && seen_file (x
->src_info
, src_name
, &src_sb
))
1219 error (0, 0, _("warning: source file %s specified more than once"),
1224 record_file (x
->src_info
, src_name
, &src_sb
);
1229 /* Regular files can be created by writing through symbolic
1230 links, but other files cannot. So use stat on the
1231 destination when copying a regular file, and lstat otherwise.
1232 However, if we intend to unlink or remove the destination
1233 first, use lstat, since a copy won't actually be made to the
1234 destination in that case. */
1236 ((S_ISREG (src_mode
)
1237 || (x
->copy_as_regular
1238 && ! (S_ISDIR (src_mode
) || S_ISLNK (src_mode
))))
1239 && ! (x
->move_mode
|| x
->symbolic_link
|| x
->hard_link
1240 || x
->backup_type
!= no_backups
1241 || x
->unlink_dest_before_opening
));
1243 ? stat (dst_name
, &dst_sb
)
1244 : lstat (dst_name
, &dst_sb
))
1247 if (errno
!= ENOENT
)
1249 error (0, errno
, _("cannot stat %s"), quote (dst_name
));
1258 { /* Here, we know that dst_name exists, at least to the point
1259 that it is stat'able or lstat'able. */
1263 have_dst_lstat
= !use_stat
;
1264 if (! same_file_ok (src_name
, &src_sb
, dst_name
, &dst_sb
,
1265 x
, &return_now
, &unlink_src
))
1267 error (0, 0, _("%s and %s are the same file"),
1268 quote_n (0, src_name
), quote_n (1, dst_name
));
1272 if (!S_ISDIR (src_mode
) && x
->update
)
1274 /* When preserving time stamps (but not moving within a file
1275 system), don't worry if the destination time stamp is
1276 less than the source merely because of time stamp
1278 int options
= ((x
->preserve_timestamps
1280 && dst_sb
.st_dev
== src_sb
.st_dev
))
1281 ? UTIMECMP_TRUNCATE_SOURCE
1284 if (0 <= utimecmp (dst_name
, &dst_sb
, &src_sb
, options
))
1286 /* We're using --update and the destination is not older
1287 than the source, so do not copy or move. Pretend the
1288 rename succeeded, so the caller (if it's mv) doesn't
1289 end up removing the source file. */
1290 if (rename_succeeded
)
1291 *rename_succeeded
= true;
1296 /* When there is an existing destination file, we may end up
1297 returning early, and hence not copying/moving the file.
1298 This may be due to an interactive `negative' reply to the
1299 prompt about the existing file. It may also be due to the
1300 use of the --reply=no option.
1302 cp and mv treat -i and -f differently. */
1305 if (abandon_move (x
, dst_name
, &dst_sb
)
1306 || (unlink_src
&& unlink (src_name
) == 0))
1308 /* Pretend the rename succeeded, so the caller (mv)
1309 doesn't end up removing the source file. */
1310 if (rename_succeeded
)
1311 *rename_succeeded
= true;
1312 if (unlink_src
&& x
->verbose
)
1313 printf (_("removed %s\n"), quote (src_name
));
1318 error (0, errno
, _("cannot remove %s"), quote (src_name
));
1324 if (! S_ISDIR (src_mode
)
1325 && (x
->interactive
== I_ALWAYS_NO
1326 || (x
->interactive
== I_ASK_USER
1327 && (overwrite_prompt (dst_name
, &dst_sb
), 1)
1335 if (!S_ISDIR (dst_sb
.st_mode
))
1337 if (S_ISDIR (src_mode
))
1339 if (x
->move_mode
&& x
->backup_type
!= no_backups
)
1341 /* Moving a directory onto an existing
1342 non-directory is ok only with --backup. */
1347 _("cannot overwrite non-directory %s with directory %s"),
1348 quote_n (0, dst_name
), quote_n (1, src_name
));
1353 /* Don't let the user destroy their data, even if they try hard:
1354 This mv command must fail (likewise for cp):
1355 rm -rf a b c; mkdir a b c; touch a/f b/f; mv a/f b/f c
1356 Otherwise, the contents of b/f would be lost.
1357 In the case of `cp', b/f would be lost if the user simulated
1358 a move using cp and rm.
1359 Note that it works fine if you use --backup=numbered. */
1360 if (command_line_arg
1361 && x
->backup_type
!= numbered_backups
1362 && seen_file (x
->dest_info
, dst_name
, &dst_sb
))
1365 _("will not overwrite just-created %s with %s"),
1366 quote_n (0, dst_name
), quote_n (1, src_name
));
1371 if (!S_ISDIR (src_mode
))
1373 if (S_ISDIR (dst_sb
.st_mode
))
1375 if (x
->move_mode
&& x
->backup_type
!= no_backups
)
1377 /* Moving a non-directory onto an existing
1378 directory is ok only with --backup. */
1383 _("cannot overwrite directory %s with non-directory"),
1392 /* Don't allow user to move a directory onto a non-directory. */
1393 if (S_ISDIR (src_sb
.st_mode
) && !S_ISDIR (dst_sb
.st_mode
)
1394 && x
->backup_type
== no_backups
)
1397 _("cannot move directory onto non-directory: %s -> %s"),
1398 quote_n (0, src_name
), quote_n (0, dst_name
));
1403 if (x
->backup_type
!= no_backups
1404 /* Don't try to back up a destination if the last
1405 component of src_name is "." or "..". */
1406 && ! dot_or_dotdot (last_component (src_name
))
1407 /* Create a backup of each destination directory in move mode,
1408 but not in copy mode. FIXME: it might make sense to add an
1409 option to suppress backup creation also for move mode.
1410 That would let one use mv to merge new content into an
1411 existing hierarchy. */
1412 && (x
->move_mode
|| ! S_ISDIR (dst_sb
.st_mode
)))
1414 char *tmp_backup
= find_backup_file_name (dst_name
,
1417 /* Detect (and fail) when creating the backup file would
1418 destroy the source file. Before, running the commands
1419 cd /tmp; rm -f a a~; : > a; echo A > a~; cp --b=simple a~ a
1420 would leave two zero-length files: a and a~. */
1421 /* FIXME: but simply change e.g., the final a~ to `./a~'
1422 and the source will still be destroyed. */
1423 if (STREQ (tmp_backup
, src_name
))
1427 ? _("backing up %s would destroy source; %s not moved")
1428 : _("backing up %s would destroy source; %s not copied"));
1430 quote_n (0, dst_name
),
1431 quote_n (1, src_name
));
1437 Using alloca for a file name that may be arbitrarily
1438 long is not recommended. In fact, even forming such a name
1439 should be discouraged. Eventually, this code will be rewritten
1440 to use fts, so using alloca here will be less of a problem. */
1441 ASSIGN_STRDUPA (dst_backup
, tmp_backup
);
1443 if (rename (dst_name
, dst_backup
) != 0)
1445 if (errno
!= ENOENT
)
1447 error (0, errno
, _("cannot backup %s"), quote (dst_name
));
1457 backup_succeeded
= true;
1461 else if (! S_ISDIR (dst_sb
.st_mode
)
1462 /* Never unlink dst_name when in move mode. */
1464 && (x
->unlink_dest_before_opening
1465 || (x
->preserve_links
&& 1 < dst_sb
.st_nlink
)
1466 || (x
->dereference
== DEREF_NEVER
1467 && ! S_ISREG (src_sb
.st_mode
))
1470 if (unlink (dst_name
) != 0 && errno
!= ENOENT
)
1472 error (0, errno
, _("cannot remove %s"), quote (dst_name
));
1477 printf (_("removed %s\n"), quote (dst_name
));
1482 /* Ensure we don't try to copy through a symlink that was
1483 created by a prior call to this function. */
1484 if (command_line_arg
1487 && x
->backup_type
== no_backups
)
1489 bool lstat_ok
= true;
1490 struct stat tmp_buf
;
1491 struct stat
*dst_lstat_sb
;
1493 /* If we called lstat above, good: use that data.
1494 Otherwise, call lstat here, in case dst_name is a symlink. */
1496 dst_lstat_sb
= &dst_sb
;
1499 if (lstat (dst_name
, &tmp_buf
) == 0)
1500 dst_lstat_sb
= &tmp_buf
;
1505 /* Never copy through a symlink we've just created. */
1507 && S_ISLNK (dst_lstat_sb
->st_mode
)
1508 && seen_file (x
->dest_info
, dst_name
, dst_lstat_sb
))
1511 _("will not copy %s through just-created symlink %s"),
1512 quote_n (0, src_name
), quote_n (1, dst_name
));
1517 /* If the source is a directory, we don't always create the destination
1518 directory. So --verbose should not announce anything until we're
1519 sure we'll create a directory. */
1520 if (x
->verbose
&& !S_ISDIR (src_mode
))
1521 emit_verbose (src_name
, dst_name
, backup_succeeded
? dst_backup
: NULL
);
1523 /* Associate the destination file name with the source device and inode
1524 so that if we encounter a matching dev/ino pair in the source tree
1525 we can arrange to create a hard link between the corresponding names
1526 in the destination tree.
1528 When using the --link (-l) option, there is no need to take special
1529 measures, because (barring race conditions) files that are hard-linked
1530 in the source tree will also be hard-linked in the destination tree.
1532 Sometimes, when preserving links, we have to record dev/ino even
1533 though st_nlink == 1:
1534 - when in move_mode, since we may be moving a group of N hard-linked
1535 files (via two or more command line arguments) to a different
1536 partition; the links may be distributed among the command line
1537 arguments (possibly hierarchies) so that the link count of
1538 the final, once-linked source file is reduced to 1 when it is
1539 considered below. But in this case (for mv) we don't need to
1540 incur the expense of recording the dev/ino => name mapping; all we
1541 really need is a lookup, to see if the dev/ino pair has already
1543 - when using -H and processing a command line argument;
1544 that command line argument could be a symlink pointing to another
1545 command line argument. With `cp -H --preserve=link', we hard-link
1546 those two destination files.
1547 - likewise for -L except that it applies to all files, not just
1548 command line arguments.
1550 Also, with --recursive, record dev/ino of each command-line directory.
1551 We'll use that info to detect this problem: cp -R dir dir. */
1553 if (x
->move_mode
&& src_sb
.st_nlink
== 1)
1555 earlier_file
= src_to_dest_lookup (src_sb
.st_ino
, src_sb
.st_dev
);
1557 else if (x
->preserve_links
1559 && (1 < src_sb
.st_nlink
1560 || (command_line_arg
1561 && x
->dereference
== DEREF_COMMAND_LINE_ARGUMENTS
)
1562 || x
->dereference
== DEREF_ALWAYS
))
1564 earlier_file
= remember_copied (dst_name
, src_sb
.st_ino
, src_sb
.st_dev
);
1566 else if (x
->recursive
&& S_ISDIR (src_mode
))
1568 if (command_line_arg
)
1569 earlier_file
= remember_copied (dst_name
, src_sb
.st_ino
, src_sb
.st_dev
);
1571 earlier_file
= src_to_dest_lookup (src_sb
.st_ino
, src_sb
.st_dev
);
1574 /* Did we copy this inode somewhere else (in this command line argument)
1575 and therefore this is a second hard link to the inode? */
1579 /* Avoid damaging the destination file system by refusing to preserve
1580 hard-linked directories (which are found at least in Netapp snapshot
1582 if (S_ISDIR (src_mode
))
1584 /* If src_name and earlier_file refer to the same directory entry,
1585 then warn about copying a directory into itself. */
1586 if (same_name (src_name
, earlier_file
))
1588 error (0, 0, _("cannot copy a directory, %s, into itself, %s"),
1589 quote_n (0, top_level_src_name
),
1590 quote_n (1, top_level_dst_name
));
1591 *copy_into_self
= true;
1594 else if (x
->dereference
== DEREF_ALWAYS
)
1596 /* This happens when e.g., encountering a directory for the
1597 second or subsequent time via symlinks when cp is invoked
1598 with -R and -L. E.g.,
1599 rm -rf a b c d; mkdir a b c d; ln -s ../c a; ln -s ../c b;
1605 error (0, 0, _("will not create hard link %s to directory %s"),
1606 quote_n (0, dst_name
), quote_n (1, earlier_file
));
1612 bool link_failed
= (link (earlier_file
, dst_name
) != 0);
1614 /* If the link failed because of an existing destination,
1615 remove that file and then call link again. */
1616 if (link_failed
&& errno
== EEXIST
)
1618 if (unlink (dst_name
) != 0)
1620 error (0, errno
, _("cannot remove %s"), quote (dst_name
));
1624 printf (_("removed %s\n"), quote (dst_name
));
1625 link_failed
= (link (earlier_file
, dst_name
) != 0);
1630 error (0, errno
, _("cannot create hard link %s to %s"),
1631 quote_n (0, dst_name
), quote_n (1, earlier_file
));
1641 if (rename (src_name
, dst_name
) == 0)
1643 if (x
->verbose
&& S_ISDIR (src_mode
))
1644 emit_verbose (src_name
, dst_name
,
1645 backup_succeeded
? dst_backup
: NULL
);
1647 if (rename_succeeded
)
1648 *rename_succeeded
= true;
1650 if (command_line_arg
)
1652 /* Record destination dev/ino/name, so that if we are asked
1653 to overwrite that file again, we can detect it and fail. */
1654 /* It's fine to use the _source_ stat buffer (src_sb) to get the
1655 _destination_ dev/ino, since the rename above can't have
1656 changed those, and `mv' always uses lstat.
1657 We could limit it further by operating
1658 only on non-directories. */
1659 record_file (x
->dest_info
, dst_name
, &src_sb
);
1665 /* FIXME: someday, consider what to do when moving a directory into
1666 itself but when source and destination are on different devices. */
1668 /* This happens when attempting to rename a directory to a
1669 subdirectory of itself. */
1670 if (errno
== EINVAL
)
1672 /* FIXME: this is a little fragile in that it relies on rename(2)
1673 failing with a specific errno value. Expect problems on
1674 non-POSIX systems. */
1675 error (0, 0, _("cannot move %s to a subdirectory of itself, %s"),
1676 quote_n (0, top_level_src_name
),
1677 quote_n (1, top_level_dst_name
));
1679 /* Note that there is no need to call forget_created here,
1680 (compare with the other calls in this file) since the
1681 destination directory didn't exist before. */
1683 *copy_into_self
= true;
1684 /* FIXME-cleanup: Don't return true here; adjust mv.c accordingly.
1685 The only caller that uses this code (mv.c) ends up setting its
1686 exit status to nonzero when copy_into_self is nonzero. */
1690 /* WARNING: there probably exist systems for which an inter-device
1691 rename fails with a value of errno not handled here.
1692 If/as those are reported, add them to the condition below.
1693 If this happens to you, please do the following and send the output
1694 to the bug-reporting address (e.g., in the output of cp --help):
1695 touch k; perl -e 'rename "k","/tmp/k" or print "$!(",$!+0,")\n"'
1696 where your current directory is on one partion and /tmp is the other.
1697 Also, please try to find the E* errno macro name corresponding to
1698 the diagnostic and parenthesized integer, and include that in your
1699 e-mail. One way to do that is to run a command like this
1700 find /usr/include/. -type f \
1701 | xargs grep 'define.*\<E[A-Z]*\>.*\<18\>' /dev/null
1702 where you'd replace `18' with the integer in parentheses that
1703 was output from the perl one-liner above.
1704 If necessary, of course, change `/tmp' to some other directory. */
1707 /* There are many ways this can happen due to a race condition.
1708 When something happens between the initial XSTAT and the
1709 subsequent rename, we can get many different types of errors.
1710 For example, if the destination is initially a non-directory
1711 or non-existent, but it is created as a directory, the rename
1712 fails. If two `mv' commands try to rename the same file at
1713 about the same time, one will succeed and the other will fail.
1714 If the permissions on the directory containing the source or
1715 destination file are made too restrictive, the rename will
1718 _("cannot move %s to %s"),
1719 quote_n (0, src_name
), quote_n (1, dst_name
));
1720 forget_created (src_sb
.st_ino
, src_sb
.st_dev
);
1724 /* The rename attempt has failed. Remove any existing destination
1725 file so that a cross-device `mv' acts as if it were really using
1726 the rename syscall. */
1727 if (unlink (dst_name
) != 0 && errno
!= ENOENT
)
1730 _("inter-device move failed: %s to %s; unable to remove target"),
1731 quote_n (0, src_name
), quote_n (1, dst_name
));
1732 forget_created (src_sb
.st_ino
, src_sb
.st_dev
);
1739 /* If the ownership might change, or if it is a directory (whose
1740 special mode bits may change after the directory is created),
1741 omit some permissions at first, so unauthorized users cannot nip
1742 in before the file is ready. */
1743 dst_mode_bits
= (x
->set_mode
? x
->mode
: src_mode
) & CHMOD_MODE_BITS
;
1744 omitted_permissions
=
1746 & (x
->preserve_ownership
? S_IRWXG
| S_IRWXO
1747 : S_ISDIR (src_mode
) ? S_IWGRP
| S_IWOTH
1752 if (x
->preserve_security_context
)
1754 security_context_t con
;
1756 if (0 <= lgetfilecon (src_name
, &con
))
1758 if (setfscreatecon (con
) < 0)
1760 if (!x
->reduce_diagnostics
|| x
->require_preserve_context
)
1762 _("failed to set default file creation context to %s"),
1764 if (x
->require_preserve_context
)
1774 if (!errno_unsupported (errno
) || x
->require_preserve_context
)
1776 if (!x
->reduce_diagnostics
|| x
->require_preserve_context
)
1778 _("failed to get security context of %s"),
1780 if (x
->require_preserve_context
)
1786 /* In certain modes (cp's --symbolic-link), and for certain file types
1787 (symlinks and hard links) it doesn't make sense to preserve metadata,
1788 or it's possible to preserve only some of it.
1789 In such cases, set this variable to zero. */
1790 preserve_metadata
= true;
1792 if (S_ISDIR (src_mode
))
1794 struct dir_list
*dir
;
1796 /* If this directory has been copied before during the
1797 recursion, there is a symbolic link to an ancestor
1798 directory of the symbolic link. It is impossible to
1799 continue to copy this, unless we've got an infinite disk. */
1801 if (is_ancestor (&src_sb
, ancestors
))
1803 error (0, 0, _("cannot copy cyclic symbolic link %s"),
1808 /* Insert the current directory in the list of parents. */
1810 dir
= alloca (sizeof *dir
);
1811 dir
->parent
= ancestors
;
1812 dir
->ino
= src_sb
.st_ino
;
1813 dir
->dev
= src_sb
.st_dev
;
1815 if (new_dst
|| !S_ISDIR (dst_sb
.st_mode
))
1817 /* POSIX says mkdir's behavior is implementation-defined when
1818 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
1819 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
1820 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
1821 if (mkdir (dst_name
, dst_mode_bits
& ~omitted_permissions
) != 0)
1823 error (0, errno
, _("cannot create directory %s"),
1828 /* We need search and write permissions to the new directory
1829 for writing the directory's contents. Check if these
1830 permissions are there. */
1832 if (lstat (dst_name
, &dst_sb
) != 0)
1834 error (0, errno
, _("cannot stat %s"), quote (dst_name
));
1837 else if ((dst_sb
.st_mode
& S_IRWXU
) != S_IRWXU
)
1839 /* Make the new directory searchable and writable. */
1841 dst_mode
= dst_sb
.st_mode
;
1842 restore_dst_mode
= true;
1844 if (lchmod (dst_name
, dst_mode
| S_IRWXU
) != 0)
1846 error (0, errno
, _("setting permissions for %s"),
1852 /* Record the created directory's inode and device numbers into
1853 the search structure, so that we can avoid copying it again.
1854 Do this only for the first directory that is created for each
1855 source command line argument. */
1856 if (!*first_dir_created_per_command_line_arg
)
1858 remember_copied (dst_name
, dst_sb
.st_ino
, dst_sb
.st_dev
);
1859 *first_dir_created_per_command_line_arg
= true;
1863 emit_verbose (src_name
, dst_name
, NULL
);
1866 /* Decide whether to copy the contents of the directory. */
1867 if (x
->one_file_system
&& device
!= 0 && device
!= src_sb
.st_dev
)
1869 /* Here, we are crossing a file system boundary and cp's -x option
1870 is in effect: so don't copy the contents of this directory. */
1874 /* Copy the contents of the directory. Don't just return if
1875 this fails -- otherwise, the failure to read a single file
1876 in a source directory would cause the containing destination
1877 directory not to have owner/perms set properly. */
1878 delayed_ok
= copy_dir (src_name
, dst_name
, new_dst
, &src_sb
, dir
, x
,
1879 first_dir_created_per_command_line_arg
,
1883 else if (x
->symbolic_link
)
1885 preserve_metadata
= false;
1887 if (*src_name
!= '/')
1889 /* Check that DST_NAME denotes a file in the current directory. */
1891 struct stat dst_parent_sb
;
1893 bool in_current_dir
;
1895 dst_parent
= dir_name (dst_name
);
1897 in_current_dir
= (STREQ (".", dst_parent
)
1898 /* If either stat call fails, it's ok not to report
1899 the failure and say dst_name is in the current
1900 directory. Other things will fail later. */
1901 || stat (".", &dot_sb
) != 0
1902 || stat (dst_parent
, &dst_parent_sb
) != 0
1903 || SAME_INODE (dot_sb
, dst_parent_sb
));
1906 if (! in_current_dir
)
1909 _("%s: can make relative symbolic links only in current directory"),
1914 if (symlink (src_name
, dst_name
) != 0)
1916 error (0, errno
, _("cannot create symbolic link %s to %s"),
1917 quote_n (0, dst_name
), quote_n (1, src_name
));
1922 else if (x
->hard_link
1923 #ifdef LINK_FOLLOWS_SYMLINKS
1924 /* A POSIX-conforming link syscall dereferences a symlink, yet cp,
1925 invoked with `--link --no-dereference', should not. Thus, with
1926 a POSIX-conforming link system call, we can't use link() here,
1927 since that would create a hard link to the referent (effectively
1928 dereferencing the symlink), rather than to the symlink itself.
1929 We can approximate the desired behavior by skipping this hard-link
1930 creating block and instead copying the symlink, via the `S_ISLNK'-
1932 When link operates on the symlinks themselves, we use this block
1933 and just call link(). */
1934 && !(S_ISLNK (src_mode
) && x
->dereference
== DEREF_NEVER
)
1938 preserve_metadata
= false;
1939 if (link (src_name
, dst_name
))
1941 error (0, errno
, _("cannot create link %s"), quote (dst_name
));
1945 else if (S_ISREG (src_mode
)
1946 || (x
->copy_as_regular
&& !S_ISLNK (src_mode
)))
1948 copied_as_regular
= true;
1949 /* POSIX says the permission bits of the source file must be
1950 used as the 3rd argument in the open call. Historical
1951 practice passed all the source mode bits to 'open', but the extra
1952 bits were ignored, so it should be the same either way. */
1953 if (! copy_reg (src_name
, dst_name
, x
, src_mode
& S_IRWXUGO
,
1954 omitted_permissions
, &new_dst
, &src_sb
))
1957 else if (S_ISFIFO (src_mode
))
1959 /* Use mknod, rather than mkfifo, because the former preserves
1960 the special mode bits of a fifo on Solaris 10, while mkfifo
1961 does not. But fall back on mkfifo, because on some BSD systems,
1962 mknod always fails when asked to create a FIFO. */
1963 if (mknod (dst_name
, src_mode
& ~omitted_permissions
, 0) != 0)
1964 if (mkfifo (dst_name
, src_mode
& ~S_IFIFO
& ~omitted_permissions
) != 0)
1966 error (0, errno
, _("cannot create fifo %s"), quote (dst_name
));
1970 else if (S_ISBLK (src_mode
) || S_ISCHR (src_mode
) || S_ISSOCK (src_mode
))
1972 if (mknod (dst_name
, src_mode
& ~omitted_permissions
, src_sb
.st_rdev
)
1975 error (0, errno
, _("cannot create special file %s"),
1980 else if (S_ISLNK (src_mode
))
1982 char *src_link_val
= areadlink_with_size (src_name
, src_sb
.st_size
);
1983 if (src_link_val
== NULL
)
1985 error (0, errno
, _("cannot read symbolic link %s"), quote (src_name
));
1989 if (symlink (src_link_val
, dst_name
) == 0)
1990 free (src_link_val
);
1993 int saved_errno
= errno
;
1994 bool same_link
= false;
1995 if (x
->update
&& !new_dst
&& S_ISLNK (dst_sb
.st_mode
)
1996 && dst_sb
.st_size
== strlen (src_link_val
))
1998 /* See if the destination is already the desired symlink.
1999 FIXME: This behavior isn't documented, and seems wrong
2000 in some cases, e.g., if the destination symlink has the
2001 wrong ownership, permissions, or time stamps. */
2002 char *dest_link_val
=
2003 areadlink_with_size (dst_name
, dst_sb
.st_size
);
2004 if (dest_link_val
&& STREQ (dest_link_val
, src_link_val
))
2006 free (dest_link_val
);
2008 free (src_link_val
);
2012 error (0, saved_errno
, _("cannot create symbolic link %s"),
2018 if (x
->preserve_security_context
)
2019 restore_default_fscreatecon_or_die ();
2021 /* There's no need to preserve timestamps or permissions. */
2022 preserve_metadata
= false;
2024 if (x
->preserve_ownership
)
2026 /* Preserve the owner and group of the just-`copied'
2027 symbolic link, if possible. */
2029 && lchown (dst_name
, src_sb
.st_uid
, src_sb
.st_gid
) != 0
2030 && ! chown_failure_ok (x
))
2032 error (0, errno
, _("failed to preserve ownership for %s"),
2038 /* Can't preserve ownership of symlinks.
2039 FIXME: maybe give a warning or even error for symlinks
2040 in directories with the sticky bit set -- there, not
2041 preserving owner/group is a potential security problem. */
2047 error (0, 0, _("%s has unknown file type"), quote (src_name
));
2051 if (command_line_arg
&& x
->dest_info
)
2053 /* Now that the destination file is very likely to exist,
2054 add its info to the set. */
2056 if (lstat (dst_name
, &sb
) == 0)
2057 record_file (x
->dest_info
, dst_name
, &sb
);
2060 if ( ! preserve_metadata
)
2063 if (copied_as_regular
)
2066 /* POSIX says that `cp -p' must restore the following:
2068 - setuid, setgid bits
2070 If it fails to restore any of those, we may give a warning but
2071 the destination must not be removed.
2072 FIXME: implement the above. */
2074 /* Adjust the times (and if possible, ownership) for the copy.
2075 chown turns off set[ug]id bits for non-root,
2076 so do the chmod last. */
2078 if (x
->preserve_timestamps
)
2080 struct timespec timespec
[2];
2081 timespec
[0] = get_stat_atime (&src_sb
);
2082 timespec
[1] = get_stat_mtime (&src_sb
);
2084 if (utimens (dst_name
, timespec
) != 0)
2086 error (0, errno
, _("preserving times for %s"), quote (dst_name
));
2087 if (x
->require_preserve
)
2092 /* Avoid calling chown if we know it's not necessary. */
2093 if (x
->preserve_ownership
2094 && (new_dst
|| !SAME_OWNER_AND_GROUP (src_sb
, dst_sb
)))
2096 switch (set_owner (x
, dst_name
, -1, &src_sb
, new_dst
, &dst_sb
))
2102 src_mode
&= ~ (S_ISUID
| S_ISGID
| S_ISVTX
);
2107 set_author (dst_name
, -1, &src_sb
);
2109 if (x
->preserve_xattr
&& ! copy_attr_by_name (src_name
, dst_name
, x
)
2110 && x
->require_preserve_xattr
)
2113 if (x
->preserve_mode
|| x
->move_mode
)
2115 if (copy_acl (src_name
, -1, dst_name
, -1, src_mode
) != 0
2116 && x
->require_preserve
)
2119 else if (x
->set_mode
)
2121 if (set_acl (dst_name
, -1, x
->mode
) != 0)
2126 if (omitted_permissions
)
2128 omitted_permissions
&= ~ cached_umask ();
2130 if (omitted_permissions
&& !restore_dst_mode
)
2132 /* Permissions were deliberately omitted when the file
2133 was created due to security concerns. See whether
2134 they need to be re-added now. It'd be faster to omit
2135 the lstat, but deducing the current destination mode
2136 is tricky in the presence of implementation-defined
2137 rules for special mode bits. */
2138 if (new_dst
&& lstat (dst_name
, &dst_sb
) != 0)
2140 error (0, errno
, _("cannot stat %s"), quote (dst_name
));
2143 dst_mode
= dst_sb
.st_mode
;
2144 if (omitted_permissions
& ~dst_mode
)
2145 restore_dst_mode
= true;
2149 if (restore_dst_mode
)
2151 if (lchmod (dst_name
, dst_mode
| omitted_permissions
) != 0)
2153 error (0, errno
, _("preserving permissions for %s"),
2155 if (x
->require_preserve
)
2165 if (x
->preserve_security_context
)
2166 restore_default_fscreatecon_or_die ();
2168 /* We have failed to create the destination file.
2169 If we've just added a dev/ino entry via the remember_copied
2170 call above (i.e., unless we've just failed to create a hard link),
2171 remove the entry associating the source dev/ino with the
2172 destination file name, so we don't try to `preserve' a link
2173 to a file we didn't create. */
2174 if (earlier_file
== NULL
)
2175 forget_created (src_sb
.st_ino
, src_sb
.st_dev
);
2179 if (rename (dst_backup
, dst_name
) != 0)
2180 error (0, errno
, _("cannot un-backup %s"), quote (dst_name
));
2184 printf (_("%s -> %s (unbackup)\n"),
2185 quote_n (0, dst_backup
), quote_n (1, dst_name
));
2192 valid_options (const struct cp_options
*co
)
2194 assert (co
!= NULL
);
2195 assert (VALID_BACKUP_TYPE (co
->backup_type
));
2196 assert (VALID_SPARSE_MODE (co
->sparse_mode
));
2197 assert (!(co
->hard_link
&& co
->symbolic_link
));
2201 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
2202 any type. NONEXISTENT_DST should be true if the file DST_NAME
2203 is known not to exist (e.g., because its parent directory was just
2204 created); NONEXISTENT_DST should be false if DST_NAME might already
2205 exist. OPTIONS is ... FIXME-describe
2206 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
2207 same as) DST_NAME; otherwise, set clear it.
2208 Return true if successful. */
2211 copy (char const *src_name
, char const *dst_name
,
2212 bool nonexistent_dst
, const struct cp_options
*options
,
2213 bool *copy_into_self
, bool *rename_succeeded
)
2215 assert (valid_options (options
));
2217 /* Record the file names: they're used in case of error, when copying
2218 a directory into itself. I don't like to make these tools do *any*
2219 extra work in the common case when that work is solely to handle
2220 exceptional cases, but in this case, I don't see a way to derive the
2221 top level source and destination directory names where they're used.
2222 An alternative is to use COPY_INTO_SELF and print the diagnostic
2223 from every caller -- but I don't want to do that. */
2224 top_level_src_name
= src_name
;
2225 top_level_dst_name
= dst_name
;
2227 bool first_dir_created_per_command_line_arg
= false;
2228 return copy_internal (src_name
, dst_name
, nonexistent_dst
, 0, NULL
,
2230 &first_dir_created_per_command_line_arg
,
2231 copy_into_self
, rename_succeeded
);
2234 /* Set *X to the default options for a value of type struct cp_options. */
2237 cp_options_default (struct cp_options
*x
)
2239 memset (x
, 0, sizeof *x
);
2240 #ifdef PRIV_FILE_CHOWN
2242 priv_set_t
*pset
= priv_allocset ();
2245 if (getppriv (PRIV_EFFECTIVE
, pset
) == 0)
2247 x
->chown_privileges
= priv_ismember (pset
, PRIV_FILE_CHOWN
);
2248 x
->owner_privileges
= priv_ismember (pset
, PRIV_FILE_OWNER
);
2250 priv_freeset (pset
);
2253 x
->chown_privileges
= x
->owner_privileges
= (geteuid () == 0);
2257 /* Return true if it's OK for chown to fail, where errno is
2258 the error number that chown failed with and X is the copying
2262 chown_failure_ok (struct cp_options
const *x
)
2264 /* If non-root uses -p, it's ok if we can't preserve ownership.
2265 But root probably wants to know, e.g. if NFS disallows it,
2266 or if the target system doesn't support file ownership. */
2268 return ((errno
== EPERM
|| errno
== EINVAL
) && !x
->chown_privileges
);
2271 /* Similarly, return true if it's OK for chmod and similar operations
2272 to fail, where errno is the error number that chmod failed with and
2273 X is the copying option set. */
2276 owner_failure_ok (struct cp_options
const *x
)
2278 return ((errno
== EPERM
|| errno
== EINVAL
) && !x
->owner_privileges
);
2281 /* Return the user's umask, caching the result. */
2286 static mode_t mask
= (mode_t
) -1;
2287 if (mask
== (mode_t
) -1)