1 /* copy.c -- core functions for copying files and directories
2 Copyright (C) 1989-2017 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 <https://www.gnu.org/licenses/>. */
17 /* Extracted from cp.c and librarified by Jim Meyering. */
22 #include <sys/ioctl.h>
23 #include <sys/types.h>
24 #include <selinux/selinux.h>
35 #include "backupfile.h"
36 #include "buffer-lcm.h"
37 #include "canonicalize.h"
40 #include "extent-scan.h"
48 #include "filenamecat.h"
49 #include "force-link.h"
50 #include "full-write.h"
52 #include "hash-triple.h"
53 #include "ignore-value.h"
54 #include "ioblksize.h"
59 #include "stat-size.h"
60 #include "stat-time.h"
63 #include "write-any-file.h"
64 #include "areadlink.h"
69 # include <attr/error_context.h>
70 # include <attr/libattr.h>
75 #if HAVE_LINUX_FALLOC_H
76 # include <linux/falloc.h>
79 /* See HAVE_FALLOCATE workaround when including this file. */
80 #ifdef HAVE_LINUX_FS_H
81 # include <linux/fs.h>
84 #if !defined FICLONE && defined __linux__
85 # define FICLONE _IOW (0x94, 9, int)
89 # define HAVE_FCHOWN false
90 # define fchown(fd, uid, gid) (-1)
94 # define HAVE_LCHOWN false
95 # define lchown(name, uid, gid) chown (name, uid, gid)
100 rpl_mkfifo (char const *file
, mode_t mode
)
105 # define mkfifo rpl_mkfifo
112 #define SAME_OWNER(A, B) ((A).st_uid == (B).st_uid)
113 #define SAME_GROUP(A, B) ((A).st_gid == (B).st_gid)
114 #define SAME_OWNER_AND_GROUP(A, B) (SAME_OWNER (A, B) && SAME_GROUP (A, B))
116 /* LINK_FOLLOWS_SYMLINKS is tri-state; if it is -1, we don't know
117 how link() behaves, so assume we can't hardlink symlinks in that case. */
118 #if (defined HAVE_LINKAT && ! LINKAT_SYMLINK_NOTSUP) || ! LINK_FOLLOWS_SYMLINKS
119 # define CAN_HARDLINK_SYMLINKS 1
121 # define CAN_HARDLINK_SYMLINKS 0
126 struct dir_list
*parent
;
131 /* Initial size of the cp.dest_info hash table. */
132 #define DEST_INFO_INITIAL_CAPACITY 61
134 static bool copy_internal (char const *src_name
, char const *dst_name
,
135 bool new_dst
, struct stat
const *parent
,
136 struct dir_list
*ancestors
,
137 const struct cp_options
*x
,
138 bool command_line_arg
,
139 bool *first_dir_created_per_command_line_arg
,
140 bool *copy_into_self
,
141 bool *rename_succeeded
);
142 static bool owner_failure_ok (struct cp_options
const *x
);
144 /* Pointers to the file names: they're used in the diagnostic that is issued
145 when we detect the user is trying to copy a directory into itself. */
146 static char const *top_level_src_name
;
147 static char const *top_level_dst_name
;
149 /* Set the timestamp of symlink, FILE, to TIMESPEC.
150 If this system lacks support for that, simply return 0. */
152 utimens_symlink (char const *file
, struct timespec
const *timespec
)
154 int err
= lutimens (file
, timespec
);
155 /* When configuring on a system with new headers and libraries, and
156 running on one with a kernel that is old enough to lack the syscall,
157 utimensat fails with ENOSYS. Ignore that. */
158 if (err
&& errno
== ENOSYS
)
163 /* Attempt to punch a hole to avoid any permanent
164 speculative preallocation on file systems such as XFS.
165 Return values as per fallocate(2) except ENOSYS etc. are ignored. */
168 punch_hole (int fd
, off_t offset
, off_t length
)
171 /* +0 is to work around older <linux/fs.h> defining HAVE_FALLOCATE to empty. */
172 #if HAVE_FALLOCATE + 0
173 # if defined FALLOC_FL_PUNCH_HOLE && defined FALLOC_FL_KEEP_SIZE
174 ret
= fallocate (fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
176 if (ret
< 0 && (is_ENOTSUP (errno
) || errno
== ENOSYS
))
183 /* Create a hole at the end of a file,
184 avoiding preallocation if requested. */
187 create_hole (int fd
, char const *name
, bool punch_holes
, off_t size
)
189 off_t file_end
= lseek (fd
, size
, SEEK_CUR
);
193 error (0, errno
, _("cannot lseek %s"), quoteaf (name
));
197 /* Some file systems (like XFS) preallocate when write extending a file.
198 I.e., a previous write() may have preallocated extra space
199 that the seek above will not discard. A subsequent write() could
200 then make this allocation permanent. */
201 if (punch_holes
&& punch_hole (fd
, file_end
- size
, size
) < 0)
203 error (0, errno
, _("error deallocating %s"), quoteaf (name
));
211 /* Copy the regular file open on SRC_FD/SRC_NAME to DST_FD/DST_NAME,
212 honoring the MAKE_HOLES setting and using the BUF_SIZE-byte buffer
213 BUF for temporary storage. Copy no more than MAX_N_READ bytes.
214 Return true upon successful completion;
215 print a diagnostic and return false upon error.
216 Note that for best results, BUF should be "well"-aligned.
217 BUF must have sizeof(uintptr_t)-1 bytes of additional space
218 beyond BUF[BUF_SIZE-1].
219 Set *LAST_WRITE_MADE_HOLE to true if the final operation on
220 DEST_FD introduced a hole. Set *TOTAL_N_READ to the number of
223 sparse_copy (int src_fd
, int dest_fd
, char *buf
, size_t buf_size
,
224 size_t hole_size
, bool punch_holes
,
225 char const *src_name
, char const *dst_name
,
226 uintmax_t max_n_read
, off_t
*total_n_read
,
227 bool *last_write_made_hole
)
229 *last_write_made_hole
= false;
231 bool make_hole
= false;
236 ssize_t n_read
= read (src_fd
, buf
, MIN (max_n_read
, buf_size
));
241 error (0, errno
, _("error reading %s"), quoteaf (src_name
));
246 max_n_read
-= n_read
;
247 *total_n_read
+= n_read
;
249 /* Loop over the input buffer in chunks of hole_size. */
250 size_t csize
= hole_size
? hole_size
: buf_size
;
256 bool prev_hole
= make_hole
;
257 csize
= MIN (csize
, n_read
);
259 if (hole_size
&& csize
)
260 make_hole
= is_nul (cbuf
, csize
);
262 bool transition
= (make_hole
!= prev_hole
) && psize
;
263 bool last_chunk
= (n_read
== csize
&& ! make_hole
) || ! csize
;
265 if (transition
|| last_chunk
)
272 if (full_write (dest_fd
, pbuf
, psize
) != psize
)
274 error (0, errno
, _("error writing %s"),
281 if (! create_hole (dest_fd
, dst_name
, punch_holes
, psize
))
291 n_read
= 0; /* Finished processing buffer. */
294 csize
= 0; /* Loop again to deal with last chunk. */
296 psize
= 0; /* Reset for next read loop. */
299 else /* Coalesce writes/seeks. */
301 if (psize
<= OFF_T_MAX
- csize
)
305 error (0, 0, _("overflow reading %s"), quoteaf (src_name
));
314 *last_write_made_hole
= make_hole
;
316 /* It's tempting to break early here upon a short read from
317 a regular file. That would save the final read syscall
318 for each file. Unfortunately that doesn't work for
319 certain files in /proc or /sys with linux kernels. */
322 /* Ensure a trailing hole is created, so that subsequent
323 calls of sparse_copy() start at the correct offset. */
324 if (make_hole
&& ! create_hole (dest_fd
, dst_name
, punch_holes
, psize
))
330 /* Perform the O(1) btrfs clone operation, if possible.
331 Upon success, return 0. Otherwise, return -1 and set errno. */
333 clone_file (int dest_fd
, int src_fd
)
336 return ioctl (dest_fd
, FICLONE
, src_fd
);
345 /* Write N_BYTES zero bytes to file descriptor FD. Return true if successful.
346 Upon write failure, set errno and return false. */
348 write_zeros (int fd
, off_t n_bytes
)
351 static size_t nz
= IO_BUFSIZE
;
353 /* Attempt to use a relatively large calloc'd source buffer for
354 efficiency, but if that allocation fails, resort to a smaller
355 statically allocated one. */
358 static char fallback
[1024];
359 zeros
= calloc (nz
, 1);
363 nz
= sizeof fallback
;
369 size_t n
= MIN (nz
, n_bytes
);
370 if ((full_write (fd
, zeros
, n
)) != n
)
378 /* Perform an efficient extent copy, if possible. This avoids
379 the overhead of detecting holes in hole-introducing/preserving
380 copy, and thus makes copying sparse files much more efficient.
381 Upon a successful copy, return true. If the initial extent scan
382 fails, set *NORMAL_COPY_REQUIRED to true and return false.
383 Upon any other failure, set *NORMAL_COPY_REQUIRED to false and
386 extent_copy (int src_fd
, int dest_fd
, char *buf
, size_t buf_size
,
387 size_t hole_size
, off_t src_total_size
,
388 enum Sparse_type sparse_mode
,
389 char const *src_name
, char const *dst_name
,
390 bool *require_normal_copy
)
392 struct extent_scan scan
;
393 off_t last_ext_start
= 0;
394 off_t last_ext_len
= 0;
396 /* Keep track of the output position.
397 We may need this at the end, for a final ftruncate. */
400 extent_scan_init (src_fd
, &scan
);
402 *require_normal_copy
= false;
403 bool wrote_hole_at_eof
= true;
406 bool ok
= extent_scan_read (&scan
);
409 if (scan
.hit_final_extent
)
412 if (scan
.initial_scan_failed
)
414 *require_normal_copy
= true;
418 error (0, errno
, _("%s: failed to get extents info"),
423 bool empty_extent
= false;
424 for (unsigned int i
= 0; i
< scan
.ei_count
|| empty_extent
; i
++)
430 if (i
< scan
.ei_count
)
432 ext_start
= scan
.ext_info
[i
].ext_logical
;
433 ext_len
= scan
.ext_info
[i
].ext_length
;
435 else /* empty extent at EOF. */
438 ext_start
= last_ext_start
+ scan
.ext_info
[i
].ext_length
;
442 /* Truncate extent to EOF. Extents starting after EOF are
443 treated as zero length extents starting right after EOF.
444 Generally this will trigger with an extent starting after
445 src_total_size, and result in creating a hole or zeros until EOF.
446 Though in a file in which extents have changed since src_total_size
447 was determined, we might have an extent spanning that size,
448 in which case we'll only copy data up to that size. */
449 if (src_total_size
< ext_start
+ ext_len
)
451 if (src_total_size
< ext_start
)
452 ext_start
= src_total_size
;
453 ext_len
= src_total_size
- ext_start
;
456 ext_hole_size
= ext_start
- last_ext_start
- last_ext_len
;
458 wrote_hole_at_eof
= false;
462 if (lseek (src_fd
, ext_start
, SEEK_SET
) < 0)
464 error (0, errno
, _("cannot lseek %s"), quoteaf (src_name
));
466 extent_scan_free (&scan
);
470 if ((empty_extent
&& sparse_mode
== SPARSE_ALWAYS
)
471 || (!empty_extent
&& sparse_mode
!= SPARSE_NEVER
))
473 if (! create_hole (dest_fd
, dst_name
,
474 sparse_mode
== SPARSE_ALWAYS
,
477 wrote_hole_at_eof
= true;
481 /* When not inducing holes and when there is a hole between
482 the end of the previous extent and the beginning of the
483 current one, write zeros to the destination file. */
484 off_t nzeros
= ext_hole_size
;
486 nzeros
= MIN (src_total_size
- dest_pos
, ext_hole_size
);
488 if (! write_zeros (dest_fd
, nzeros
))
490 error (0, errno
, _("%s: write failed"),
495 dest_pos
= MIN (src_total_size
, ext_start
);
499 last_ext_start
= ext_start
;
501 /* Treat an unwritten but allocated extent much like a hole.
502 I.e., don't read, but don't convert to a hole in the destination,
503 unless SPARSE_ALWAYS. */
504 /* For now, do not treat FIEMAP_EXTENT_UNWRITTEN specially,
505 because that (in combination with no sync) would lead to data
506 loss at least on XFS and ext4 when using 2.6.39-rc3 kernels. */
507 if (0 && (scan
.ext_info
[i
].ext_flags
& FIEMAP_EXTENT_UNWRITTEN
))
511 if (ext_len
== 0) /* The last extent is empty and processed. */
512 empty_extent
= false;
517 empty_extent
= false;
518 last_ext_len
= ext_len
;
521 if ( ! sparse_copy (src_fd
, dest_fd
, buf
, buf_size
,
522 sparse_mode
== SPARSE_ALWAYS
? hole_size
: 0,
523 true, src_name
, dst_name
, ext_len
, &n_read
,
527 dest_pos
= ext_start
+ n_read
;
529 wrote_hole_at_eof
= read_hole
;
532 /* If the file ends with unwritten extents not accounted for in the
533 size, then skip processing them, and the associated redundant
534 read() calls which will always return 0. We will need to
535 remove this when we add fallocate() so that we can maintain
536 extents beyond the apparent size. */
537 if (dest_pos
== src_total_size
)
539 scan
.hit_final_extent
= true;
544 /* Release the space allocated to scan->ext_info. */
545 extent_scan_free (&scan
);
548 while (! scan
.hit_final_extent
);
550 /* When the source file ends with a hole, we have to do a little more work,
551 since the above copied only up to and including the final extent.
552 In order to complete the copy, we may have to insert a hole or write
553 zeros in the destination corresponding to the source file's hole-at-EOF.
555 In addition, if the final extent was a block of zeros at EOF and we've
556 just converted them to a hole in the destination, we must call ftruncate
557 here in order to record the proper length in the destination. */
558 if ((dest_pos
< src_total_size
|| wrote_hole_at_eof
)
559 && (sparse_mode
!= SPARSE_NEVER
560 ? ftruncate (dest_fd
, src_total_size
)
561 : ! write_zeros (dest_fd
, src_total_size
- dest_pos
)))
563 error (0, errno
, _("failed to extend %s"), quoteaf (dst_name
));
567 if (sparse_mode
== SPARSE_ALWAYS
&& dest_pos
< src_total_size
568 && punch_hole (dest_fd
, dest_pos
, src_total_size
- dest_pos
) < 0)
570 error (0, errno
, _("error deallocating %s"), quoteaf (dst_name
));
577 /* FIXME: describe */
578 /* FIXME: rewrite this to use a hash table so we avoid the quadratic
579 performance hit that's probably noticeable only on trees deeper
580 than a few hundred levels. See use of active_dir_map in remove.c */
582 static bool _GL_ATTRIBUTE_PURE
583 is_ancestor (const struct stat
*sb
, const struct dir_list
*ancestors
)
585 while (ancestors
!= 0)
587 if (ancestors
->ino
== sb
->st_ino
&& ancestors
->dev
== sb
->st_dev
)
589 ancestors
= ancestors
->parent
;
595 errno_unsupported (int err
)
597 return err
== ENOTSUP
|| err
== ENODATA
;
602 copy_attr_error (struct error_context
*ctx _GL_UNUSED
,
603 char const *fmt
, ...)
605 if (!errno_unsupported (errno
))
610 /* use verror module to print error message */
612 verror (0, err
, fmt
, ap
);
618 copy_attr_allerror (struct error_context
*ctx _GL_UNUSED
,
619 char const *fmt
, ...)
624 /* use verror module to print error message */
626 verror (0, err
, fmt
, ap
);
631 copy_attr_quote (struct error_context
*ctx _GL_UNUSED
, char const *str
)
633 return quoteaf (str
);
637 copy_attr_free (struct error_context
*ctx _GL_UNUSED
,
638 char const *str _GL_UNUSED
)
642 /* Exclude SELinux extended attributes that are otherwise handled,
643 and are problematic to copy again. Also honor attributes
644 configured for exclusion in /etc/xattr.conf.
645 FIXME: Should we handle POSIX ACLs similarly?
646 Return zero to skip. */
648 check_selinux_attr (const char *name
, struct error_context
*ctx
)
650 return STRNCMP_LIT (name
, "security.selinux")
651 && attr_copy_check_permissions (name
, ctx
);
654 /* If positive SRC_FD and DST_FD descriptors are passed,
655 then copy by fd, otherwise copy by name. */
658 copy_attr (char const *src_path
, int src_fd
,
659 char const *dst_path
, int dst_fd
, struct cp_options
const *x
)
662 bool all_errors
= (!x
->data_copy_required
|| x
->require_preserve_xattr
);
663 bool some_errors
= (!all_errors
&& !x
->reduce_diagnostics
);
664 bool selinux_done
= (x
->preserve_security_context
|| x
->set_security_context
);
665 struct error_context ctx
=
667 .error
= all_errors
? copy_attr_allerror
: copy_attr_error
,
668 .quote
= copy_attr_quote
,
669 .quote_free
= copy_attr_free
671 if (0 <= src_fd
&& 0 <= dst_fd
)
672 ret
= attr_copy_fd (src_path
, src_fd
, dst_path
, dst_fd
,
673 selinux_done
? check_selinux_attr
: NULL
,
674 (all_errors
|| some_errors
? &ctx
: NULL
));
676 ret
= attr_copy_file (src_path
, dst_path
,
677 selinux_done
? check_selinux_attr
: NULL
,
678 (all_errors
|| some_errors
? &ctx
: NULL
));
682 #else /* USE_XATTR */
685 copy_attr (char const *src_path _GL_UNUSED
,
686 int src_fd _GL_UNUSED
,
687 char const *dst_path _GL_UNUSED
,
688 int dst_fd _GL_UNUSED
,
689 struct cp_options
const *x _GL_UNUSED
)
693 #endif /* USE_XATTR */
695 /* Read the contents of the directory SRC_NAME_IN, and recursively
696 copy the contents to DST_NAME_IN. NEW_DST is true if
697 DST_NAME_IN is a directory that was created previously in the
698 recursion. SRC_SB and ANCESTORS describe SRC_NAME_IN.
699 Set *COPY_INTO_SELF if SRC_NAME_IN is a parent of
700 (or the same as) DST_NAME_IN; otherwise, clear it.
701 Propagate *FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG from
702 caller to each invocation of copy_internal. Be careful to
703 pass the address of a temporary, and to update
704 *FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG only upon completion.
705 Return true if successful. */
708 copy_dir (char const *src_name_in
, char const *dst_name_in
, bool new_dst
,
709 const struct stat
*src_sb
, struct dir_list
*ancestors
,
710 const struct cp_options
*x
,
711 bool *first_dir_created_per_command_line_arg
,
712 bool *copy_into_self
)
716 struct cp_options non_command_line_options
= *x
;
719 name_space
= savedir (src_name_in
, SAVEDIR_SORT_FASTREAD
);
720 if (name_space
== NULL
)
722 /* This diagnostic is a bit vague because savedir can fail in
723 several different ways. */
724 error (0, errno
, _("cannot access %s"), quoteaf (src_name_in
));
728 /* For cp's -H option, dereference command line arguments, but do not
729 dereference symlinks that are found via recursive traversal. */
730 if (x
->dereference
== DEREF_COMMAND_LINE_ARGUMENTS
)
731 non_command_line_options
.dereference
= DEREF_NEVER
;
733 bool new_first_dir_created
= false;
735 while (*namep
!= '\0')
737 bool local_copy_into_self
;
738 char *src_name
= file_name_concat (src_name_in
, namep
, NULL
);
739 char *dst_name
= file_name_concat (dst_name_in
, namep
, NULL
);
740 bool first_dir_created
= *first_dir_created_per_command_line_arg
;
742 ok
&= copy_internal (src_name
, dst_name
, new_dst
, src_sb
,
743 ancestors
, &non_command_line_options
, false,
745 &local_copy_into_self
, NULL
);
746 *copy_into_self
|= local_copy_into_self
;
751 /* If we're copying into self, there's no point in continuing,
752 and in fact, that would even infloop, now that we record only
753 the first created directory per command line argument. */
754 if (local_copy_into_self
)
757 new_first_dir_created
|= first_dir_created
;
758 namep
+= strlen (namep
) + 1;
761 *first_dir_created_per_command_line_arg
= new_first_dir_created
;
766 /* Set the owner and owning group of DEST_DESC to the st_uid and
767 st_gid fields of SRC_SB. If DEST_DESC is undefined (-1), set
768 the owner and owning group of DST_NAME instead; for
769 safety prefer lchown if the system supports it since no
770 symbolic links should be involved. DEST_DESC must
771 refer to the same file as DEST_NAME if defined.
772 Upon failure to set both UID and GID, try to set only the GID.
773 NEW_DST is true if the file was newly created; otherwise,
774 DST_SB is the status of the destination.
775 Return 1 if the initial syscall succeeds, 0 if it fails but it's OK
776 not to preserve ownership, -1 otherwise. */
779 set_owner (const struct cp_options
*x
, char const *dst_name
, int dest_desc
,
780 struct stat
const *src_sb
, bool new_dst
,
781 struct stat
const *dst_sb
)
783 uid_t uid
= src_sb
->st_uid
;
784 gid_t gid
= src_sb
->st_gid
;
786 /* Naively changing the ownership of an already-existing file before
787 changing its permissions would create a window of vulnerability if
788 the file's old permissions are too generous for the new owner and
789 group. Avoid the window by first changing to a restrictive
790 temporary mode if necessary. */
792 if (!new_dst
&& (x
->preserve_mode
|| x
->move_mode
|| x
->set_mode
))
794 mode_t old_mode
= dst_sb
->st_mode
;
796 (x
->preserve_mode
|| x
->move_mode
? src_sb
->st_mode
: x
->mode
);
797 mode_t restrictive_temp_mode
= old_mode
& new_mode
& S_IRWXU
;
800 || (old_mode
& CHMOD_MODE_BITS
801 & (~new_mode
| S_ISUID
| S_ISGID
| S_ISVTX
)))
802 && qset_acl (dst_name
, dest_desc
, restrictive_temp_mode
) != 0)
804 if (! owner_failure_ok (x
))
805 error (0, errno
, _("clearing permissions for %s"),
807 return -x
->require_preserve
;
811 if (HAVE_FCHOWN
&& dest_desc
!= -1)
813 if (fchown (dest_desc
, uid
, gid
) == 0)
815 if (errno
== EPERM
|| errno
== EINVAL
)
817 /* We've failed to set *both*. Now, try to set just the group
818 ID, but ignore any failure here, and don't change errno. */
819 int saved_errno
= errno
;
820 ignore_value (fchown (dest_desc
, -1, gid
));
826 if (lchown (dst_name
, uid
, gid
) == 0)
828 if (errno
== EPERM
|| errno
== EINVAL
)
830 /* We've failed to set *both*. Now, try to set just the group
831 ID, but ignore any failure here, and don't change errno. */
832 int saved_errno
= errno
;
833 ignore_value (lchown (dst_name
, -1, gid
));
838 if (! chown_failure_ok (x
))
840 error (0, errno
, _("failed to preserve ownership for %s"),
842 if (x
->require_preserve
)
849 /* Set the st_author field of DEST_DESC to the st_author field of
850 SRC_SB. If DEST_DESC is undefined (-1), set the st_author field
851 of DST_NAME instead. DEST_DESC must refer to the same file as
852 DEST_NAME if defined. */
855 set_author (const char *dst_name
, int dest_desc
, const struct stat
*src_sb
)
857 #if HAVE_STRUCT_STAT_ST_AUTHOR
858 /* FIXME: Modify the following code so that it does not
859 follow symbolic links. */
861 /* Preserve the st_author field. */
862 file_t file
= (dest_desc
< 0
863 ? file_name_lookup (dst_name
, 0, 0)
864 : getdport (dest_desc
));
865 if (file
== MACH_PORT_NULL
)
866 error (0, errno
, _("failed to lookup file %s"), quoteaf (dst_name
));
869 error_t err
= file_chauthor (file
, src_sb
->st_author
);
871 error (0, err
, _("failed to preserve authorship for %s"),
873 mach_port_deallocate (mach_task_self (), file
);
882 /* Set the default security context for the process. New files will
883 have this security context set. Also existing files can have their
884 context adjusted based on this process context, by
885 set_file_security_ctx() called with PROCESS_LOCAL=true.
886 This should be called before files are created so there is no race
887 where a file may be present without an appropriate security context.
888 Based on CP_OPTIONS, diagnose warnings and fail when appropriate.
889 Return FALSE on failure, TRUE on success. */
892 set_process_security_ctx (char const *src_name
, char const *dst_name
,
893 mode_t mode
, bool new_dst
, const struct cp_options
*x
)
895 if (x
->preserve_security_context
)
897 /* Set the default context for the process to match the source. */
898 bool all_errors
= !x
->data_copy_required
|| x
->require_preserve_context
;
899 bool some_errors
= !all_errors
&& !x
->reduce_diagnostics
;
902 if (0 <= lgetfilecon (src_name
, &con
))
904 if (setfscreatecon (con
) < 0)
906 if (all_errors
|| (some_errors
&& !errno_unsupported (errno
)))
908 _("failed to set default file creation context to %s"),
910 if (x
->require_preserve_context
)
920 if (all_errors
|| (some_errors
&& !errno_unsupported (errno
)))
923 _("failed to get security context of %s"),
926 if (x
->require_preserve_context
)
930 else if (x
->set_security_context
)
932 /* With -Z, adjust the default context for the process
933 to have the type component adjusted as per the destination path. */
934 if (new_dst
&& defaultcon (dst_name
, mode
) < 0
935 && ! ignorable_ctx_err (errno
))
938 _("failed to set default file creation context for %s"),
946 /* Reset the security context of DST_NAME, to that already set
947 as the process default if PROCESS_LOCAL is true. Otherwise
948 adjust the type component of DST_NAME's security context as
949 per the system default for that path. Issue warnings upon
950 failure, when allowed by various settings in CP_OPTIONS.
951 Return FALSE on failure, TRUE on success. */
954 set_file_security_ctx (char const *dst_name
, bool process_local
,
955 bool recurse
, const struct cp_options
*x
)
957 bool all_errors
= (!x
->data_copy_required
958 || x
->require_preserve_context
);
959 bool some_errors
= !all_errors
&& !x
->reduce_diagnostics
;
961 if (! restorecon (dst_name
, recurse
, process_local
))
963 if (all_errors
|| (some_errors
&& !errno_unsupported (errno
)))
964 error (0, errno
, _("failed to set the security context of %s"),
965 quoteaf_n (0, dst_name
));
972 /* Change the file mode bits of the file identified by DESC or NAME to MODE.
973 Use DESC if DESC is valid and fchmod is available, NAME otherwise. */
976 fchmod_or_lchmod (int desc
, char const *name
, mode_t mode
)
980 return fchmod (desc
, mode
);
982 return lchmod (name
, mode
);
985 #ifndef HAVE_STRUCT_STAT_ST_BLOCKS
986 # define HAVE_STRUCT_STAT_ST_BLOCKS 0
989 /* Use a heuristic to determine whether stat buffer SB comes from a file
990 with sparse blocks. If the file has fewer blocks than would normally
991 be needed for a file of its size, then at least one of the blocks in
992 the file is a hole. In that case, return true. */
994 is_probably_sparse (struct stat
const *sb
)
996 return (HAVE_STRUCT_STAT_ST_BLOCKS
997 && S_ISREG (sb
->st_mode
)
998 && ST_NBLOCKS (*sb
) < sb
->st_size
/ ST_NBLOCKSIZE
);
1002 /* Copy a regular file from SRC_NAME to DST_NAME.
1003 If the source file contains holes, copies holes and blocks of zeros
1004 in the source file as holes in the destination file.
1005 (Holes are read as zeroes by the 'read' system call.)
1006 When creating the destination, use DST_MODE & ~OMITTED_PERMISSIONS
1007 as the third argument in the call to open, adding
1008 OMITTED_PERMISSIONS after copying as needed.
1009 X provides many option settings.
1010 Return true if successful.
1011 *NEW_DST is as in copy_internal.
1012 SRC_SB is the result of calling XSTAT (aka stat) on SRC_NAME. */
1015 copy_reg (char const *src_name
, char const *dst_name
,
1016 const struct cp_options
*x
,
1017 mode_t dst_mode
, mode_t omitted_permissions
, bool *new_dst
,
1018 struct stat
const *src_sb
)
1021 char *buf_alloc
= NULL
;
1022 char *name_alloc
= NULL
;
1026 mode_t src_mode
= src_sb
->st_mode
;
1028 struct stat src_open_sb
;
1029 bool return_val
= true;
1030 bool data_copy_required
= x
->data_copy_required
;
1032 source_desc
= open (src_name
,
1033 (O_RDONLY
| O_BINARY
1034 | (x
->dereference
== DEREF_NEVER
? O_NOFOLLOW
: 0)));
1035 if (source_desc
< 0)
1037 error (0, errno
, _("cannot open %s for reading"), quoteaf (src_name
));
1041 if (fstat (source_desc
, &src_open_sb
) != 0)
1043 error (0, errno
, _("cannot fstat %s"), quoteaf (src_name
));
1045 goto close_src_desc
;
1048 /* Compare the source dev/ino from the open file to the incoming,
1049 saved ones obtained via a previous call to stat. */
1050 if (! SAME_INODE (*src_sb
, src_open_sb
))
1053 _("skipping file %s, as it was replaced while being copied"),
1054 quoteaf (src_name
));
1056 goto close_src_desc
;
1059 /* The semantics of the following open calls are mandated
1060 by the specs for both cp and mv. */
1064 O_WRONLY
| O_BINARY
| (x
->data_copy_required
? O_TRUNC
: 0);
1065 dest_desc
= open (dst_name
, open_flags
);
1068 /* When using cp --preserve=context to copy to an existing destination,
1069 reset the context as per the default context, which has already been
1070 set according to the src.
1071 When using the mutually exclusive -Z option, then adjust the type of
1072 the existing context according to the system default for the dest.
1073 Note we set the context here, _after_ the file is opened, lest the
1074 new context disallow that. */
1075 if ((x
->set_security_context
|| x
->preserve_security_context
)
1078 if (! set_file_security_ctx (dst_name
, x
->preserve_security_context
,
1081 if (x
->require_preserve_context
)
1084 goto close_src_and_dst_desc
;
1089 if (dest_desc
< 0 && x
->unlink_dest_after_failed_open
)
1091 if (unlink (dst_name
) != 0)
1093 error (0, errno
, _("cannot remove %s"), quoteaf (dst_name
));
1095 goto close_src_desc
;
1098 printf (_("removed %s\n"), quoteaf (dst_name
));
1100 /* Tell caller that the destination file was unlinked. */
1103 /* Ensure there is no race where a file may be left without
1104 an appropriate security context. */
1105 if (x
->set_security_context
)
1107 if (! set_process_security_ctx (src_name
, dst_name
, dst_mode
,
1111 goto close_src_desc
;
1121 int open_flags
= O_WRONLY
| O_CREAT
| O_BINARY
;
1122 dest_desc
= open (dst_name
, open_flags
| O_EXCL
,
1123 dst_mode
& ~omitted_permissions
);
1126 /* When trying to copy through a dangling destination symlink,
1127 the above open fails with EEXIST. If that happens, and
1128 lstat'ing the DST_NAME shows that it is a symlink, then we
1129 have a problem: trying to resolve this dangling symlink to
1130 a directory/destination-entry pair is fundamentally racy,
1131 so punt. If x->open_dangling_dest_symlink is set (cp sets
1132 that when POSIXLY_CORRECT is set in the environment), simply
1133 call open again, but without O_EXCL (potentially dangerous).
1134 If not, fail with a diagnostic. These shenanigans are necessary
1135 only when copying, i.e., not in move_mode. */
1136 if (dest_desc
< 0 && dest_errno
== EEXIST
&& ! x
->move_mode
)
1138 struct stat dangling_link_sb
;
1139 if (lstat (dst_name
, &dangling_link_sb
) == 0
1140 && S_ISLNK (dangling_link_sb
.st_mode
))
1142 if (x
->open_dangling_dest_symlink
)
1144 dest_desc
= open (dst_name
, open_flags
,
1145 dst_mode
& ~omitted_permissions
);
1150 error (0, 0, _("not writing through dangling symlink %s"),
1151 quoteaf (dst_name
));
1153 goto close_src_desc
;
1158 /* Improve quality of diagnostic when a nonexistent dst_name
1159 ends in a slash and open fails with errno == EISDIR. */
1160 if (dest_desc
< 0 && dest_errno
== EISDIR
1161 && *dst_name
&& dst_name
[strlen (dst_name
) - 1] == '/')
1162 dest_errno
= ENOTDIR
;
1166 omitted_permissions
= 0;
1171 /* If we've just failed due to ENOENT for an ostensibly preexisting
1172 destination (*new_dst was 0), that's a bit of a contradiction/race:
1173 the prior stat/lstat said the file existed (*new_dst was 0), yet
1174 the subsequent open-existing-file failed with ENOENT. With NFS,
1175 the race window is wider still, since its meta-data caching tends
1176 to make the stat succeed for a just-removed remote file, while the
1177 more-definitive initial open call will fail with ENOENT. When this
1178 situation arises, we attempt to open again, but this time with
1179 O_CREAT. Do this only when not in move-mode, since when handling
1180 a cross-device move, we must never open an existing destination. */
1181 if (dest_errno
== ENOENT
&& ! *new_dst
&& ! x
->move_mode
)
1184 goto open_with_O_CREAT
;
1187 /* Otherwise, it's an error. */
1188 error (0, dest_errno
, _("cannot create regular file %s"),
1189 quoteaf (dst_name
));
1191 goto close_src_desc
;
1194 if (fstat (dest_desc
, &sb
) != 0)
1196 error (0, errno
, _("cannot fstat %s"), quoteaf (dst_name
));
1198 goto close_src_and_dst_desc
;
1201 /* --attributes-only overrides --reflink. */
1202 if (data_copy_required
&& x
->reflink_mode
)
1204 bool clone_ok
= clone_file (dest_desc
, source_desc
) == 0;
1205 if (clone_ok
|| x
->reflink_mode
== REFLINK_ALWAYS
)
1209 error (0, errno
, _("failed to clone %s from %s"),
1210 quoteaf_n (0, dst_name
), quoteaf_n (1, src_name
));
1212 goto close_src_and_dst_desc
;
1214 data_copy_required
= false;
1218 if (data_copy_required
)
1220 /* Choose a suitable buffer size; it may be adjusted later. */
1221 size_t buf_alignment
= getpagesize ();
1222 size_t buf_size
= io_blksize (sb
);
1223 size_t hole_size
= ST_BLKSIZE (sb
);
1225 fdadvise (source_desc
, 0, 0, FADVISE_SEQUENTIAL
);
1227 /* Deal with sparse files. */
1228 bool make_holes
= false;
1229 bool sparse_src
= is_probably_sparse (&src_open_sb
);
1231 if (S_ISREG (sb
.st_mode
))
1233 /* Even with --sparse=always, try to create holes only
1234 if the destination is a regular file. */
1235 if (x
->sparse_mode
== SPARSE_ALWAYS
)
1238 /* Use a heuristic to determine whether SRC_NAME contains any sparse
1239 blocks. If the file has fewer blocks than would normally be
1240 needed for a file of its size, then at least one of the blocks in
1241 the file is a hole. */
1242 if (x
->sparse_mode
== SPARSE_AUTO
&& sparse_src
)
1246 /* If not making a sparse file, try to use a more-efficient
1250 /* Compute the least common multiple of the input and output
1251 buffer sizes, adjusting for outlandish values. */
1252 size_t blcm_max
= MIN (SIZE_MAX
, SSIZE_MAX
) - buf_alignment
;
1253 size_t blcm
= buffer_lcm (io_blksize (src_open_sb
), buf_size
,
1256 /* Do not bother with a buffer larger than the input file, plus one
1257 byte to make sure the file has not grown while reading it. */
1258 if (S_ISREG (src_open_sb
.st_mode
) && src_open_sb
.st_size
< buf_size
)
1259 buf_size
= src_open_sb
.st_size
+ 1;
1261 /* However, stick with a block size that is a positive multiple of
1262 blcm, overriding the above adjustments. Watch out for
1264 buf_size
+= blcm
- 1;
1265 buf_size
-= buf_size
% blcm
;
1266 if (buf_size
== 0 || blcm_max
< buf_size
)
1270 buf_alloc
= xmalloc (buf_size
+ buf_alignment
);
1271 buf
= ptr_align (buf_alloc
, buf_alignment
);
1275 bool normal_copy_required
;
1277 /* Perform an efficient extent-based copy, falling back to the
1278 standard copy only if the initial extent scan fails. If the
1279 '--sparse=never' option is specified, write all data but use
1280 any extents to read more efficiently. */
1281 if (extent_copy (source_desc
, dest_desc
, buf
, buf_size
, hole_size
,
1282 src_open_sb
.st_size
,
1283 make_holes
? x
->sparse_mode
: SPARSE_NEVER
,
1284 src_name
, dst_name
, &normal_copy_required
))
1285 goto preserve_metadata
;
1287 if (! normal_copy_required
)
1290 goto close_src_and_dst_desc
;
1295 bool wrote_hole_at_eof
;
1296 if (! sparse_copy (source_desc
, dest_desc
, buf
, buf_size
,
1297 make_holes
? hole_size
: 0,
1298 x
->sparse_mode
== SPARSE_ALWAYS
, src_name
, dst_name
,
1299 UINTMAX_MAX
, &n_read
,
1300 &wrote_hole_at_eof
))
1303 goto close_src_and_dst_desc
;
1305 else if (wrote_hole_at_eof
&& ftruncate (dest_desc
, n_read
) < 0)
1307 error (0, errno
, _("failed to extend %s"), quoteaf (dst_name
));
1309 goto close_src_and_dst_desc
;
1314 if (x
->preserve_timestamps
)
1316 struct timespec timespec
[2];
1317 timespec
[0] = get_stat_atime (src_sb
);
1318 timespec
[1] = get_stat_mtime (src_sb
);
1320 if (fdutimens (dest_desc
, dst_name
, timespec
) != 0)
1322 error (0, errno
, _("preserving times for %s"), quoteaf (dst_name
));
1323 if (x
->require_preserve
)
1326 goto close_src_and_dst_desc
;
1331 /* Set ownership before xattrs as changing owners will
1332 clear capabilities. */
1333 if (x
->preserve_ownership
&& ! SAME_OWNER_AND_GROUP (*src_sb
, sb
))
1335 switch (set_owner (x
, dst_name
, dest_desc
, src_sb
, *new_dst
, &sb
))
1339 goto close_src_and_dst_desc
;
1342 src_mode
&= ~ (S_ISUID
| S_ISGID
| S_ISVTX
);
1347 /* To allow copying xattrs on read-only files, temporarily chmod u+rw.
1348 This workaround is required as an inode permission check is done
1349 by xattr_permission() in fs/xattr.c of the GNU/Linux kernel tree. */
1350 if (x
->preserve_xattr
)
1352 bool access_changed
= false;
1354 if (!(sb
.st_mode
& S_IWUSR
) && geteuid () != ROOT_UID
)
1355 access_changed
= fchmod_or_lchmod (dest_desc
, dst_name
, 0600) == 0;
1357 if (!copy_attr (src_name
, source_desc
, dst_name
, dest_desc
, x
)
1358 && x
->require_preserve_xattr
)
1362 fchmod_or_lchmod (dest_desc
, dst_name
, dst_mode
& ~omitted_permissions
);
1365 set_author (dst_name
, dest_desc
, src_sb
);
1367 if (x
->preserve_mode
|| x
->move_mode
)
1369 if (copy_acl (src_name
, source_desc
, dst_name
, dest_desc
, src_mode
) != 0
1370 && x
->require_preserve
)
1373 else if (x
->set_mode
)
1375 if (set_acl (dst_name
, dest_desc
, x
->mode
) != 0)
1378 else if (x
->explicit_no_preserve_mode
)
1380 if (set_acl (dst_name
, dest_desc
, 0666 & ~cached_umask ()) != 0)
1383 else if (omitted_permissions
)
1385 omitted_permissions
&= ~ cached_umask ();
1386 if (omitted_permissions
1387 && fchmod_or_lchmod (dest_desc
, dst_name
, dst_mode
) != 0)
1389 error (0, errno
, _("preserving permissions for %s"),
1390 quoteaf (dst_name
));
1391 if (x
->require_preserve
)
1396 close_src_and_dst_desc
:
1397 if (close (dest_desc
) < 0)
1399 error (0, errno
, _("failed to close %s"), quoteaf (dst_name
));
1403 if (close (source_desc
) < 0)
1405 error (0, errno
, _("failed to close %s"), quoteaf (src_name
));
1414 /* Return true if it's ok that the source and destination
1415 files are the 'same' by some measure. The goal is to avoid
1416 making the 'copy' operation remove both copies of the file
1417 in that case, while still allowing the user to e.g., move or
1418 copy a regular file onto a symlink that points to it.
1419 Try to minimize the cost of this function in the common case.
1420 Set *RETURN_NOW if we've determined that the caller has no more
1421 work to do and should return successfully, right away. */
1424 same_file_ok (char const *src_name
, struct stat
const *src_sb
,
1425 char const *dst_name
, struct stat
const *dst_sb
,
1426 const struct cp_options
*x
, bool *return_now
)
1428 const struct stat
*src_sb_link
;
1429 const struct stat
*dst_sb_link
;
1430 struct stat tmp_dst_sb
;
1431 struct stat tmp_src_sb
;
1434 bool same
= SAME_INODE (*src_sb
, *dst_sb
);
1436 *return_now
= false;
1438 /* FIXME: this should (at the very least) be moved into the following
1439 if-block. More likely, it should be removed, because it inhibits
1440 making backups. But removing it will result in a change in behavior
1441 that will probably have to be documented -- and tests will have to
1443 if (same
&& x
->hard_link
)
1449 if (x
->dereference
== DEREF_NEVER
)
1453 /* If both the source and destination files are symlinks (and we'll
1454 know this here IFF preserving symlinks), then it's usually ok
1455 when they are distinct. */
1456 if (S_ISLNK (src_sb
->st_mode
) && S_ISLNK (dst_sb
->st_mode
))
1458 bool sn
= same_name (src_name
, dst_name
);
1461 /* It's fine when we're making any type of backup. */
1462 if (x
->backup_type
!= no_backups
)
1465 /* Here we have two symlinks that are hard-linked together,
1466 and we're not making backups. In this unusual case, simply
1467 returning true would lead to mv calling "rename(A,B)",
1468 which would do nothing and return 0. */
1472 return ! x
->move_mode
;
1479 src_sb_link
= src_sb
;
1480 dst_sb_link
= dst_sb
;
1487 if (lstat (dst_name
, &tmp_dst_sb
) != 0
1488 || lstat (src_name
, &tmp_src_sb
) != 0)
1491 src_sb_link
= &tmp_src_sb
;
1492 dst_sb_link
= &tmp_dst_sb
;
1494 same_link
= SAME_INODE (*src_sb_link
, *dst_sb_link
);
1496 /* If both are symlinks, then it's ok, but only if the destination
1497 will be unlinked before being opened. This is like the test
1498 above, but with the addition of the unlink_dest_before_opening
1499 conjunct because otherwise, with two symlinks to the same target,
1500 we'd end up truncating the source file. */
1501 if (S_ISLNK (src_sb_link
->st_mode
) && S_ISLNK (dst_sb_link
->st_mode
)
1502 && x
->unlink_dest_before_opening
)
1506 /* The backup code ensures there's a copy, so it's usually ok to
1507 remove any destination file. One exception is when both
1508 source and destination are the same directory entry. In that
1509 case, moving the destination file aside (in making the backup)
1510 would also rename the source file and result in an error. */
1511 if (x
->backup_type
!= no_backups
)
1515 /* In copy mode when dereferencing symlinks, if the source is a
1516 symlink and the dest is not, then backing up the destination
1517 (moving it aside) would make it a dangling symlink, and the
1518 subsequent attempt to open it in copy_reg would fail with
1519 a misleading diagnostic. Avoid that by returning zero in
1520 that case so the caller can make cp (or mv when it has to
1521 resort to reading the source file) fail now. */
1523 /* FIXME-note: even with the following kludge, we can still provoke
1524 the offending diagnostic. It's just a little harder to do :-)
1525 $ rm -f a b c; touch c; ln -s c b; ln -s b a; cp -b a b
1526 cp: cannot open 'a' for reading: No such file or directory
1527 That's misleading, since a subsequent 'ls' shows that 'a'
1529 One solution would be to open the source file *before* moving
1530 aside the destination, but that'd involve a big rewrite. */
1532 && x
->dereference
!= DEREF_NEVER
1533 && S_ISLNK (src_sb_link
->st_mode
)
1534 && ! S_ISLNK (dst_sb_link
->st_mode
))
1540 /* FIXME: What about case insensitive file systems ? */
1541 return ! same_name (src_name
, dst_name
);
1545 /* FIXME: use or remove */
1547 /* If we're making a backup, we'll detect the problem case in
1548 copy_reg because SRC_NAME will no longer exist. Allowing
1549 the test to be deferred lets cp do some useful things.
1550 But when creating hardlinks and SRC_NAME is a symlink
1551 but DST_NAME is not we must test anyway. */
1553 || !S_ISLNK (src_sb_link
->st_mode
)
1554 || S_ISLNK (dst_sb_link
->st_mode
))
1557 if (x
->dereference
!= DEREF_NEVER
)
1561 if (x
->move_mode
|| x
->unlink_dest_before_opening
)
1563 /* They may refer to the same file if we're in move mode and the
1564 target is a symlink. That is ok, since we remove any existing
1565 destination file before opening it -- via 'rename' if they're on
1566 the same file system, via 'unlink (DST_NAME)' otherwise. */
1567 if (S_ISLNK (dst_sb_link
->st_mode
))
1570 /* It's not ok if they're distinct hard links to the same file as
1571 this causes a race condition and we may lose data in this case. */
1573 && 1 < dst_sb_link
->st_nlink
1574 && ! same_name (src_name
, dst_name
))
1575 return ! x
->move_mode
;
1578 /* If neither is a symlink, then it's ok as long as they aren't
1579 hard links to the same file. */
1580 if (!S_ISLNK (src_sb_link
->st_mode
) && !S_ISLNK (dst_sb_link
->st_mode
))
1582 if (!SAME_INODE (*src_sb_link
, *dst_sb_link
))
1585 /* If they are the same file, it's ok if we're making hard links. */
1593 /* At this point, it is normally an error (data loss) to move a symlink
1594 onto its referent, but in at least one narrow case, it is not:
1596 1) src is a symlink,
1597 2) dest has a link count of 2 or more and
1598 3) dest and the referent of src are not the same directory entry,
1599 then it's ok, since while we'll lose one of those hard links,
1600 src will still point to a remaining link.
1601 Note that technically, condition #3 obviates condition #2, but we
1602 retain the 1 < st_nlink condition because that means fewer invocations
1603 of the more expensive #3.
1606 $ touch f && ln f l && ln -s f s
1608 -rw-------. 2 0 Jan 4 22:46 f
1609 -rw-------. 2 0 Jan 4 22:46 l
1610 lrwxrwxrwx. 1 1 Jan 4 22:46 s -> f
1611 this must fail: mv s f
1612 this must succeed: mv s l */
1614 && S_ISLNK (src_sb
->st_mode
)
1615 && 1 < dst_sb_link
->st_nlink
)
1617 char *abs_src
= canonicalize_file_name (src_name
);
1620 bool result
= ! same_name (abs_src
, dst_name
);
1626 /* It's ok to remove a destination symlink. But that works only
1627 when creating symbolic links, or when the source and destination
1628 are on the same file system and when creating hard links or when
1629 unlinking before opening the destination. */
1630 if (x
->symbolic_link
1631 || ((x
->hard_link
|| x
->unlink_dest_before_opening
)
1632 && S_ISLNK (dst_sb_link
->st_mode
)))
1633 return dst_sb_link
->st_dev
== src_sb_link
->st_dev
;
1635 if (x
->dereference
== DEREF_NEVER
)
1637 if ( ! S_ISLNK (src_sb_link
->st_mode
))
1638 tmp_src_sb
= *src_sb_link
;
1639 else if (stat (src_name
, &tmp_src_sb
) != 0)
1642 if ( ! S_ISLNK (dst_sb_link
->st_mode
))
1643 tmp_dst_sb
= *dst_sb_link
;
1644 else if (stat (dst_name
, &tmp_dst_sb
) != 0)
1647 if ( ! SAME_INODE (tmp_src_sb
, tmp_dst_sb
))
1650 /* FIXME: shouldn't this be testing whether we're making symlinks? */
1661 /* Return true if FILE, with mode MODE, is writable in the sense of 'mv'.
1662 Always consider a symbolic link to be writable. */
1664 writable_destination (char const *file
, mode_t mode
)
1666 return (S_ISLNK (mode
)
1667 || can_write_any_file ()
1668 || euidaccess (file
, W_OK
) == 0);
1672 overwrite_ok (struct cp_options
const *x
, char const *dst_name
,
1673 struct stat
const *dst_sb
)
1675 if (! writable_destination (dst_name
, dst_sb
->st_mode
))
1677 char perms
[12]; /* "-rwxrwxrwx " ls-style modes. */
1678 strmode (dst_sb
->st_mode
, perms
);
1681 (x
->move_mode
|| x
->unlink_dest_before_opening
1682 || x
->unlink_dest_after_failed_open
)
1683 ? _("%s: replace %s, overriding mode %04lo (%s)? ")
1684 : _("%s: unwritable %s (mode %04lo, %s); try anyway? "),
1685 program_name
, quoteaf (dst_name
),
1686 (unsigned long int) (dst_sb
->st_mode
& CHMOD_MODE_BITS
),
1691 fprintf (stderr
, _("%s: overwrite %s? "),
1692 program_name
, quoteaf (dst_name
));
1698 /* Initialize the hash table implementing a set of F_triple entries
1699 corresponding to destination files. */
1701 dest_info_init (struct cp_options
*x
)
1704 = hash_initialize (DEST_INFO_INITIAL_CAPACITY
,
1711 /* Initialize the hash table implementing a set of F_triple entries
1712 corresponding to source files listed on the command line. */
1714 src_info_init (struct cp_options
*x
)
1717 /* Note that we use triple_hash_no_name here.
1718 Contrast with the use of triple_hash above.
1719 That is necessary because a source file may be specified
1720 in many different ways. We want to warn about this
1726 = hash_initialize (DEST_INFO_INITIAL_CAPACITY
,
1728 triple_hash_no_name
,
1733 /* When effecting a move (e.g., for mv(1)), and given the name DST_NAME
1734 of the destination and a corresponding stat buffer, DST_SB, return
1735 true if the logical 'move' operation should _not_ proceed.
1736 Otherwise, return false.
1737 Depending on options specified in X, this code may issue an
1738 interactive prompt asking whether it's ok to overwrite DST_NAME. */
1740 abandon_move (const struct cp_options
*x
,
1741 char const *dst_name
,
1742 struct stat
const *dst_sb
)
1744 assert (x
->move_mode
);
1745 return (x
->interactive
== I_ALWAYS_NO
1746 || ((x
->interactive
== I_ASK_USER
1747 || (x
->interactive
== I_UNSPECIFIED
1749 && ! writable_destination (dst_name
, dst_sb
->st_mode
)))
1750 && ! overwrite_ok (x
, dst_name
, dst_sb
)));
1753 /* Print --verbose output on standard output, e.g. 'new' -> 'old'.
1754 If BACKUP_DST_NAME is non-NULL, then also indicate that it is
1755 the name of a backup file. */
1757 emit_verbose (char const *src
, char const *dst
, char const *backup_dst_name
)
1759 printf ("%s -> %s", quoteaf_n (0, src
), quoteaf_n (1, dst
));
1760 if (backup_dst_name
)
1761 printf (_(" (backup: %s)"), quoteaf (backup_dst_name
));
1765 /* A wrapper around "setfscreatecon (NULL)" that exits upon failure. */
1767 restore_default_fscreatecon_or_die (void)
1769 if (setfscreatecon (NULL
) != 0)
1770 die (EXIT_FAILURE
, errno
,
1771 _("failed to restore the default file creation context"));
1774 /* Create a hard link DST_NAME to SRC_NAME, honoring the REPLACE, VERBOSE and
1775 DEREFERENCE settings. Return true upon success. Otherwise, diagnose the
1776 failure and return false. If SRC_NAME is a symbolic link, then it will not
1777 be followed unless DEREFERENCE is true.
1778 If the system doesn't support hard links to symbolic links, then DST_NAME
1779 will be created as a symbolic link to SRC_NAME. */
1781 create_hard_link (char const *src_name
, char const *dst_name
,
1782 bool replace
, bool verbose
, bool dereference
)
1784 int status
= force_linkat (AT_FDCWD
, src_name
, AT_FDCWD
, dst_name
,
1785 dereference
? AT_SYMLINK_FOLLOW
: 0,
1789 error (0, errno
, _("cannot create hard link %s to %s"),
1790 quoteaf_n (0, dst_name
), quoteaf_n (1, src_name
));
1793 if (0 < status
&& verbose
)
1794 printf (_("removed %s\n"), quoteaf (dst_name
));
1798 /* Return true if the current file should be (tried to be) dereferenced:
1799 either for DEREF_ALWAYS or for DEREF_COMMAND_LINE_ARGUMENTS in the case
1800 where the current file is a COMMAND_LINE_ARG; otherwise return false. */
1801 static inline bool _GL_ATTRIBUTE_PURE
1802 should_dereference (const struct cp_options
*x
, bool command_line_arg
)
1804 return x
->dereference
== DEREF_ALWAYS
1805 || (x
->dereference
== DEREF_COMMAND_LINE_ARGUMENTS
1806 && command_line_arg
);
1809 /* Return true if the source file with basename SRCBASE and status SRC_ST
1810 is likely to be the simple backup file for DST_NAME. */
1812 source_is_dst_backup (char const *srcbase
, struct stat
const *src_st
,
1813 char const *dst_name
)
1815 size_t srcbaselen
= strlen (srcbase
);
1816 char const *dstbase
= last_component (dst_name
);
1817 size_t dstbaselen
= strlen (dstbase
);
1818 size_t suffixlen
= strlen (simple_backup_suffix
);
1819 if (! (srcbaselen
== dstbaselen
+ suffixlen
1820 && memcmp (srcbase
, dstbase
, dstbaselen
) == 0
1821 && STREQ (srcbase
+ dstbaselen
, simple_backup_suffix
)))
1823 size_t dstlen
= strlen (dst_name
);
1824 char *dst_back
= xmalloc (dstlen
+ suffixlen
+ 1);
1825 strcpy (mempcpy (dst_back
, dst_name
, dstlen
), simple_backup_suffix
);
1826 struct stat dst_back_sb
;
1827 int dst_back_status
= stat (dst_back
, &dst_back_sb
);
1829 return dst_back_status
== 0 && SAME_INODE (*src_st
, dst_back_sb
);
1832 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
1833 any type. NEW_DST should be true if the file DST_NAME cannot
1834 exist because its parent directory was just created; NEW_DST should
1835 be false if DST_NAME might already exist. A non-null PARENT describes the
1836 parent directory. ANCESTORS points to a linked, null terminated list of
1837 devices and inodes of parent directories of SRC_NAME. COMMAND_LINE_ARG
1838 is true iff SRC_NAME was specified on the command line.
1839 FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG is both input and output.
1840 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
1841 same as) DST_NAME; otherwise, clear it.
1842 Return true if successful. */
1844 copy_internal (char const *src_name
, char const *dst_name
,
1846 struct stat
const *parent
,
1847 struct dir_list
*ancestors
,
1848 const struct cp_options
*x
,
1849 bool command_line_arg
,
1850 bool *first_dir_created_per_command_line_arg
,
1851 bool *copy_into_self
,
1852 bool *rename_succeeded
)
1857 mode_t dst_mode
IF_LINT ( = 0);
1858 mode_t dst_mode_bits
;
1859 mode_t omitted_permissions
;
1860 bool restore_dst_mode
= false;
1861 char *earlier_file
= NULL
;
1862 char *dst_backup
= NULL
;
1864 bool copied_as_regular
= false;
1865 bool dest_is_symlink
= false;
1866 bool have_dst_lstat
= false;
1868 if (x
->move_mode
&& rename_succeeded
)
1869 *rename_succeeded
= false;
1871 *copy_into_self
= false;
1873 if (XSTAT (x
, src_name
, &src_sb
) != 0)
1875 error (0, errno
, _("cannot stat %s"), quoteaf (src_name
));
1879 src_mode
= src_sb
.st_mode
;
1881 if (S_ISDIR (src_mode
) && !x
->recursive
)
1883 error (0, 0, ! x
->install_mode
/* cp */
1884 ? _("-r not specified; omitting directory %s")
1885 : _("omitting directory %s"),
1886 quoteaf (src_name
));
1890 /* Detect the case in which the same source file appears more than
1891 once on the command line and no backup option has been selected.
1892 If so, simply warn and don't copy it the second time.
1893 This check is enabled only if x->src_info is non-NULL. */
1894 if (command_line_arg
)
1896 if ( ! S_ISDIR (src_sb
.st_mode
)
1897 && x
->backup_type
== no_backups
1898 && seen_file (x
->src_info
, src_name
, &src_sb
))
1900 error (0, 0, _("warning: source file %s specified more than once"),
1901 quoteaf (src_name
));
1905 record_file (x
->src_info
, src_name
, &src_sb
);
1908 bool dereference
= should_dereference (x
, command_line_arg
);
1912 /* Regular files can be created by writing through symbolic
1913 links, but other files cannot. So use stat on the
1914 destination when copying a regular file, and lstat otherwise.
1915 However, if we intend to unlink or remove the destination
1916 first, use lstat, since a copy won't actually be made to the
1917 destination in that case. */
1919 ((S_ISREG (src_mode
)
1920 || (x
->copy_as_regular
1921 && ! (S_ISDIR (src_mode
) || S_ISLNK (src_mode
))))
1922 && ! (x
->move_mode
|| x
->symbolic_link
|| x
->hard_link
1923 || x
->backup_type
!= no_backups
1924 || x
->unlink_dest_before_opening
));
1926 ? stat (dst_name
, &dst_sb
)
1927 : lstat (dst_name
, &dst_sb
))
1930 if (errno
!= ENOENT
)
1932 error (0, errno
, _("cannot stat %s"), quoteaf (dst_name
));
1941 { /* Here, we know that dst_name exists, at least to the point
1942 that it is stat'able or lstat'able. */
1945 have_dst_lstat
= !use_stat
;
1946 if (! same_file_ok (src_name
, &src_sb
, dst_name
, &dst_sb
,
1949 error (0, 0, _("%s and %s are the same file"),
1950 quoteaf_n (0, src_name
), quoteaf_n (1, dst_name
));
1954 if (!S_ISDIR (src_mode
) && x
->update
)
1956 /* When preserving timestamps (but not moving within a file
1957 system), don't worry if the destination timestamp is
1958 less than the source merely because of timestamp
1960 int options
= ((x
->preserve_timestamps
1962 && dst_sb
.st_dev
== src_sb
.st_dev
))
1963 ? UTIMECMP_TRUNCATE_SOURCE
1966 if (0 <= utimecmp (dst_name
, &dst_sb
, &src_sb
, options
))
1968 /* We're using --update and the destination is not older
1969 than the source, so do not copy or move. Pretend the
1970 rename succeeded, so the caller (if it's mv) doesn't
1971 end up removing the source file. */
1972 if (rename_succeeded
)
1973 *rename_succeeded
= true;
1975 /* However, we still must record that we've processed
1976 this src/dest pair, in case this source file is
1977 hard-linked to another one. In that case, we'll use
1978 the mapping information to link the corresponding
1979 destination names. */
1980 earlier_file
= remember_copied (dst_name
, src_sb
.st_ino
,
1984 /* Note we currently replace DST_NAME unconditionally,
1985 even if it was a newer separate file. */
1986 if (! create_hard_link (earlier_file
, dst_name
, true,
1987 x
->verbose
, dereference
))
1997 /* When there is an existing destination file, we may end up
1998 returning early, and hence not copying/moving the file.
1999 This may be due to an interactive 'negative' reply to the
2000 prompt about the existing file. It may also be due to the
2001 use of the --no-clobber option.
2003 cp and mv treat -i and -f differently. */
2006 if (abandon_move (x
, dst_name
, &dst_sb
))
2008 /* Pretend the rename succeeded, so the caller (mv)
2009 doesn't end up removing the source file. */
2010 if (rename_succeeded
)
2011 *rename_succeeded
= true;
2017 if (! S_ISDIR (src_mode
)
2018 && (x
->interactive
== I_ALWAYS_NO
2019 || (x
->interactive
== I_ASK_USER
2020 && ! overwrite_ok (x
, dst_name
, &dst_sb
))))
2027 if (!S_ISDIR (dst_sb
.st_mode
))
2029 if (S_ISDIR (src_mode
))
2031 if (x
->move_mode
&& x
->backup_type
!= no_backups
)
2033 /* Moving a directory onto an existing
2034 non-directory is ok only with --backup. */
2039 _("cannot overwrite non-directory %s with directory %s"),
2040 quoteaf_n (0, dst_name
), quoteaf_n (1, src_name
));
2045 /* Don't let the user destroy their data, even if they try hard:
2046 This mv command must fail (likewise for cp):
2047 rm -rf a b c; mkdir a b c; touch a/f b/f; mv a/f b/f c
2048 Otherwise, the contents of b/f would be lost.
2049 In the case of 'cp', b/f would be lost if the user simulated
2050 a move using cp and rm.
2051 Note that it works fine if you use --backup=numbered. */
2052 if (command_line_arg
2053 && x
->backup_type
!= numbered_backups
2054 && seen_file (x
->dest_info
, dst_name
, &dst_sb
))
2057 _("will not overwrite just-created %s with %s"),
2058 quoteaf_n (0, dst_name
), quoteaf_n (1, src_name
));
2063 if (!S_ISDIR (src_mode
))
2065 if (S_ISDIR (dst_sb
.st_mode
))
2067 if (x
->move_mode
&& x
->backup_type
!= no_backups
)
2069 /* Moving a non-directory onto an existing
2070 directory is ok only with --backup. */
2075 _("cannot overwrite directory %s with non-directory"),
2076 quoteaf (dst_name
));
2084 /* Don't allow user to move a directory onto a non-directory. */
2085 if (S_ISDIR (src_sb
.st_mode
) && !S_ISDIR (dst_sb
.st_mode
)
2086 && x
->backup_type
== no_backups
)
2089 _("cannot move directory onto non-directory: %s -> %s"),
2090 quotef_n (0, src_name
), quotef_n (0, dst_name
));
2095 char const *srcbase
;
2096 if (x
->backup_type
!= no_backups
2097 /* Don't try to back up a destination if the last
2098 component of src_name is "." or "..". */
2099 && ! dot_or_dotdot (srcbase
= last_component (src_name
))
2100 /* Create a backup of each destination directory in move mode,
2101 but not in copy mode. FIXME: it might make sense to add an
2102 option to suppress backup creation also for move mode.
2103 That would let one use mv to merge new content into an
2104 existing hierarchy. */
2105 && (x
->move_mode
|| ! S_ISDIR (dst_sb
.st_mode
)))
2107 /* Fail if creating the backup file would likely destroy
2108 the source file. Otherwise, the commands:
2109 cd /tmp; rm -f a a~; : > a; echo A > a~; cp --b=simple a~ a
2110 would leave two zero-length files: a and a~. */
2111 if (x
->backup_type
!= numbered_backups
2112 && source_is_dst_backup (srcbase
, &src_sb
, dst_name
))
2116 ? _("backing up %s might destroy source; %s not moved")
2117 : _("backing up %s might destroy source; %s not copied"));
2119 quoteaf_n (0, dst_name
),
2120 quoteaf_n (1, src_name
));
2124 char *tmp_backup
= backup_file_rename (dst_name
, x
->backup_type
);
2127 Using alloca for a file name that may be arbitrarily
2128 long is not recommended. In fact, even forming such a name
2129 should be discouraged. Eventually, this code will be rewritten
2130 to use fts, so using alloca here will be less of a problem. */
2133 ASSIGN_STRDUPA (dst_backup
, tmp_backup
);
2136 else if (errno
!= ENOENT
)
2138 error (0, errno
, _("cannot backup %s"), quoteaf (dst_name
));
2143 else if (! S_ISDIR (dst_sb
.st_mode
)
2144 /* Never unlink dst_name when in move mode. */
2146 && (x
->unlink_dest_before_opening
2147 || (x
->preserve_links
&& 1 < dst_sb
.st_nlink
)
2148 || (x
->dereference
== DEREF_NEVER
2149 && ! S_ISREG (src_sb
.st_mode
))
2152 if (unlink (dst_name
) != 0 && errno
!= ENOENT
)
2154 error (0, errno
, _("cannot remove %s"), quoteaf (dst_name
));
2159 printf (_("removed %s\n"), quoteaf (dst_name
));
2164 /* Ensure we don't try to copy through a symlink that was
2165 created by a prior call to this function. */
2166 if (command_line_arg
2169 && x
->backup_type
== no_backups
)
2171 bool lstat_ok
= true;
2172 struct stat tmp_buf
;
2173 struct stat
*dst_lstat_sb
;
2175 /* If we called lstat above, good: use that data.
2176 Otherwise, call lstat here, in case dst_name is a symlink. */
2178 dst_lstat_sb
= &dst_sb
;
2181 if (lstat (dst_name
, &tmp_buf
) == 0)
2182 dst_lstat_sb
= &tmp_buf
;
2187 /* Never copy through a symlink we've just created. */
2189 && S_ISLNK (dst_lstat_sb
->st_mode
)
2190 && seen_file (x
->dest_info
, dst_name
, dst_lstat_sb
))
2193 _("will not copy %s through just-created symlink %s"),
2194 quoteaf_n (0, src_name
), quoteaf_n (1, dst_name
));
2199 /* If the source is a directory, we don't always create the destination
2200 directory. So --verbose should not announce anything until we're
2201 sure we'll create a directory. Also don't announce yet when moving
2202 so we can distinguish renames versus copies. */
2203 if (x
->verbose
&& !x
->move_mode
&& !S_ISDIR (src_mode
))
2204 emit_verbose (src_name
, dst_name
, dst_backup
);
2206 /* Associate the destination file name with the source device and inode
2207 so that if we encounter a matching dev/ino pair in the source tree
2208 we can arrange to create a hard link between the corresponding names
2209 in the destination tree.
2211 When using the --link (-l) option, there is no need to take special
2212 measures, because (barring race conditions) files that are hard-linked
2213 in the source tree will also be hard-linked in the destination tree.
2215 Sometimes, when preserving links, we have to record dev/ino even
2216 though st_nlink == 1:
2217 - when in move_mode, since we may be moving a group of N hard-linked
2218 files (via two or more command line arguments) to a different
2219 partition; the links may be distributed among the command line
2220 arguments (possibly hierarchies) so that the link count of
2221 the final, once-linked source file is reduced to 1 when it is
2222 considered below. But in this case (for mv) we don't need to
2223 incur the expense of recording the dev/ino => name mapping; all we
2224 really need is a lookup, to see if the dev/ino pair has already
2226 - when using -H and processing a command line argument;
2227 that command line argument could be a symlink pointing to another
2228 command line argument. With 'cp -H --preserve=link', we hard-link
2229 those two destination files.
2230 - likewise for -L except that it applies to all files, not just
2231 command line arguments.
2233 Also, with --recursive, record dev/ino of each command-line directory.
2234 We'll use that info to detect this problem: cp -R dir dir. */
2236 if (x
->recursive
&& S_ISDIR (src_mode
))
2238 if (command_line_arg
)
2239 earlier_file
= remember_copied (dst_name
, src_sb
.st_ino
, src_sb
.st_dev
);
2241 earlier_file
= src_to_dest_lookup (src_sb
.st_ino
, src_sb
.st_dev
);
2243 else if (x
->move_mode
&& src_sb
.st_nlink
== 1)
2245 earlier_file
= src_to_dest_lookup (src_sb
.st_ino
, src_sb
.st_dev
);
2247 else if (x
->preserve_links
2249 && (1 < src_sb
.st_nlink
2250 || (command_line_arg
2251 && x
->dereference
== DEREF_COMMAND_LINE_ARGUMENTS
)
2252 || x
->dereference
== DEREF_ALWAYS
))
2254 earlier_file
= remember_copied (dst_name
, src_sb
.st_ino
, src_sb
.st_dev
);
2257 /* Did we copy this inode somewhere else (in this command line argument)
2258 and therefore this is a second hard link to the inode? */
2262 /* Avoid damaging the destination file system by refusing to preserve
2263 hard-linked directories (which are found at least in Netapp snapshot
2265 if (S_ISDIR (src_mode
))
2267 /* If src_name and earlier_file refer to the same directory entry,
2268 then warn about copying a directory into itself. */
2269 if (same_name (src_name
, earlier_file
))
2271 error (0, 0, _("cannot copy a directory, %s, into itself, %s"),
2272 quoteaf_n (0, top_level_src_name
),
2273 quoteaf_n (1, top_level_dst_name
));
2274 *copy_into_self
= true;
2277 else if (same_name (dst_name
, earlier_file
))
2279 error (0, 0, _("warning: source directory %s "
2280 "specified more than once"),
2281 quoteaf (top_level_src_name
));
2282 /* In move mode, if a previous rename succeeded, then
2283 we won't be in this path as the source is missing. If the
2284 rename previously failed, then that has been handled, so
2285 pretend this attempt succeeded so the source isn't removed. */
2286 if (x
->move_mode
&& rename_succeeded
)
2287 *rename_succeeded
= true;
2288 /* We only do backups in move mode, and for non directories.
2289 So just ignore this repeated entry. */
2292 else if (x
->dereference
== DEREF_ALWAYS
2293 || (command_line_arg
2294 && x
->dereference
== DEREF_COMMAND_LINE_ARGUMENTS
))
2296 /* This happens when e.g., encountering a directory for the
2297 second or subsequent time via symlinks when cp is invoked
2298 with -R and -L. E.g.,
2299 rm -rf a b c d; mkdir a b c d; ln -s ../c a; ln -s ../c b;
2305 error (0, 0, _("will not create hard link %s to directory %s"),
2306 quoteaf_n (0, dst_name
), quoteaf_n (1, earlier_file
));
2312 if (! create_hard_link (earlier_file
, dst_name
, true, x
->verbose
,
2322 if (rename (src_name
, dst_name
) == 0)
2326 printf (_("renamed "));
2327 emit_verbose (src_name
, dst_name
, dst_backup
);
2330 if (x
->set_security_context
)
2332 /* -Z failures are only warnings currently. */
2333 (void) set_file_security_ctx (dst_name
, false, true, x
);
2336 if (rename_succeeded
)
2337 *rename_succeeded
= true;
2339 if (command_line_arg
)
2341 /* Record destination dev/ino/name, so that if we are asked
2342 to overwrite that file again, we can detect it and fail. */
2343 /* It's fine to use the _source_ stat buffer (src_sb) to get the
2344 _destination_ dev/ino, since the rename above can't have
2345 changed those, and 'mv' always uses lstat.
2346 We could limit it further by operating
2347 only on non-directories. */
2348 record_file (x
->dest_info
, dst_name
, &src_sb
);
2354 /* FIXME: someday, consider what to do when moving a directory into
2355 itself but when source and destination are on different devices. */
2357 /* This happens when attempting to rename a directory to a
2358 subdirectory of itself. */
2359 if (errno
== EINVAL
)
2361 /* FIXME: this is a little fragile in that it relies on rename(2)
2362 failing with a specific errno value. Expect problems on
2363 non-POSIX systems. */
2364 error (0, 0, _("cannot move %s to a subdirectory of itself, %s"),
2365 quoteaf_n (0, top_level_src_name
),
2366 quoteaf_n (1, top_level_dst_name
));
2368 /* Note that there is no need to call forget_created here,
2369 (compare with the other calls in this file) since the
2370 destination directory didn't exist before. */
2372 *copy_into_self
= true;
2373 /* FIXME-cleanup: Don't return true here; adjust mv.c accordingly.
2374 The only caller that uses this code (mv.c) ends up setting its
2375 exit status to nonzero when copy_into_self is nonzero. */
2379 /* WARNING: there probably exist systems for which an inter-device
2380 rename fails with a value of errno not handled here.
2381 If/as those are reported, add them to the condition below.
2382 If this happens to you, please do the following and send the output
2383 to the bug-reporting address (e.g., in the output of cp --help):
2384 touch k; perl -e 'rename "k","/tmp/k" or print "$!(",$!+0,")\n"'
2385 where your current directory is on one partition and /tmp is the other.
2386 Also, please try to find the E* errno macro name corresponding to
2387 the diagnostic and parenthesized integer, and include that in your
2388 e-mail. One way to do that is to run a command like this
2389 find /usr/include/. -type f \
2390 | xargs grep 'define.*\<E[A-Z]*\>.*\<18\>' /dev/null
2391 where you'd replace '18' with the integer in parentheses that
2392 was output from the perl one-liner above.
2393 If necessary, of course, change '/tmp' to some other directory. */
2396 /* There are many ways this can happen due to a race condition.
2397 When something happens between the initial XSTAT and the
2398 subsequent rename, we can get many different types of errors.
2399 For example, if the destination is initially a non-directory
2400 or non-existent, but it is created as a directory, the rename
2401 fails. If two 'mv' commands try to rename the same file at
2402 about the same time, one will succeed and the other will fail.
2403 If the permissions on the directory containing the source or
2404 destination file are made too restrictive, the rename will
2407 _("cannot move %s to %s"),
2408 quoteaf_n (0, src_name
), quoteaf_n (1, dst_name
));
2409 forget_created (src_sb
.st_ino
, src_sb
.st_dev
);
2413 /* The rename attempt has failed. Remove any existing destination
2414 file so that a cross-device 'mv' acts as if it were really using
2415 the rename syscall. Note both src and dst must both be directories
2416 or not, and this is enforced above. Therefore we check the src_mode
2417 and operate on dst_name here as a tighter constraint and also because
2418 src_mode is readily available here. */
2419 if ((S_ISDIR (src_mode
) ? rmdir (dst_name
) : unlink (dst_name
)) != 0
2423 _("inter-device move failed: %s to %s; unable to remove target"),
2424 quoteaf_n (0, src_name
), quoteaf_n (1, dst_name
));
2425 forget_created (src_sb
.st_ino
, src_sb
.st_dev
);
2429 if (x
->verbose
&& !S_ISDIR (src_mode
))
2431 printf (_("copied "));
2432 emit_verbose (src_name
, dst_name
, dst_backup
);
2437 /* If the ownership might change, or if it is a directory (whose
2438 special mode bits may change after the directory is created),
2439 omit some permissions at first, so unauthorized users cannot nip
2440 in before the file is ready. */
2441 dst_mode_bits
= (x
->set_mode
? x
->mode
: src_mode
) & CHMOD_MODE_BITS
;
2442 omitted_permissions
=
2444 & (x
->preserve_ownership
? S_IRWXG
| S_IRWXO
2445 : S_ISDIR (src_mode
) ? S_IWGRP
| S_IWOTH
2450 /* If required, set the default security context for new files.
2451 Also for existing files this is used as a reference
2452 when copying the context with --preserve=context.
2453 FIXME: Do we need to consider dst_mode_bits here? */
2454 if (! set_process_security_ctx (src_name
, dst_name
, src_mode
, new_dst
, x
))
2457 if (S_ISDIR (src_mode
))
2459 struct dir_list
*dir
;
2461 /* If this directory has been copied before during the
2462 recursion, there is a symbolic link to an ancestor
2463 directory of the symbolic link. It is impossible to
2464 continue to copy this, unless we've got an infinite disk. */
2466 if (is_ancestor (&src_sb
, ancestors
))
2468 error (0, 0, _("cannot copy cyclic symbolic link %s"),
2469 quoteaf (src_name
));
2473 /* Insert the current directory in the list of parents. */
2475 dir
= alloca (sizeof *dir
);
2476 dir
->parent
= ancestors
;
2477 dir
->ino
= src_sb
.st_ino
;
2478 dir
->dev
= src_sb
.st_dev
;
2480 if (new_dst
|| !S_ISDIR (dst_sb
.st_mode
))
2482 /* POSIX says mkdir's behavior is implementation-defined when
2483 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
2484 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
2485 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
2486 if (mkdir (dst_name
, dst_mode_bits
& ~omitted_permissions
) != 0)
2488 error (0, errno
, _("cannot create directory %s"),
2489 quoteaf (dst_name
));
2493 /* We need search and write permissions to the new directory
2494 for writing the directory's contents. Check if these
2495 permissions are there. */
2497 if (lstat (dst_name
, &dst_sb
) != 0)
2499 error (0, errno
, _("cannot stat %s"), quoteaf (dst_name
));
2502 else if ((dst_sb
.st_mode
& S_IRWXU
) != S_IRWXU
)
2504 /* Make the new directory searchable and writable. */
2506 dst_mode
= dst_sb
.st_mode
;
2507 restore_dst_mode
= true;
2509 if (lchmod (dst_name
, dst_mode
| S_IRWXU
) != 0)
2511 error (0, errno
, _("setting permissions for %s"),
2512 quoteaf (dst_name
));
2517 /* Record the created directory's inode and device numbers into
2518 the search structure, so that we can avoid copying it again.
2519 Do this only for the first directory that is created for each
2520 source command line argument. */
2521 if (!*first_dir_created_per_command_line_arg
)
2523 remember_copied (dst_name
, dst_sb
.st_ino
, dst_sb
.st_dev
);
2524 *first_dir_created_per_command_line_arg
= true;
2530 printf (_("created directory %s\n"), quoteaf (dst_name
));
2532 emit_verbose (src_name
, dst_name
, NULL
);
2537 omitted_permissions
= 0;
2539 /* For directories, the process global context could be reset for
2540 descendents, so use it to set the context for existing dirs here.
2541 This will also give earlier indication of failure to set ctx. */
2542 if (x
->set_security_context
|| x
->preserve_security_context
)
2543 if (! set_file_security_ctx (dst_name
, x
->preserve_security_context
,
2546 if (x
->require_preserve_context
)
2551 /* Decide whether to copy the contents of the directory. */
2552 if (x
->one_file_system
&& parent
&& parent
->st_dev
!= src_sb
.st_dev
)
2554 /* Here, we are crossing a file system boundary and cp's -x option
2555 is in effect: so don't copy the contents of this directory. */
2559 /* Copy the contents of the directory. Don't just return if
2560 this fails -- otherwise, the failure to read a single file
2561 in a source directory would cause the containing destination
2562 directory not to have owner/perms set properly. */
2563 delayed_ok
= copy_dir (src_name
, dst_name
, new_dst
, &src_sb
, dir
, x
,
2564 first_dir_created_per_command_line_arg
,
2568 else if (x
->symbolic_link
)
2570 dest_is_symlink
= true;
2571 if (*src_name
!= '/')
2573 /* Check that DST_NAME denotes a file in the current directory. */
2575 struct stat dst_parent_sb
;
2577 bool in_current_dir
;
2579 dst_parent
= dir_name (dst_name
);
2581 in_current_dir
= (STREQ (".", dst_parent
)
2582 /* If either stat call fails, it's ok not to report
2583 the failure and say dst_name is in the current
2584 directory. Other things will fail later. */
2585 || stat (".", &dot_sb
) != 0
2586 || stat (dst_parent
, &dst_parent_sb
) != 0
2587 || SAME_INODE (dot_sb
, dst_parent_sb
));
2590 if (! in_current_dir
)
2593 _("%s: can make relative symbolic links only in current directory"),
2598 if (force_symlinkat (src_name
, AT_FDCWD
, dst_name
,
2599 x
->unlink_dest_after_failed_open
)
2602 error (0, errno
, _("cannot create symbolic link %s to %s"),
2603 quoteaf_n (0, dst_name
), quoteaf_n (1, src_name
));
2608 /* POSIX 2008 states that it is implementation-defined whether
2609 link() on a symlink creates a hard-link to the symlink, or only
2610 to the referent (effectively dereferencing the symlink) (POSIX
2611 2001 required the latter behavior, although many systems provided
2612 the former). Yet cp, invoked with '--link --no-dereference',
2613 should not follow the link. We can approximate the desired
2614 behavior by skipping this hard-link creating block and instead
2615 copying the symlink, via the 'S_ISLNK'- copying code below.
2617 Note gnulib's linkat module, guarantees that the symlink is not
2618 dereferenced. However its emulation currently doesn't maintain
2619 timestamps or ownership so we only call it when we know the
2620 emulation will not be needed. */
2621 else if (x
->hard_link
2622 && !(! CAN_HARDLINK_SYMLINKS
&& S_ISLNK (src_mode
)
2623 && x
->dereference
== DEREF_NEVER
))
2625 if (! create_hard_link (src_name
, dst_name
,
2626 x
->unlink_dest_after_failed_open
,
2627 false, dereference
))
2630 else if (S_ISREG (src_mode
)
2631 || (x
->copy_as_regular
&& !S_ISLNK (src_mode
)))
2633 copied_as_regular
= true;
2634 /* POSIX says the permission bits of the source file must be
2635 used as the 3rd argument in the open call. Historical
2636 practice passed all the source mode bits to 'open', but the extra
2637 bits were ignored, so it should be the same either way.
2639 This call uses DST_MODE_BITS, not SRC_MODE. These are
2640 normally the same, and the exception (where x->set_mode) is
2641 used only by 'install', which POSIX does not specify and
2642 where DST_MODE_BITS is what's wanted. */
2643 if (! copy_reg (src_name
, dst_name
, x
, dst_mode_bits
& S_IRWXUGO
,
2644 omitted_permissions
, &new_dst
, &src_sb
))
2647 else if (S_ISFIFO (src_mode
))
2649 /* Use mknod, rather than mkfifo, because the former preserves
2650 the special mode bits of a fifo on Solaris 10, while mkfifo
2651 does not. But fall back on mkfifo, because on some BSD systems,
2652 mknod always fails when asked to create a FIFO. */
2653 if (mknod (dst_name
, src_mode
& ~omitted_permissions
, 0) != 0)
2654 if (mkfifo (dst_name
, src_mode
& ~S_IFIFO
& ~omitted_permissions
) != 0)
2656 error (0, errno
, _("cannot create fifo %s"), quoteaf (dst_name
));
2660 else if (S_ISBLK (src_mode
) || S_ISCHR (src_mode
) || S_ISSOCK (src_mode
))
2662 if (mknod (dst_name
, src_mode
& ~omitted_permissions
, src_sb
.st_rdev
)
2665 error (0, errno
, _("cannot create special file %s"),
2666 quoteaf (dst_name
));
2670 else if (S_ISLNK (src_mode
))
2672 char *src_link_val
= areadlink_with_size (src_name
, src_sb
.st_size
);
2673 dest_is_symlink
= true;
2674 if (src_link_val
== NULL
)
2676 error (0, errno
, _("cannot read symbolic link %s"),
2677 quoteaf (src_name
));
2681 int symlink_r
= force_symlinkat (src_link_val
, AT_FDCWD
, dst_name
,
2682 x
->unlink_dest_after_failed_open
);
2683 int symlink_err
= symlink_r
< 0 ? errno
: 0;
2684 if (symlink_err
&& x
->update
&& !new_dst
&& S_ISLNK (dst_sb
.st_mode
)
2685 && dst_sb
.st_size
== strlen (src_link_val
))
2687 /* See if the destination is already the desired symlink.
2688 FIXME: This behavior isn't documented, and seems wrong
2689 in some cases, e.g., if the destination symlink has the
2690 wrong ownership, permissions, or timestamps. */
2691 char *dest_link_val
=
2692 areadlink_with_size (dst_name
, dst_sb
.st_size
);
2695 if (STREQ (dest_link_val
, src_link_val
))
2697 free (dest_link_val
);
2700 free (src_link_val
);
2703 error (0, symlink_err
, _("cannot create symbolic link %s"),
2704 quoteaf (dst_name
));
2708 if (x
->preserve_security_context
)
2709 restore_default_fscreatecon_or_die ();
2711 if (x
->preserve_ownership
)
2713 /* Preserve the owner and group of the just-'copied'
2714 symbolic link, if possible. */
2716 && lchown (dst_name
, src_sb
.st_uid
, src_sb
.st_gid
) != 0
2717 && ! chown_failure_ok (x
))
2719 error (0, errno
, _("failed to preserve ownership for %s"),
2721 if (x
->require_preserve
)
2726 /* Can't preserve ownership of symlinks.
2727 FIXME: maybe give a warning or even error for symlinks
2728 in directories with the sticky bit set -- there, not
2729 preserving owner/group is a potential security problem. */
2735 error (0, 0, _("%s has unknown file type"), quoteaf (src_name
));
2739 /* With -Z or --preserve=context, set the context for existing files.
2740 Note this is done already for copy_reg() for reasons described therein. */
2741 if (!new_dst
&& !x
->copy_as_regular
&& !S_ISDIR (src_mode
)
2742 && (x
->set_security_context
|| x
->preserve_security_context
))
2744 if (! set_file_security_ctx (dst_name
, x
->preserve_security_context
,
2747 if (x
->require_preserve_context
)
2752 if (command_line_arg
&& x
->dest_info
)
2754 /* Now that the destination file is very likely to exist,
2755 add its info to the set. */
2757 if (lstat (dst_name
, &sb
) == 0)
2758 record_file (x
->dest_info
, dst_name
, &sb
);
2761 /* If we've just created a hard-link due to cp's --link option,
2763 if (x
->hard_link
&& ! S_ISDIR (src_mode
)
2764 && !(! CAN_HARDLINK_SYMLINKS
&& S_ISLNK (src_mode
)
2765 && x
->dereference
== DEREF_NEVER
))
2768 if (copied_as_regular
)
2771 /* POSIX says that 'cp -p' must restore the following:
2773 - setuid, setgid bits
2775 If it fails to restore any of those, we may give a warning but
2776 the destination must not be removed.
2777 FIXME: implement the above. */
2779 /* Adjust the times (and if possible, ownership) for the copy.
2780 chown turns off set[ug]id bits for non-root,
2781 so do the chmod last. */
2783 if (x
->preserve_timestamps
)
2785 struct timespec timespec
[2];
2786 timespec
[0] = get_stat_atime (&src_sb
);
2787 timespec
[1] = get_stat_mtime (&src_sb
);
2789 if ((dest_is_symlink
2790 ? utimens_symlink (dst_name
, timespec
)
2791 : utimens (dst_name
, timespec
))
2794 error (0, errno
, _("preserving times for %s"), quoteaf (dst_name
));
2795 if (x
->require_preserve
)
2800 /* Avoid calling chown if we know it's not necessary. */
2801 if (!dest_is_symlink
&& x
->preserve_ownership
2802 && (new_dst
|| !SAME_OWNER_AND_GROUP (src_sb
, dst_sb
)))
2804 switch (set_owner (x
, dst_name
, -1, &src_sb
, new_dst
, &dst_sb
))
2810 src_mode
&= ~ (S_ISUID
| S_ISGID
| S_ISVTX
);
2815 /* Set xattrs after ownership as changing owners will clear capabilities. */
2816 if (x
->preserve_xattr
&& ! copy_attr (src_name
, -1, dst_name
, -1, x
)
2817 && x
->require_preserve_xattr
)
2820 /* The operations beyond this point may dereference a symlink. */
2821 if (dest_is_symlink
)
2824 set_author (dst_name
, -1, &src_sb
);
2826 if (x
->preserve_mode
|| x
->move_mode
)
2828 if (copy_acl (src_name
, -1, dst_name
, -1, src_mode
) != 0
2829 && x
->require_preserve
)
2832 else if (x
->set_mode
)
2834 if (set_acl (dst_name
, -1, x
->mode
) != 0)
2837 else if (x
->explicit_no_preserve_mode
)
2839 if (set_acl (dst_name
, -1, 0777 & ~cached_umask ()) != 0)
2844 if (omitted_permissions
)
2846 omitted_permissions
&= ~ cached_umask ();
2848 if (omitted_permissions
&& !restore_dst_mode
)
2850 /* Permissions were deliberately omitted when the file
2851 was created due to security concerns. See whether
2852 they need to be re-added now. It'd be faster to omit
2853 the lstat, but deducing the current destination mode
2854 is tricky in the presence of implementation-defined
2855 rules for special mode bits. */
2856 if (new_dst
&& lstat (dst_name
, &dst_sb
) != 0)
2858 error (0, errno
, _("cannot stat %s"), quoteaf (dst_name
));
2861 dst_mode
= dst_sb
.st_mode
;
2862 if (omitted_permissions
& ~dst_mode
)
2863 restore_dst_mode
= true;
2867 if (restore_dst_mode
)
2869 if (lchmod (dst_name
, dst_mode
| omitted_permissions
) != 0)
2871 error (0, errno
, _("preserving permissions for %s"),
2872 quoteaf (dst_name
));
2873 if (x
->require_preserve
)
2883 if (x
->preserve_security_context
)
2884 restore_default_fscreatecon_or_die ();
2886 /* We have failed to create the destination file.
2887 If we've just added a dev/ino entry via the remember_copied
2888 call above (i.e., unless we've just failed to create a hard link),
2889 remove the entry associating the source dev/ino with the
2890 destination file name, so we don't try to 'preserve' a link
2891 to a file we didn't create. */
2892 if (earlier_file
== NULL
)
2893 forget_created (src_sb
.st_ino
, src_sb
.st_dev
);
2897 if (rename (dst_backup
, dst_name
) != 0)
2898 error (0, errno
, _("cannot un-backup %s"), quoteaf (dst_name
));
2902 printf (_("%s -> %s (unbackup)\n"),
2903 quoteaf_n (0, dst_backup
), quoteaf_n (1, dst_name
));
2909 static bool _GL_ATTRIBUTE_PURE
2910 valid_options (const struct cp_options
*co
)
2912 assert (co
!= NULL
);
2913 assert (VALID_BACKUP_TYPE (co
->backup_type
));
2914 assert (VALID_SPARSE_MODE (co
->sparse_mode
));
2915 assert (VALID_REFLINK_MODE (co
->reflink_mode
));
2916 assert (!(co
->hard_link
&& co
->symbolic_link
));
2918 (co
->reflink_mode
== REFLINK_ALWAYS
2919 && co
->sparse_mode
!= SPARSE_AUTO
));
2923 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
2924 any type. NONEXISTENT_DST should be true if the file DST_NAME
2925 is known not to exist (e.g., because its parent directory was just
2926 created); NONEXISTENT_DST should be false if DST_NAME might already
2927 exist. OPTIONS is ... FIXME-describe
2928 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
2929 same as) DST_NAME; otherwise, set clear it.
2930 Return true if successful. */
2933 copy (char const *src_name
, char const *dst_name
,
2934 bool nonexistent_dst
, const struct cp_options
*options
,
2935 bool *copy_into_self
, bool *rename_succeeded
)
2937 assert (valid_options (options
));
2939 /* Record the file names: they're used in case of error, when copying
2940 a directory into itself. I don't like to make these tools do *any*
2941 extra work in the common case when that work is solely to handle
2942 exceptional cases, but in this case, I don't see a way to derive the
2943 top level source and destination directory names where they're used.
2944 An alternative is to use COPY_INTO_SELF and print the diagnostic
2945 from every caller -- but I don't want to do that. */
2946 top_level_src_name
= src_name
;
2947 top_level_dst_name
= dst_name
;
2949 bool first_dir_created_per_command_line_arg
= false;
2950 return copy_internal (src_name
, dst_name
, nonexistent_dst
, NULL
, NULL
,
2952 &first_dir_created_per_command_line_arg
,
2953 copy_into_self
, rename_succeeded
);
2956 /* Set *X to the default options for a value of type struct cp_options. */
2959 cp_options_default (struct cp_options
*x
)
2961 memset (x
, 0, sizeof *x
);
2962 #ifdef PRIV_FILE_CHOWN
2964 priv_set_t
*pset
= priv_allocset ();
2967 if (getppriv (PRIV_EFFECTIVE
, pset
) == 0)
2969 x
->chown_privileges
= priv_ismember (pset
, PRIV_FILE_CHOWN
);
2970 x
->owner_privileges
= priv_ismember (pset
, PRIV_FILE_OWNER
);
2972 priv_freeset (pset
);
2975 x
->chown_privileges
= x
->owner_privileges
= (geteuid () == ROOT_UID
);
2979 /* Return true if it's OK for chown to fail, where errno is
2980 the error number that chown failed with and X is the copying
2984 chown_failure_ok (struct cp_options
const *x
)
2986 /* If non-root uses -p, it's ok if we can't preserve ownership.
2987 But root probably wants to know, e.g. if NFS disallows it,
2988 or if the target system doesn't support file ownership. */
2990 return ((errno
== EPERM
|| errno
== EINVAL
) && !x
->chown_privileges
);
2993 /* Similarly, return true if it's OK for chmod and similar operations
2994 to fail, where errno is the error number that chmod failed with and
2995 X is the copying option set. */
2998 owner_failure_ok (struct cp_options
const *x
)
3000 return ((errno
== EPERM
|| errno
== EINVAL
) && !x
->owner_privileges
);
3003 /* Return the user's umask, caching the result.
3005 FIXME: If the destination's parent directory has has a default ACL,
3006 some operating systems (e.g., GNU/Linux's "POSIX" ACLs) use that
3007 ACL's mask rather than the process umask. Currently, the callers
3008 of cached_umask incorrectly assume that this situation cannot occur. */
3012 static mode_t mask
= (mode_t
) -1;
3013 if (mask
== (mode_t
) -1)