1 /* copy.c -- core functions for copying files and directories
2 Copyright (C) 1989-2016 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/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 "full-write.h"
51 #include "hash-triple.h"
52 #include "ignore-value.h"
53 #include "ioblksize.h"
58 #include "stat-size.h"
59 #include "stat-time.h"
62 #include "write-any-file.h"
63 #include "areadlink.h"
68 # include <attr/error_context.h>
69 # include <attr/libattr.h>
74 #if HAVE_LINUX_FALLOC_H
75 # include <linux/falloc.h>
78 #ifdef HAVE_LINUX_FS_H
79 # include <linux/fs.h>
82 #if !defined FICLONE && defined __linux__
83 # define FICLONE _IOW (0x94, 9, int)
87 # define HAVE_FCHOWN false
88 # define fchown(fd, uid, gid) (-1)
92 # define HAVE_LCHOWN false
93 # define lchown(name, uid, gid) chown (name, uid, gid)
98 rpl_mkfifo (char const *file
, mode_t mode
)
103 # define mkfifo rpl_mkfifo
110 #define SAME_OWNER(A, B) ((A).st_uid == (B).st_uid)
111 #define SAME_GROUP(A, B) ((A).st_gid == (B).st_gid)
112 #define SAME_OWNER_AND_GROUP(A, B) (SAME_OWNER (A, B) && SAME_GROUP (A, B))
114 /* LINK_FOLLOWS_SYMLINKS is tri-state; if it is -1, we don't know
115 how link() behaves, so assume we can't hardlink symlinks in that case. */
116 #if (defined HAVE_LINKAT && ! LINKAT_SYMLINK_NOTSUP) || ! LINK_FOLLOWS_SYMLINKS
117 # define CAN_HARDLINK_SYMLINKS 1
119 # define CAN_HARDLINK_SYMLINKS 0
124 struct dir_list
*parent
;
129 /* Initial size of the cp.dest_info hash table. */
130 #define DEST_INFO_INITIAL_CAPACITY 61
132 static bool copy_internal (char const *src_name
, char const *dst_name
,
133 bool new_dst
, struct stat
const *parent
,
134 struct dir_list
*ancestors
,
135 const struct cp_options
*x
,
136 bool command_line_arg
,
137 bool *first_dir_created_per_command_line_arg
,
138 bool *copy_into_self
,
139 bool *rename_succeeded
);
140 static bool owner_failure_ok (struct cp_options
const *x
);
142 /* Pointers to the file names: they're used in the diagnostic that is issued
143 when we detect the user is trying to copy a directory into itself. */
144 static char const *top_level_src_name
;
145 static char const *top_level_dst_name
;
147 /* Set the timestamp of symlink, FILE, to TIMESPEC.
148 If this system lacks support for that, simply return 0. */
150 utimens_symlink (char const *file
, struct timespec
const *timespec
)
152 int err
= lutimens (file
, timespec
);
153 /* When configuring on a system with new headers and libraries, and
154 running on one with a kernel that is old enough to lack the syscall,
155 utimensat fails with ENOSYS. Ignore that. */
156 if (err
&& errno
== ENOSYS
)
161 /* Attempt to punch a hole to avoid any permanent
162 speculative preallocation on file systems such as XFS.
163 Return values as per fallocate(2) except ENOSYS etc. are ignored. */
166 punch_hole (int fd
, off_t offset
, off_t length
)
170 # if defined FALLOC_FL_PUNCH_HOLE && defined FALLOC_FL_KEEP_SIZE
171 ret
= fallocate (fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
173 if (ret
< 0 && (is_ENOTSUP (errno
) || errno
== ENOSYS
))
180 /* Create a hole at the end of a file,
181 avoiding preallocation if requested. */
184 create_hole (int fd
, char const *name
, bool punch_holes
, off_t size
)
186 off_t file_end
= lseek (fd
, size
, SEEK_CUR
);
190 error (0, errno
, _("cannot lseek %s"), quoteaf (name
));
194 /* Some file systems (like XFS) preallocate when write extending a file.
195 I.e., a previous write() may have preallocated extra space
196 that the seek above will not discard. A subsequent write() could
197 then make this allocation permanent. */
198 if (punch_holes
&& punch_hole (fd
, file_end
- size
, size
) < 0)
200 error (0, errno
, _("error deallocating %s"), quoteaf (name
));
208 /* Copy the regular file open on SRC_FD/SRC_NAME to DST_FD/DST_NAME,
209 honoring the MAKE_HOLES setting and using the BUF_SIZE-byte buffer
210 BUF for temporary storage. Copy no more than MAX_N_READ bytes.
211 Return true upon successful completion;
212 print a diagnostic and return false upon error.
213 Note that for best results, BUF should be "well"-aligned.
214 BUF must have sizeof(uintptr_t)-1 bytes of additional space
215 beyond BUF[BUF_SIZE-1].
216 Set *LAST_WRITE_MADE_HOLE to true if the final operation on
217 DEST_FD introduced a hole. Set *TOTAL_N_READ to the number of
220 sparse_copy (int src_fd
, int dest_fd
, char *buf
, size_t buf_size
,
221 size_t hole_size
, bool punch_holes
,
222 char const *src_name
, char const *dst_name
,
223 uintmax_t max_n_read
, off_t
*total_n_read
,
224 bool *last_write_made_hole
)
226 *last_write_made_hole
= false;
228 bool make_hole
= false;
233 ssize_t n_read
= read (src_fd
, buf
, MIN (max_n_read
, buf_size
));
238 error (0, errno
, _("error reading %s"), quoteaf (src_name
));
243 max_n_read
-= n_read
;
244 *total_n_read
+= n_read
;
246 /* Loop over the input buffer in chunks of hole_size. */
247 size_t csize
= hole_size
? hole_size
: buf_size
;
253 bool prev_hole
= make_hole
;
254 csize
= MIN (csize
, n_read
);
256 if (hole_size
&& csize
)
257 make_hole
= is_nul (cbuf
, csize
);
259 bool transition
= (make_hole
!= prev_hole
) && psize
;
260 bool last_chunk
= (n_read
== csize
&& ! make_hole
) || ! csize
;
262 if (transition
|| last_chunk
)
269 if (full_write (dest_fd
, pbuf
, psize
) != psize
)
271 error (0, errno
, _("error writing %s"),
278 if (! create_hole (dest_fd
, dst_name
, punch_holes
, psize
))
288 n_read
= 0; /* Finished processing buffer. */
291 csize
= 0; /* Loop again to deal with last chunk. */
293 psize
= 0; /* Reset for next read loop. */
296 else /* Coalesce writes/seeks. */
298 if (psize
<= OFF_T_MAX
- csize
)
302 error (0, 0, _("overflow reading %s"), quoteaf (src_name
));
311 *last_write_made_hole
= make_hole
;
313 /* It's tempting to break early here upon a short read from
314 a regular file. That would save the final read syscall
315 for each file. Unfortunately that doesn't work for
316 certain files in /proc or /sys with linux kernels. */
319 /* Ensure a trailing hole is created, so that subsequent
320 calls of sparse_copy() start at the correct offset. */
321 if (make_hole
&& ! create_hole (dest_fd
, dst_name
, punch_holes
, psize
))
327 /* Perform the O(1) btrfs clone operation, if possible.
328 Upon success, return 0. Otherwise, return -1 and set errno. */
330 clone_file (int dest_fd
, int src_fd
)
333 return ioctl (dest_fd
, FICLONE
, src_fd
);
342 /* Write N_BYTES zero bytes to file descriptor FD. Return true if successful.
343 Upon write failure, set errno and return false. */
345 write_zeros (int fd
, off_t n_bytes
)
348 static size_t nz
= IO_BUFSIZE
;
350 /* Attempt to use a relatively large calloc'd source buffer for
351 efficiency, but if that allocation fails, resort to a smaller
352 statically allocated one. */
355 static char fallback
[1024];
356 zeros
= calloc (nz
, 1);
360 nz
= sizeof fallback
;
366 size_t n
= MIN (nz
, n_bytes
);
367 if ((full_write (fd
, zeros
, n
)) != n
)
375 /* Perform an efficient extent copy, if possible. This avoids
376 the overhead of detecting holes in hole-introducing/preserving
377 copy, and thus makes copying sparse files much more efficient.
378 Upon a successful copy, return true. If the initial extent scan
379 fails, set *NORMAL_COPY_REQUIRED to true and return false.
380 Upon any other failure, set *NORMAL_COPY_REQUIRED to false and
383 extent_copy (int src_fd
, int dest_fd
, char *buf
, size_t buf_size
,
384 size_t hole_size
, off_t src_total_size
,
385 enum Sparse_type sparse_mode
,
386 char const *src_name
, char const *dst_name
,
387 bool *require_normal_copy
)
389 struct extent_scan scan
;
390 off_t last_ext_start
= 0;
391 off_t last_ext_len
= 0;
393 /* Keep track of the output position.
394 We may need this at the end, for a final ftruncate. */
397 extent_scan_init (src_fd
, &scan
);
399 *require_normal_copy
= false;
400 bool wrote_hole_at_eof
= true;
403 bool ok
= extent_scan_read (&scan
);
406 if (scan
.hit_final_extent
)
409 if (scan
.initial_scan_failed
)
411 *require_normal_copy
= true;
415 error (0, errno
, _("%s: failed to get extents info"),
421 bool empty_extent
= false;
422 for (i
= 0; i
< scan
.ei_count
|| empty_extent
; i
++)
428 if (i
< scan
.ei_count
)
430 ext_start
= scan
.ext_info
[i
].ext_logical
;
431 ext_len
= scan
.ext_info
[i
].ext_length
;
433 else /* empty extent at EOF. */
436 ext_start
= last_ext_start
+ scan
.ext_info
[i
].ext_length
;
440 /* Truncate extent to EOF. Extents starting after EOF are
441 treated as zero length extents starting right after EOF.
442 Generally this will trigger with an extent starting after
443 src_total_size, and result in creating a hole or zeros until EOF.
444 Though in a file in which extents have changed since src_total_size
445 was determined, we might have an extent spanning that size,
446 in which case we'll only copy data up to that size. */
447 if (src_total_size
< ext_start
+ ext_len
)
449 if (src_total_size
< ext_start
)
450 ext_start
= src_total_size
;
451 ext_len
= src_total_size
- ext_start
;
454 ext_hole_size
= ext_start
- last_ext_start
- last_ext_len
;
456 wrote_hole_at_eof
= false;
460 if (lseek (src_fd
, ext_start
, SEEK_SET
) < 0)
462 error (0, errno
, _("cannot lseek %s"), quoteaf (src_name
));
464 extent_scan_free (&scan
);
468 if ((empty_extent
&& sparse_mode
== SPARSE_ALWAYS
)
469 || (!empty_extent
&& sparse_mode
!= SPARSE_NEVER
))
471 if (! create_hole (dest_fd
, dst_name
,
472 sparse_mode
== SPARSE_ALWAYS
,
475 wrote_hole_at_eof
= true;
479 /* When not inducing holes and when there is a hole between
480 the end of the previous extent and the beginning of the
481 current one, write zeros to the destination file. */
482 off_t nzeros
= ext_hole_size
;
484 nzeros
= MIN (src_total_size
- dest_pos
, ext_hole_size
);
486 if (! write_zeros (dest_fd
, nzeros
))
488 error (0, errno
, _("%s: write failed"),
493 dest_pos
= MIN (src_total_size
, ext_start
);
497 last_ext_start
= ext_start
;
499 /* Treat an unwritten but allocated extent much like a hole.
500 I.e., don't read, but don't convert to a hole in the destination,
501 unless SPARSE_ALWAYS. */
502 /* For now, do not treat FIEMAP_EXTENT_UNWRITTEN specially,
503 because that (in combination with no sync) would lead to data
504 loss at least on XFS and ext4 when using 2.6.39-rc3 kernels. */
505 if (0 && (scan
.ext_info
[i
].ext_flags
& FIEMAP_EXTENT_UNWRITTEN
))
509 if (ext_len
== 0) /* The last extent is empty and processed. */
510 empty_extent
= false;
515 empty_extent
= false;
516 last_ext_len
= ext_len
;
519 if ( ! sparse_copy (src_fd
, dest_fd
, buf
, buf_size
,
520 sparse_mode
== SPARSE_ALWAYS
? hole_size
: 0,
521 true, src_name
, dst_name
, ext_len
, &n_read
,
525 dest_pos
= ext_start
+ n_read
;
527 wrote_hole_at_eof
= read_hole
;
530 /* If the file ends with unwritten extents not accounted for in the
531 size, then skip processing them, and the associated redundant
532 read() calls which will always return 0. We will need to
533 remove this when we add fallocate() so that we can maintain
534 extents beyond the apparent size. */
535 if (dest_pos
== src_total_size
)
537 scan
.hit_final_extent
= true;
542 /* Release the space allocated to scan->ext_info. */
543 extent_scan_free (&scan
);
546 while (! scan
.hit_final_extent
);
548 /* When the source file ends with a hole, we have to do a little more work,
549 since the above copied only up to and including the final extent.
550 In order to complete the copy, we may have to insert a hole or write
551 zeros in the destination corresponding to the source file's hole-at-EOF.
553 In addition, if the final extent was a block of zeros at EOF and we've
554 just converted them to a hole in the destination, we must call ftruncate
555 here in order to record the proper length in the destination. */
556 if ((dest_pos
< src_total_size
|| wrote_hole_at_eof
)
557 && (sparse_mode
!= SPARSE_NEVER
558 ? ftruncate (dest_fd
, src_total_size
)
559 : ! write_zeros (dest_fd
, src_total_size
- dest_pos
)))
561 error (0, errno
, _("failed to extend %s"), quoteaf (dst_name
));
565 if (sparse_mode
== SPARSE_ALWAYS
&& dest_pos
< src_total_size
566 && punch_hole (dest_fd
, dest_pos
, src_total_size
- dest_pos
) < 0)
568 error (0, errno
, _("error deallocating %s"), quoteaf (dst_name
));
575 /* FIXME: describe */
576 /* FIXME: rewrite this to use a hash table so we avoid the quadratic
577 performance hit that's probably noticeable only on trees deeper
578 than a few hundred levels. See use of active_dir_map in remove.c */
580 static bool _GL_ATTRIBUTE_PURE
581 is_ancestor (const struct stat
*sb
, const struct dir_list
*ancestors
)
583 while (ancestors
!= 0)
585 if (ancestors
->ino
== sb
->st_ino
&& ancestors
->dev
== sb
->st_dev
)
587 ancestors
= ancestors
->parent
;
593 errno_unsupported (int err
)
595 return err
== ENOTSUP
|| err
== ENODATA
;
600 copy_attr_error (struct error_context
*ctx _GL_UNUSED
,
601 char const *fmt
, ...)
603 if (!errno_unsupported (errno
))
608 /* use verror module to print error message */
610 verror (0, err
, fmt
, ap
);
616 copy_attr_allerror (struct error_context
*ctx _GL_UNUSED
,
617 char const *fmt
, ...)
622 /* use verror module to print error message */
624 verror (0, err
, fmt
, ap
);
629 copy_attr_quote (struct error_context
*ctx _GL_UNUSED
, char const *str
)
631 return quoteaf (str
);
635 copy_attr_free (struct error_context
*ctx _GL_UNUSED
,
636 char const *str _GL_UNUSED
)
640 /* Exclude SELinux extended attributes that are otherwise handled,
641 and are problematic to copy again. Also honor attributes
642 configured for exclusion in /etc/xattr.conf.
643 FIXME: Should we handle POSIX ACLs similarly?
644 Return zero to skip. */
646 check_selinux_attr (const char *name
, struct error_context
*ctx
)
648 return STRNCMP_LIT (name
, "security.selinux")
649 && attr_copy_check_permissions (name
, ctx
);
652 /* If positive SRC_FD and DST_FD descriptors are passed,
653 then copy by fd, otherwise copy by name. */
656 copy_attr (char const *src_path
, int src_fd
,
657 char const *dst_path
, int dst_fd
, struct cp_options
const *x
)
660 bool all_errors
= (!x
->data_copy_required
|| x
->require_preserve_xattr
);
661 bool some_errors
= (!all_errors
&& !x
->reduce_diagnostics
);
662 bool selinux_done
= (x
->preserve_security_context
|| x
->set_security_context
);
663 struct error_context ctx
=
665 .error
= all_errors
? copy_attr_allerror
: copy_attr_error
,
666 .quote
= copy_attr_quote
,
667 .quote_free
= copy_attr_free
669 if (0 <= src_fd
&& 0 <= dst_fd
)
670 ret
= attr_copy_fd (src_path
, src_fd
, dst_path
, dst_fd
,
671 selinux_done
? check_selinux_attr
: NULL
,
672 (all_errors
|| some_errors
? &ctx
: NULL
));
674 ret
= attr_copy_file (src_path
, dst_path
,
675 selinux_done
? check_selinux_attr
: NULL
,
676 (all_errors
|| some_errors
? &ctx
: NULL
));
680 #else /* USE_XATTR */
683 copy_attr (char const *src_path _GL_UNUSED
,
684 int src_fd _GL_UNUSED
,
685 char const *dst_path _GL_UNUSED
,
686 int dst_fd _GL_UNUSED
,
687 struct cp_options
const *x _GL_UNUSED
)
691 #endif /* USE_XATTR */
693 /* Read the contents of the directory SRC_NAME_IN, and recursively
694 copy the contents to DST_NAME_IN. NEW_DST is true if
695 DST_NAME_IN is a directory that was created previously in the
696 recursion. SRC_SB and ANCESTORS describe SRC_NAME_IN.
697 Set *COPY_INTO_SELF if SRC_NAME_IN is a parent of
698 (or the same as) DST_NAME_IN; otherwise, clear it.
699 Propagate *FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG from
700 caller to each invocation of copy_internal. Be careful to
701 pass the address of a temporary, and to update
702 *FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG only upon completion.
703 Return true if successful. */
706 copy_dir (char const *src_name_in
, char const *dst_name_in
, bool new_dst
,
707 const struct stat
*src_sb
, struct dir_list
*ancestors
,
708 const struct cp_options
*x
,
709 bool *first_dir_created_per_command_line_arg
,
710 bool *copy_into_self
)
714 struct cp_options non_command_line_options
= *x
;
717 name_space
= savedir (src_name_in
, SAVEDIR_SORT_FASTREAD
);
718 if (name_space
== NULL
)
720 /* This diagnostic is a bit vague because savedir can fail in
721 several different ways. */
722 error (0, errno
, _("cannot access %s"), quoteaf (src_name_in
));
726 /* For cp's -H option, dereference command line arguments, but do not
727 dereference symlinks that are found via recursive traversal. */
728 if (x
->dereference
== DEREF_COMMAND_LINE_ARGUMENTS
)
729 non_command_line_options
.dereference
= DEREF_NEVER
;
731 bool new_first_dir_created
= false;
733 while (*namep
!= '\0')
735 bool local_copy_into_self
;
736 char *src_name
= file_name_concat (src_name_in
, namep
, NULL
);
737 char *dst_name
= file_name_concat (dst_name_in
, namep
, NULL
);
738 bool first_dir_created
= *first_dir_created_per_command_line_arg
;
740 ok
&= copy_internal (src_name
, dst_name
, new_dst
, src_sb
,
741 ancestors
, &non_command_line_options
, false,
743 &local_copy_into_self
, NULL
);
744 *copy_into_self
|= local_copy_into_self
;
749 /* If we're copying into self, there's no point in continuing,
750 and in fact, that would even infloop, now that we record only
751 the first created directory per command line argument. */
752 if (local_copy_into_self
)
755 new_first_dir_created
|= first_dir_created
;
756 namep
+= strlen (namep
) + 1;
759 *first_dir_created_per_command_line_arg
= new_first_dir_created
;
764 /* Set the owner and owning group of DEST_DESC to the st_uid and
765 st_gid fields of SRC_SB. If DEST_DESC is undefined (-1), set
766 the owner and owning group of DST_NAME instead; for
767 safety prefer lchown if the system supports it since no
768 symbolic links should be involved. DEST_DESC must
769 refer to the same file as DEST_NAME if defined.
770 Upon failure to set both UID and GID, try to set only the GID.
771 NEW_DST is true if the file was newly created; otherwise,
772 DST_SB is the status of the destination.
773 Return 1 if the initial syscall succeeds, 0 if it fails but it's OK
774 not to preserve ownership, -1 otherwise. */
777 set_owner (const struct cp_options
*x
, char const *dst_name
, int dest_desc
,
778 struct stat
const *src_sb
, bool new_dst
,
779 struct stat
const *dst_sb
)
781 uid_t uid
= src_sb
->st_uid
;
782 gid_t gid
= src_sb
->st_gid
;
784 /* Naively changing the ownership of an already-existing file before
785 changing its permissions would create a window of vulnerability if
786 the file's old permissions are too generous for the new owner and
787 group. Avoid the window by first changing to a restrictive
788 temporary mode if necessary. */
790 if (!new_dst
&& (x
->preserve_mode
|| x
->move_mode
|| x
->set_mode
))
792 mode_t old_mode
= dst_sb
->st_mode
;
794 (x
->preserve_mode
|| x
->move_mode
? src_sb
->st_mode
: x
->mode
);
795 mode_t restrictive_temp_mode
= old_mode
& new_mode
& S_IRWXU
;
798 || (old_mode
& CHMOD_MODE_BITS
799 & (~new_mode
| S_ISUID
| S_ISGID
| S_ISVTX
)))
800 && qset_acl (dst_name
, dest_desc
, restrictive_temp_mode
) != 0)
802 if (! owner_failure_ok (x
))
803 error (0, errno
, _("clearing permissions for %s"),
805 return -x
->require_preserve
;
809 if (HAVE_FCHOWN
&& dest_desc
!= -1)
811 if (fchown (dest_desc
, uid
, gid
) == 0)
813 if (errno
== EPERM
|| errno
== EINVAL
)
815 /* We've failed to set *both*. Now, try to set just the group
816 ID, but ignore any failure here, and don't change errno. */
817 int saved_errno
= errno
;
818 ignore_value (fchown (dest_desc
, -1, gid
));
824 if (lchown (dst_name
, uid
, gid
) == 0)
826 if (errno
== EPERM
|| errno
== EINVAL
)
828 /* We've failed to set *both*. Now, try to set just the group
829 ID, but ignore any failure here, and don't change errno. */
830 int saved_errno
= errno
;
831 ignore_value (lchown (dst_name
, -1, gid
));
836 if (! chown_failure_ok (x
))
838 error (0, errno
, _("failed to preserve ownership for %s"),
840 if (x
->require_preserve
)
847 /* Set the st_author field of DEST_DESC to the st_author field of
848 SRC_SB. If DEST_DESC is undefined (-1), set the st_author field
849 of DST_NAME instead. DEST_DESC must refer to the same file as
850 DEST_NAME if defined. */
853 set_author (const char *dst_name
, int dest_desc
, const struct stat
*src_sb
)
855 #if HAVE_STRUCT_STAT_ST_AUTHOR
856 /* FIXME: Modify the following code so that it does not
857 follow symbolic links. */
859 /* Preserve the st_author field. */
860 file_t file
= (dest_desc
< 0
861 ? file_name_lookup (dst_name
, 0, 0)
862 : getdport (dest_desc
));
863 if (file
== MACH_PORT_NULL
)
864 error (0, errno
, _("failed to lookup file %s"), quoteaf (dst_name
));
867 error_t err
= file_chauthor (file
, src_sb
->st_author
);
869 error (0, err
, _("failed to preserve authorship for %s"),
871 mach_port_deallocate (mach_task_self (), file
);
880 /* Set the default security context for the process. New files will
881 have this security context set. Also existing files can have their
882 context adjusted based on this process context, by
883 set_file_security_ctx() called with PROCESS_LOCAL=true.
884 This should be called before files are created so there is no race
885 where a file may be present without an appropriate security context.
886 Based on CP_OPTIONS, diagnose warnings and fail when appropriate.
887 Return FALSE on failure, TRUE on success. */
890 set_process_security_ctx (char const *src_name
, char const *dst_name
,
891 mode_t mode
, bool new_dst
, const struct cp_options
*x
)
893 if (x
->preserve_security_context
)
895 /* Set the default context for the process to match the source. */
896 bool all_errors
= !x
->data_copy_required
|| x
->require_preserve_context
;
897 bool some_errors
= !all_errors
&& !x
->reduce_diagnostics
;
900 if (0 <= lgetfilecon (src_name
, &con
))
902 if (setfscreatecon (con
) < 0)
904 if (all_errors
|| (some_errors
&& !errno_unsupported (errno
)))
906 _("failed to set default file creation context to %s"),
908 if (x
->require_preserve_context
)
918 if (all_errors
|| (some_errors
&& !errno_unsupported (errno
)))
921 _("failed to get security context of %s"),
924 if (x
->require_preserve_context
)
928 else if (x
->set_security_context
)
930 /* With -Z, adjust the default context for the process
931 to have the type component adjusted as per the destination path. */
932 if (new_dst
&& defaultcon (dst_name
, mode
) < 0
933 && ! ignorable_ctx_err (errno
))
936 _("failed to set default file creation context for %s"),
944 /* Reset the security context of DST_NAME, to that already set
945 as the process default if PROCESS_LOCAL is true. Otherwise
946 adjust the type component of DST_NAME's security context as
947 per the system default for that path. Issue warnings upon
948 failure, when allowed by various settings in CP_OPTIONS.
949 Return FALSE on failure, TRUE on success. */
952 set_file_security_ctx (char const *dst_name
, bool process_local
,
953 bool recurse
, const struct cp_options
*x
)
955 bool all_errors
= (!x
->data_copy_required
956 || x
->require_preserve_context
);
957 bool some_errors
= !all_errors
&& !x
->reduce_diagnostics
;
959 if (! restorecon (dst_name
, recurse
, process_local
))
961 if (all_errors
|| (some_errors
&& !errno_unsupported (errno
)))
962 error (0, errno
, _("failed to set the security context of %s"),
963 quoteaf_n (0, dst_name
));
970 /* Change the file mode bits of the file identified by DESC or NAME to MODE.
971 Use DESC if DESC is valid and fchmod is available, NAME otherwise. */
974 fchmod_or_lchmod (int desc
, char const *name
, mode_t mode
)
978 return fchmod (desc
, mode
);
980 return lchmod (name
, mode
);
983 #ifndef HAVE_STRUCT_STAT_ST_BLOCKS
984 # define HAVE_STRUCT_STAT_ST_BLOCKS 0
987 /* Use a heuristic to determine whether stat buffer SB comes from a file
988 with sparse blocks. If the file has fewer blocks than would normally
989 be needed for a file of its size, then at least one of the blocks in
990 the file is a hole. In that case, return true. */
992 is_probably_sparse (struct stat
const *sb
)
994 return (HAVE_STRUCT_STAT_ST_BLOCKS
995 && S_ISREG (sb
->st_mode
)
996 && ST_NBLOCKS (*sb
) < sb
->st_size
/ ST_NBLOCKSIZE
);
1000 /* Copy a regular file from SRC_NAME to DST_NAME.
1001 If the source file contains holes, copies holes and blocks of zeros
1002 in the source file as holes in the destination file.
1003 (Holes are read as zeroes by the 'read' system call.)
1004 When creating the destination, use DST_MODE & ~OMITTED_PERMISSIONS
1005 as the third argument in the call to open, adding
1006 OMITTED_PERMISSIONS after copying as needed.
1007 X provides many option settings.
1008 Return true if successful.
1009 *NEW_DST is as in copy_internal.
1010 SRC_SB is the result of calling XSTAT (aka stat) on SRC_NAME. */
1013 copy_reg (char const *src_name
, char const *dst_name
,
1014 const struct cp_options
*x
,
1015 mode_t dst_mode
, mode_t omitted_permissions
, bool *new_dst
,
1016 struct stat
const *src_sb
)
1019 char *buf_alloc
= NULL
;
1020 char *name_alloc
= NULL
;
1024 mode_t src_mode
= src_sb
->st_mode
;
1026 struct stat src_open_sb
;
1027 bool return_val
= true;
1028 bool data_copy_required
= x
->data_copy_required
;
1030 source_desc
= open (src_name
,
1031 (O_RDONLY
| O_BINARY
1032 | (x
->dereference
== DEREF_NEVER
? O_NOFOLLOW
: 0)));
1033 if (source_desc
< 0)
1035 error (0, errno
, _("cannot open %s for reading"), quoteaf (src_name
));
1039 if (fstat (source_desc
, &src_open_sb
) != 0)
1041 error (0, errno
, _("cannot fstat %s"), quoteaf (src_name
));
1043 goto close_src_desc
;
1046 /* Compare the source dev/ino from the open file to the incoming,
1047 saved ones obtained via a previous call to stat. */
1048 if (! SAME_INODE (*src_sb
, src_open_sb
))
1051 _("skipping file %s, as it was replaced while being copied"),
1052 quoteaf (src_name
));
1054 goto close_src_desc
;
1057 /* The semantics of the following open calls are mandated
1058 by the specs for both cp and mv. */
1062 O_WRONLY
| O_BINARY
| (x
->data_copy_required
? O_TRUNC
: 0);
1063 dest_desc
= open (dst_name
, open_flags
);
1066 /* When using cp --preserve=context to copy to an existing destination,
1067 reset the context as per the default context, which has already been
1068 set according to the src.
1069 When using the mutually exclusive -Z option, then adjust the type of
1070 the existing context according to the system default for the dest.
1071 Note we set the context here, _after_ the file is opened, lest the
1072 new context disallow that. */
1073 if ((x
->set_security_context
|| x
->preserve_security_context
)
1076 if (! set_file_security_ctx (dst_name
, x
->preserve_security_context
,
1079 if (x
->require_preserve_context
)
1082 goto close_src_and_dst_desc
;
1087 if (dest_desc
< 0 && x
->unlink_dest_after_failed_open
)
1089 if (unlink (dst_name
) != 0)
1091 error (0, errno
, _("cannot remove %s"), quoteaf (dst_name
));
1093 goto close_src_desc
;
1096 printf (_("removed %s\n"), quoteaf (dst_name
));
1098 /* Tell caller that the destination file was unlinked. */
1101 /* Ensure there is no race where a file may be left without
1102 an appropriate security context. */
1103 if (x
->set_security_context
)
1105 if (! set_process_security_ctx (src_name
, dst_name
, dst_mode
,
1109 goto close_src_desc
;
1119 int open_flags
= O_WRONLY
| O_CREAT
| O_BINARY
;
1120 dest_desc
= open (dst_name
, open_flags
| O_EXCL
,
1121 dst_mode
& ~omitted_permissions
);
1124 /* When trying to copy through a dangling destination symlink,
1125 the above open fails with EEXIST. If that happens, and
1126 lstat'ing the DST_NAME shows that it is a symlink, then we
1127 have a problem: trying to resolve this dangling symlink to
1128 a directory/destination-entry pair is fundamentally racy,
1129 so punt. If x->open_dangling_dest_symlink is set (cp sets
1130 that when POSIXLY_CORRECT is set in the environment), simply
1131 call open again, but without O_EXCL (potentially dangerous).
1132 If not, fail with a diagnostic. These shenanigans are necessary
1133 only when copying, i.e., not in move_mode. */
1134 if (dest_desc
< 0 && dest_errno
== EEXIST
&& ! x
->move_mode
)
1136 struct stat dangling_link_sb
;
1137 if (lstat (dst_name
, &dangling_link_sb
) == 0
1138 && S_ISLNK (dangling_link_sb
.st_mode
))
1140 if (x
->open_dangling_dest_symlink
)
1142 dest_desc
= open (dst_name
, open_flags
,
1143 dst_mode
& ~omitted_permissions
);
1148 error (0, 0, _("not writing through dangling symlink %s"),
1149 quoteaf (dst_name
));
1151 goto close_src_desc
;
1156 /* Improve quality of diagnostic when a nonexistent dst_name
1157 ends in a slash and open fails with errno == EISDIR. */
1158 if (dest_desc
< 0 && dest_errno
== EISDIR
1159 && *dst_name
&& dst_name
[strlen (dst_name
) - 1] == '/')
1160 dest_errno
= ENOTDIR
;
1164 omitted_permissions
= 0;
1169 /* If we've just failed due to ENOENT for an ostensibly preexisting
1170 destination (*new_dst was 0), that's a bit of a contradiction/race:
1171 the prior stat/lstat said the file existed (*new_dst was 0), yet
1172 the subsequent open-existing-file failed with ENOENT. With NFS,
1173 the race window is wider still, since its meta-data caching tends
1174 to make the stat succeed for a just-removed remote file, while the
1175 more-definitive initial open call will fail with ENOENT. When this
1176 situation arises, we attempt to open again, but this time with
1177 O_CREAT. Do this only when not in move-mode, since when handling
1178 a cross-device move, we must never open an existing destination. */
1179 if (dest_errno
== ENOENT
&& ! *new_dst
&& ! x
->move_mode
)
1182 goto open_with_O_CREAT
;
1185 /* Otherwise, it's an error. */
1186 error (0, dest_errno
, _("cannot create regular file %s"),
1187 quoteaf (dst_name
));
1189 goto close_src_desc
;
1192 if (fstat (dest_desc
, &sb
) != 0)
1194 error (0, errno
, _("cannot fstat %s"), quoteaf (dst_name
));
1196 goto close_src_and_dst_desc
;
1199 /* --attributes-only overrides --reflink. */
1200 if (data_copy_required
&& x
->reflink_mode
)
1202 bool clone_ok
= clone_file (dest_desc
, source_desc
) == 0;
1203 if (clone_ok
|| x
->reflink_mode
== REFLINK_ALWAYS
)
1207 error (0, errno
, _("failed to clone %s from %s"),
1208 quoteaf_n (0, dst_name
), quoteaf_n (1, src_name
));
1210 goto close_src_and_dst_desc
;
1212 data_copy_required
= false;
1216 if (data_copy_required
)
1218 /* Choose a suitable buffer size; it may be adjusted later. */
1219 size_t buf_alignment
= getpagesize ();
1220 size_t buf_size
= io_blksize (sb
);
1221 size_t hole_size
= ST_BLKSIZE (sb
);
1223 fdadvise (source_desc
, 0, 0, FADVISE_SEQUENTIAL
);
1225 /* Deal with sparse files. */
1226 bool make_holes
= false;
1227 bool sparse_src
= is_probably_sparse (&src_open_sb
);
1229 if (S_ISREG (sb
.st_mode
))
1231 /* Even with --sparse=always, try to create holes only
1232 if the destination is a regular file. */
1233 if (x
->sparse_mode
== SPARSE_ALWAYS
)
1236 /* Use a heuristic to determine whether SRC_NAME contains any sparse
1237 blocks. If the file has fewer blocks than would normally be
1238 needed for a file of its size, then at least one of the blocks in
1239 the file is a hole. */
1240 if (x
->sparse_mode
== SPARSE_AUTO
&& sparse_src
)
1244 /* If not making a sparse file, try to use a more-efficient
1248 /* Compute the least common multiple of the input and output
1249 buffer sizes, adjusting for outlandish values. */
1250 size_t blcm_max
= MIN (SIZE_MAX
, SSIZE_MAX
) - buf_alignment
;
1251 size_t blcm
= buffer_lcm (io_blksize (src_open_sb
), buf_size
,
1254 /* Do not bother with a buffer larger than the input file, plus one
1255 byte to make sure the file has not grown while reading it. */
1256 if (S_ISREG (src_open_sb
.st_mode
) && src_open_sb
.st_size
< buf_size
)
1257 buf_size
= src_open_sb
.st_size
+ 1;
1259 /* However, stick with a block size that is a positive multiple of
1260 blcm, overriding the above adjustments. Watch out for
1262 buf_size
+= blcm
- 1;
1263 buf_size
-= buf_size
% blcm
;
1264 if (buf_size
== 0 || blcm_max
< buf_size
)
1268 buf_alloc
= xmalloc (buf_size
+ buf_alignment
);
1269 buf
= ptr_align (buf_alloc
, buf_alignment
);
1273 bool normal_copy_required
;
1275 /* Perform an efficient extent-based copy, falling back to the
1276 standard copy only if the initial extent scan fails. If the
1277 '--sparse=never' option is specified, write all data but use
1278 any extents to read more efficiently. */
1279 if (extent_copy (source_desc
, dest_desc
, buf
, buf_size
, hole_size
,
1280 src_open_sb
.st_size
,
1281 make_holes
? x
->sparse_mode
: SPARSE_NEVER
,
1282 src_name
, dst_name
, &normal_copy_required
))
1283 goto preserve_metadata
;
1285 if (! normal_copy_required
)
1288 goto close_src_and_dst_desc
;
1293 bool wrote_hole_at_eof
;
1294 if (! sparse_copy (source_desc
, dest_desc
, buf
, buf_size
,
1295 make_holes
? hole_size
: 0,
1296 x
->sparse_mode
== SPARSE_ALWAYS
, src_name
, dst_name
,
1297 UINTMAX_MAX
, &n_read
,
1298 &wrote_hole_at_eof
))
1301 goto close_src_and_dst_desc
;
1303 else if (wrote_hole_at_eof
&& ftruncate (dest_desc
, n_read
) < 0)
1305 error (0, errno
, _("failed to extend %s"), quoteaf (dst_name
));
1307 goto close_src_and_dst_desc
;
1312 if (x
->preserve_timestamps
)
1314 struct timespec timespec
[2];
1315 timespec
[0] = get_stat_atime (src_sb
);
1316 timespec
[1] = get_stat_mtime (src_sb
);
1318 if (fdutimens (dest_desc
, dst_name
, timespec
) != 0)
1320 error (0, errno
, _("preserving times for %s"), quoteaf (dst_name
));
1321 if (x
->require_preserve
)
1324 goto close_src_and_dst_desc
;
1329 /* Set ownership before xattrs as changing owners will
1330 clear capabilities. */
1331 if (x
->preserve_ownership
&& ! SAME_OWNER_AND_GROUP (*src_sb
, sb
))
1333 switch (set_owner (x
, dst_name
, dest_desc
, src_sb
, *new_dst
, &sb
))
1337 goto close_src_and_dst_desc
;
1340 src_mode
&= ~ (S_ISUID
| S_ISGID
| S_ISVTX
);
1345 /* To allow copying xattrs on read-only files, temporarily chmod u+rw.
1346 This workaround is required as an inode permission check is done
1347 by xattr_permission() in fs/xattr.c of the GNU/Linux kernel tree. */
1348 if (x
->preserve_xattr
)
1350 bool access_changed
= false;
1352 if (!(sb
.st_mode
& S_IWUSR
) && geteuid () != ROOT_UID
)
1353 access_changed
= fchmod_or_lchmod (dest_desc
, dst_name
, 0600) == 0;
1355 if (!copy_attr (src_name
, source_desc
, dst_name
, dest_desc
, x
)
1356 && x
->require_preserve_xattr
)
1360 fchmod_or_lchmod (dest_desc
, dst_name
, dst_mode
& ~omitted_permissions
);
1363 set_author (dst_name
, dest_desc
, src_sb
);
1365 if (x
->preserve_mode
|| x
->move_mode
)
1367 if (copy_acl (src_name
, source_desc
, dst_name
, dest_desc
, src_mode
) != 0
1368 && x
->require_preserve
)
1371 else if (x
->set_mode
)
1373 if (set_acl (dst_name
, dest_desc
, x
->mode
) != 0)
1376 else if (x
->explicit_no_preserve_mode
)
1378 if (set_acl (dst_name
, dest_desc
, 0666 & ~cached_umask ()) != 0)
1381 else if (omitted_permissions
)
1383 omitted_permissions
&= ~ cached_umask ();
1384 if (omitted_permissions
1385 && fchmod_or_lchmod (dest_desc
, dst_name
, dst_mode
) != 0)
1387 error (0, errno
, _("preserving permissions for %s"),
1388 quoteaf (dst_name
));
1389 if (x
->require_preserve
)
1394 close_src_and_dst_desc
:
1395 if (close (dest_desc
) < 0)
1397 error (0, errno
, _("failed to close %s"), quoteaf (dst_name
));
1401 if (close (source_desc
) < 0)
1403 error (0, errno
, _("failed to close %s"), quoteaf (src_name
));
1412 /* Return true if it's ok that the source and destination
1413 files are the 'same' by some measure. The goal is to avoid
1414 making the 'copy' operation remove both copies of the file
1415 in that case, while still allowing the user to e.g., move or
1416 copy a regular file onto a symlink that points to it.
1417 Try to minimize the cost of this function in the common case.
1418 Set *RETURN_NOW if we've determined that the caller has no more
1419 work to do and should return successfully, right away. */
1422 same_file_ok (char const *src_name
, struct stat
const *src_sb
,
1423 char const *dst_name
, struct stat
const *dst_sb
,
1424 const struct cp_options
*x
, bool *return_now
)
1426 const struct stat
*src_sb_link
;
1427 const struct stat
*dst_sb_link
;
1428 struct stat tmp_dst_sb
;
1429 struct stat tmp_src_sb
;
1432 bool same
= SAME_INODE (*src_sb
, *dst_sb
);
1434 *return_now
= false;
1436 /* FIXME: this should (at the very least) be moved into the following
1437 if-block. More likely, it should be removed, because it inhibits
1438 making backups. But removing it will result in a change in behavior
1439 that will probably have to be documented -- and tests will have to
1441 if (same
&& x
->hard_link
)
1447 if (x
->dereference
== DEREF_NEVER
)
1451 /* If both the source and destination files are symlinks (and we'll
1452 know this here IFF preserving symlinks), then it's usually ok
1453 when they are distinct. */
1454 if (S_ISLNK (src_sb
->st_mode
) && S_ISLNK (dst_sb
->st_mode
))
1456 bool sn
= same_name (src_name
, dst_name
);
1459 /* It's fine when we're making any type of backup. */
1460 if (x
->backup_type
!= no_backups
)
1463 /* Here we have two symlinks that are hard-linked together,
1464 and we're not making backups. In this unusual case, simply
1465 returning true would lead to mv calling "rename(A,B)",
1466 which would do nothing and return 0. */
1470 return ! x
->move_mode
;
1477 src_sb_link
= src_sb
;
1478 dst_sb_link
= dst_sb
;
1485 if (lstat (dst_name
, &tmp_dst_sb
) != 0
1486 || lstat (src_name
, &tmp_src_sb
) != 0)
1489 src_sb_link
= &tmp_src_sb
;
1490 dst_sb_link
= &tmp_dst_sb
;
1492 same_link
= SAME_INODE (*src_sb_link
, *dst_sb_link
);
1494 /* If both are symlinks, then it's ok, but only if the destination
1495 will be unlinked before being opened. This is like the test
1496 above, but with the addition of the unlink_dest_before_opening
1497 conjunct because otherwise, with two symlinks to the same target,
1498 we'd end up truncating the source file. */
1499 if (S_ISLNK (src_sb_link
->st_mode
) && S_ISLNK (dst_sb_link
->st_mode
)
1500 && x
->unlink_dest_before_opening
)
1504 /* The backup code ensures there's a copy, so it's usually ok to
1505 remove any destination file. One exception is when both
1506 source and destination are the same directory entry. In that
1507 case, moving the destination file aside (in making the backup)
1508 would also rename the source file and result in an error. */
1509 if (x
->backup_type
!= no_backups
)
1513 /* In copy mode when dereferencing symlinks, if the source is a
1514 symlink and the dest is not, then backing up the destination
1515 (moving it aside) would make it a dangling symlink, and the
1516 subsequent attempt to open it in copy_reg would fail with
1517 a misleading diagnostic. Avoid that by returning zero in
1518 that case so the caller can make cp (or mv when it has to
1519 resort to reading the source file) fail now. */
1521 /* FIXME-note: even with the following kludge, we can still provoke
1522 the offending diagnostic. It's just a little harder to do :-)
1523 $ rm -f a b c; touch c; ln -s c b; ln -s b a; cp -b a b
1524 cp: cannot open 'a' for reading: No such file or directory
1525 That's misleading, since a subsequent 'ls' shows that 'a'
1527 One solution would be to open the source file *before* moving
1528 aside the destination, but that'd involve a big rewrite. */
1530 && x
->dereference
!= DEREF_NEVER
1531 && S_ISLNK (src_sb_link
->st_mode
)
1532 && ! S_ISLNK (dst_sb_link
->st_mode
))
1538 /* FIXME: What about case insensitive file systems ? */
1539 return ! same_name (src_name
, dst_name
);
1543 /* FIXME: use or remove */
1545 /* If we're making a backup, we'll detect the problem case in
1546 copy_reg because SRC_NAME will no longer exist. Allowing
1547 the test to be deferred lets cp do some useful things.
1548 But when creating hardlinks and SRC_NAME is a symlink
1549 but DST_NAME is not we must test anyway. */
1551 || !S_ISLNK (src_sb_link
->st_mode
)
1552 || S_ISLNK (dst_sb_link
->st_mode
))
1555 if (x
->dereference
!= DEREF_NEVER
)
1559 if (x
->move_mode
|| x
->unlink_dest_before_opening
)
1561 /* They may refer to the same file if we're in move mode and the
1562 target is a symlink. That is ok, since we remove any existing
1563 destination file before opening it -- via 'rename' if they're on
1564 the same file system, via 'unlink (DST_NAME)' otherwise. */
1565 if (S_ISLNK (dst_sb_link
->st_mode
))
1568 /* It's not ok if they're distinct hard links to the same file as
1569 this causes a race condition and we may lose data in this case. */
1571 && 1 < dst_sb_link
->st_nlink
1572 && ! same_name (src_name
, dst_name
))
1573 return ! x
->move_mode
;
1576 /* If neither is a symlink, then it's ok as long as they aren't
1577 hard links to the same file. */
1578 if (!S_ISLNK (src_sb_link
->st_mode
) && !S_ISLNK (dst_sb_link
->st_mode
))
1580 if (!SAME_INODE (*src_sb_link
, *dst_sb_link
))
1583 /* If they are the same file, it's ok if we're making hard links. */
1591 /* At this point, it is normally an error (data loss) to move a symlink
1592 onto its referent, but in at least one narrow case, it is not:
1594 1) src is a symlink,
1595 2) dest has a link count of 2 or more and
1596 3) dest and the referent of src are not the same directory entry,
1597 then it's ok, since while we'll lose one of those hard links,
1598 src will still point to a remaining link.
1599 Note that technically, condition #3 obviates condition #2, but we
1600 retain the 1 < st_nlink condition because that means fewer invocations
1601 of the more expensive #3.
1604 $ touch f && ln f l && ln -s f s
1606 -rw-------. 2 0 Jan 4 22:46 f
1607 -rw-------. 2 0 Jan 4 22:46 l
1608 lrwxrwxrwx. 1 1 Jan 4 22:46 s -> f
1609 this must fail: mv s f
1610 this must succeed: mv s l */
1612 && S_ISLNK (src_sb
->st_mode
)
1613 && 1 < dst_sb_link
->st_nlink
)
1615 char *abs_src
= canonicalize_file_name (src_name
);
1618 bool result
= ! same_name (abs_src
, dst_name
);
1624 /* It's ok to remove a destination symlink. But that works only when we
1625 unlink before opening the destination and when the source and destination
1626 files are on the same partition. */
1627 if (x
->unlink_dest_before_opening
1628 && S_ISLNK (dst_sb_link
->st_mode
))
1629 return dst_sb_link
->st_dev
== src_sb_link
->st_dev
;
1631 if (x
->dereference
== DEREF_NEVER
)
1633 if ( ! S_ISLNK (src_sb_link
->st_mode
))
1634 tmp_src_sb
= *src_sb_link
;
1635 else if (stat (src_name
, &tmp_src_sb
) != 0)
1638 if ( ! S_ISLNK (dst_sb_link
->st_mode
))
1639 tmp_dst_sb
= *dst_sb_link
;
1640 else if (stat (dst_name
, &tmp_dst_sb
) != 0)
1643 if ( ! SAME_INODE (tmp_src_sb
, tmp_dst_sb
))
1646 /* FIXME: shouldn't this be testing whether we're making symlinks? */
1657 /* Return true if FILE, with mode MODE, is writable in the sense of 'mv'.
1658 Always consider a symbolic link to be writable. */
1660 writable_destination (char const *file
, mode_t mode
)
1662 return (S_ISLNK (mode
)
1663 || can_write_any_file ()
1664 || euidaccess (file
, W_OK
) == 0);
1668 overwrite_ok (struct cp_options
const *x
, char const *dst_name
,
1669 struct stat
const *dst_sb
)
1671 if (! writable_destination (dst_name
, dst_sb
->st_mode
))
1673 char perms
[12]; /* "-rwxrwxrwx " ls-style modes. */
1674 strmode (dst_sb
->st_mode
, perms
);
1677 (x
->move_mode
|| x
->unlink_dest_before_opening
1678 || x
->unlink_dest_after_failed_open
)
1679 ? _("%s: replace %s, overriding mode %04lo (%s)? ")
1680 : _("%s: unwritable %s (mode %04lo, %s); try anyway? "),
1681 program_name
, quoteaf (dst_name
),
1682 (unsigned long int) (dst_sb
->st_mode
& CHMOD_MODE_BITS
),
1687 fprintf (stderr
, _("%s: overwrite %s? "),
1688 program_name
, quoteaf (dst_name
));
1694 /* Initialize the hash table implementing a set of F_triple entries
1695 corresponding to destination files. */
1697 dest_info_init (struct cp_options
*x
)
1700 = hash_initialize (DEST_INFO_INITIAL_CAPACITY
,
1707 /* Initialize the hash table implementing a set of F_triple entries
1708 corresponding to source files listed on the command line. */
1710 src_info_init (struct cp_options
*x
)
1713 /* Note that we use triple_hash_no_name here.
1714 Contrast with the use of triple_hash above.
1715 That is necessary because a source file may be specified
1716 in many different ways. We want to warn about this
1722 = hash_initialize (DEST_INFO_INITIAL_CAPACITY
,
1724 triple_hash_no_name
,
1729 /* When effecting a move (e.g., for mv(1)), and given the name DST_NAME
1730 of the destination and a corresponding stat buffer, DST_SB, return
1731 true if the logical 'move' operation should _not_ proceed.
1732 Otherwise, return false.
1733 Depending on options specified in X, this code may issue an
1734 interactive prompt asking whether it's ok to overwrite DST_NAME. */
1736 abandon_move (const struct cp_options
*x
,
1737 char const *dst_name
,
1738 struct stat
const *dst_sb
)
1740 assert (x
->move_mode
);
1741 return (x
->interactive
== I_ALWAYS_NO
1742 || ((x
->interactive
== I_ASK_USER
1743 || (x
->interactive
== I_UNSPECIFIED
1745 && ! writable_destination (dst_name
, dst_sb
->st_mode
)))
1746 && ! overwrite_ok (x
, dst_name
, dst_sb
)));
1749 /* Print --verbose output on standard output, e.g. 'new' -> 'old'.
1750 If BACKUP_DST_NAME is non-NULL, then also indicate that it is
1751 the name of a backup file. */
1753 emit_verbose (char const *src
, char const *dst
, char const *backup_dst_name
)
1755 printf ("%s -> %s", quoteaf_n (0, src
), quoteaf_n (1, dst
));
1756 if (backup_dst_name
)
1757 printf (_(" (backup: %s)"), quoteaf (backup_dst_name
));
1761 /* A wrapper around "setfscreatecon (NULL)" that exits upon failure. */
1763 restore_default_fscreatecon_or_die (void)
1765 if (setfscreatecon (NULL
) != 0)
1766 die (EXIT_FAILURE
, errno
,
1767 _("failed to restore the default file creation context"));
1770 /* Create a hard link DST_NAME to SRC_NAME, honoring the REPLACE, VERBOSE and
1771 DEREFERENCE settings. Return true upon success. Otherwise, diagnose the
1772 failure and return false. If SRC_NAME is a symbolic link, then it will not
1773 be followed unless DEREFERENCE is true.
1774 If the system doesn't support hard links to symbolic links, then DST_NAME
1775 will be created as a symbolic link to SRC_NAME. */
1777 create_hard_link (char const *src_name
, char const *dst_name
,
1778 bool replace
, bool verbose
, bool dereference
)
1780 /* We want to guarantee that symlinks are not followed, unless requested. */
1783 flags
= AT_SYMLINK_FOLLOW
;
1785 bool link_failed
= (linkat (AT_FDCWD
, src_name
, AT_FDCWD
, dst_name
, flags
)
1788 /* If the link failed because of an existing destination,
1789 remove that file and then call link again. */
1790 if (link_failed
&& replace
&& errno
== EEXIST
)
1792 if (unlink (dst_name
) != 0)
1794 error (0, errno
, _("cannot remove %s"), quoteaf (dst_name
));
1798 printf (_("removed %s\n"), quoteaf (dst_name
));
1799 link_failed
= (linkat (AT_FDCWD
, src_name
, AT_FDCWD
, dst_name
, flags
)
1805 error (0, errno
, _("cannot create hard link %s to %s"),
1806 quoteaf_n (0, dst_name
), quoteaf_n (1, src_name
));
1813 /* Return true if the current file should be (tried to be) dereferenced:
1814 either for DEREF_ALWAYS or for DEREF_COMMAND_LINE_ARGUMENTS in the case
1815 where the current file is a COMMAND_LINE_ARG; otherwise return false. */
1816 static inline bool _GL_ATTRIBUTE_PURE
1817 should_dereference (const struct cp_options
*x
, bool command_line_arg
)
1819 return x
->dereference
== DEREF_ALWAYS
1820 || (x
->dereference
== DEREF_COMMAND_LINE_ARGUMENTS
1821 && command_line_arg
);
1824 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
1825 any type. NEW_DST should be true if the file DST_NAME cannot
1826 exist because its parent directory was just created; NEW_DST should
1827 be false if DST_NAME might already exist. A non-null PARENT describes the
1828 parent directory. ANCESTORS points to a linked, null terminated list of
1829 devices and inodes of parent directories of SRC_NAME. COMMAND_LINE_ARG
1830 is true iff SRC_NAME was specified on the command line.
1831 FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG is both input and output.
1832 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
1833 same as) DST_NAME; otherwise, clear it.
1834 Return true if successful. */
1836 copy_internal (char const *src_name
, char const *dst_name
,
1838 struct stat
const *parent
,
1839 struct dir_list
*ancestors
,
1840 const struct cp_options
*x
,
1841 bool command_line_arg
,
1842 bool *first_dir_created_per_command_line_arg
,
1843 bool *copy_into_self
,
1844 bool *rename_succeeded
)
1849 mode_t dst_mode
IF_LINT ( = 0);
1850 mode_t dst_mode_bits
;
1851 mode_t omitted_permissions
;
1852 bool restore_dst_mode
= false;
1853 char *earlier_file
= NULL
;
1854 char *dst_backup
= NULL
;
1855 bool backup_succeeded
= false;
1857 bool copied_as_regular
= false;
1858 bool dest_is_symlink
= false;
1859 bool have_dst_lstat
= false;
1861 if (x
->move_mode
&& rename_succeeded
)
1862 *rename_succeeded
= false;
1864 *copy_into_self
= false;
1866 if (XSTAT (x
, src_name
, &src_sb
) != 0)
1868 error (0, errno
, _("cannot stat %s"), quoteaf (src_name
));
1872 src_mode
= src_sb
.st_mode
;
1874 if (S_ISDIR (src_mode
) && !x
->recursive
)
1876 error (0, 0, ! x
->install_mode
/* cp */
1877 ? _("-r not specified; omitting directory %s")
1878 : _("omitting directory %s"),
1879 quoteaf (src_name
));
1883 /* Detect the case in which the same source file appears more than
1884 once on the command line and no backup option has been selected.
1885 If so, simply warn and don't copy it the second time.
1886 This check is enabled only if x->src_info is non-NULL. */
1887 if (command_line_arg
)
1889 if ( ! S_ISDIR (src_sb
.st_mode
)
1890 && x
->backup_type
== no_backups
1891 && seen_file (x
->src_info
, src_name
, &src_sb
))
1893 error (0, 0, _("warning: source file %s specified more than once"),
1894 quoteaf (src_name
));
1898 record_file (x
->src_info
, src_name
, &src_sb
);
1901 bool dereference
= should_dereference (x
, command_line_arg
);
1905 /* Regular files can be created by writing through symbolic
1906 links, but other files cannot. So use stat on the
1907 destination when copying a regular file, and lstat otherwise.
1908 However, if we intend to unlink or remove the destination
1909 first, use lstat, since a copy won't actually be made to the
1910 destination in that case. */
1912 ((S_ISREG (src_mode
)
1913 || (x
->copy_as_regular
1914 && ! (S_ISDIR (src_mode
) || S_ISLNK (src_mode
))))
1915 && ! (x
->move_mode
|| x
->symbolic_link
|| x
->hard_link
1916 || x
->backup_type
!= no_backups
1917 || x
->unlink_dest_before_opening
));
1919 ? stat (dst_name
, &dst_sb
)
1920 : lstat (dst_name
, &dst_sb
))
1923 if (errno
!= ENOENT
)
1925 error (0, errno
, _("cannot stat %s"), quoteaf (dst_name
));
1934 { /* Here, we know that dst_name exists, at least to the point
1935 that it is stat'able or lstat'able. */
1938 have_dst_lstat
= !use_stat
;
1939 if (! same_file_ok (src_name
, &src_sb
, dst_name
, &dst_sb
,
1942 error (0, 0, _("%s and %s are the same file"),
1943 quoteaf_n (0, src_name
), quoteaf_n (1, dst_name
));
1947 if (!S_ISDIR (src_mode
) && x
->update
)
1949 /* When preserving time stamps (but not moving within a file
1950 system), don't worry if the destination time stamp is
1951 less than the source merely because of time stamp
1953 int options
= ((x
->preserve_timestamps
1955 && dst_sb
.st_dev
== src_sb
.st_dev
))
1956 ? UTIMECMP_TRUNCATE_SOURCE
1959 if (0 <= utimecmp (dst_name
, &dst_sb
, &src_sb
, options
))
1961 /* We're using --update and the destination is not older
1962 than the source, so do not copy or move. Pretend the
1963 rename succeeded, so the caller (if it's mv) doesn't
1964 end up removing the source file. */
1965 if (rename_succeeded
)
1966 *rename_succeeded
= true;
1968 /* However, we still must record that we've processed
1969 this src/dest pair, in case this source file is
1970 hard-linked to another one. In that case, we'll use
1971 the mapping information to link the corresponding
1972 destination names. */
1973 earlier_file
= remember_copied (dst_name
, src_sb
.st_ino
,
1977 /* Note we currently replace DST_NAME unconditionally,
1978 even if it was a newer separate file. */
1979 if (! create_hard_link (earlier_file
, dst_name
, true,
1980 x
->verbose
, dereference
))
1990 /* When there is an existing destination file, we may end up
1991 returning early, and hence not copying/moving the file.
1992 This may be due to an interactive 'negative' reply to the
1993 prompt about the existing file. It may also be due to the
1994 use of the --no-clobber option.
1996 cp and mv treat -i and -f differently. */
1999 if (abandon_move (x
, dst_name
, &dst_sb
))
2001 /* Pretend the rename succeeded, so the caller (mv)
2002 doesn't end up removing the source file. */
2003 if (rename_succeeded
)
2004 *rename_succeeded
= true;
2010 if (! S_ISDIR (src_mode
)
2011 && (x
->interactive
== I_ALWAYS_NO
2012 || (x
->interactive
== I_ASK_USER
2013 && ! overwrite_ok (x
, dst_name
, &dst_sb
))))
2020 if (!S_ISDIR (dst_sb
.st_mode
))
2022 if (S_ISDIR (src_mode
))
2024 if (x
->move_mode
&& x
->backup_type
!= no_backups
)
2026 /* Moving a directory onto an existing
2027 non-directory is ok only with --backup. */
2032 _("cannot overwrite non-directory %s with directory %s"),
2033 quoteaf_n (0, dst_name
), quoteaf_n (1, src_name
));
2038 /* Don't let the user destroy their data, even if they try hard:
2039 This mv command must fail (likewise for cp):
2040 rm -rf a b c; mkdir a b c; touch a/f b/f; mv a/f b/f c
2041 Otherwise, the contents of b/f would be lost.
2042 In the case of 'cp', b/f would be lost if the user simulated
2043 a move using cp and rm.
2044 Note that it works fine if you use --backup=numbered. */
2045 if (command_line_arg
2046 && x
->backup_type
!= numbered_backups
2047 && seen_file (x
->dest_info
, dst_name
, &dst_sb
))
2050 _("will not overwrite just-created %s with %s"),
2051 quoteaf_n (0, dst_name
), quoteaf_n (1, src_name
));
2056 if (!S_ISDIR (src_mode
))
2058 if (S_ISDIR (dst_sb
.st_mode
))
2060 if (x
->move_mode
&& x
->backup_type
!= no_backups
)
2062 /* Moving a non-directory onto an existing
2063 directory is ok only with --backup. */
2068 _("cannot overwrite directory %s with non-directory"),
2069 quoteaf (dst_name
));
2077 /* Don't allow user to move a directory onto a non-directory. */
2078 if (S_ISDIR (src_sb
.st_mode
) && !S_ISDIR (dst_sb
.st_mode
)
2079 && x
->backup_type
== no_backups
)
2082 _("cannot move directory onto non-directory: %s -> %s"),
2083 quotef_n (0, src_name
), quotef_n (0, dst_name
));
2088 if (x
->backup_type
!= no_backups
2089 /* Don't try to back up a destination if the last
2090 component of src_name is "." or "..". */
2091 && ! dot_or_dotdot (last_component (src_name
))
2092 /* Create a backup of each destination directory in move mode,
2093 but not in copy mode. FIXME: it might make sense to add an
2094 option to suppress backup creation also for move mode.
2095 That would let one use mv to merge new content into an
2096 existing hierarchy. */
2097 && (x
->move_mode
|| ! S_ISDIR (dst_sb
.st_mode
)))
2099 char *tmp_backup
= find_backup_file_name (dst_name
,
2102 /* Detect (and fail) when creating the backup file would
2103 destroy the source file. Before, running the commands
2104 cd /tmp; rm -f a a~; : > a; echo A > a~; cp --b=simple a~ a
2105 would leave two zero-length files: a and a~. */
2106 /* FIXME: but simply change e.g., the final a~ to './a~'
2107 and the source will still be destroyed. */
2108 if (STREQ (tmp_backup
, src_name
))
2112 ? _("backing up %s would destroy source; %s not moved")
2113 : _("backing up %s would destroy source; %s not copied"));
2115 quoteaf_n (0, dst_name
),
2116 quoteaf_n (1, src_name
));
2122 Using alloca for a file name that may be arbitrarily
2123 long is not recommended. In fact, even forming such a name
2124 should be discouraged. Eventually, this code will be rewritten
2125 to use fts, so using alloca here will be less of a problem. */
2126 ASSIGN_STRDUPA (dst_backup
, tmp_backup
);
2128 /* In move mode, when src_name and dst_name are on the
2129 same partition (FIXME, and when they are non-directories),
2130 make the operation atomic: link dest
2131 to backup, then rename src to dest. */
2132 if (rename (dst_name
, dst_backup
) != 0)
2134 if (errno
!= ENOENT
)
2136 error (0, errno
, _("cannot backup %s"),
2137 quoteaf (dst_name
));
2147 backup_succeeded
= true;
2151 else if (! S_ISDIR (dst_sb
.st_mode
)
2152 /* Never unlink dst_name when in move mode. */
2154 && (x
->unlink_dest_before_opening
2155 || (x
->preserve_links
&& 1 < dst_sb
.st_nlink
)
2156 || (x
->dereference
== DEREF_NEVER
2157 && ! S_ISREG (src_sb
.st_mode
))
2160 if (unlink (dst_name
) != 0 && errno
!= ENOENT
)
2162 error (0, errno
, _("cannot remove %s"), quoteaf (dst_name
));
2167 printf (_("removed %s\n"), quoteaf (dst_name
));
2172 /* Ensure we don't try to copy through a symlink that was
2173 created by a prior call to this function. */
2174 if (command_line_arg
2177 && x
->backup_type
== no_backups
)
2179 bool lstat_ok
= true;
2180 struct stat tmp_buf
;
2181 struct stat
*dst_lstat_sb
;
2183 /* If we called lstat above, good: use that data.
2184 Otherwise, call lstat here, in case dst_name is a symlink. */
2186 dst_lstat_sb
= &dst_sb
;
2189 if (lstat (dst_name
, &tmp_buf
) == 0)
2190 dst_lstat_sb
= &tmp_buf
;
2195 /* Never copy through a symlink we've just created. */
2197 && S_ISLNK (dst_lstat_sb
->st_mode
)
2198 && seen_file (x
->dest_info
, dst_name
, dst_lstat_sb
))
2201 _("will not copy %s through just-created symlink %s"),
2202 quoteaf_n (0, src_name
), quoteaf_n (1, dst_name
));
2207 /* If the source is a directory, we don't always create the destination
2208 directory. So --verbose should not announce anything until we're
2209 sure we'll create a directory. */
2210 if (x
->verbose
&& !S_ISDIR (src_mode
))
2211 emit_verbose (src_name
, dst_name
, backup_succeeded
? dst_backup
: NULL
);
2213 /* Associate the destination file name with the source device and inode
2214 so that if we encounter a matching dev/ino pair in the source tree
2215 we can arrange to create a hard link between the corresponding names
2216 in the destination tree.
2218 When using the --link (-l) option, there is no need to take special
2219 measures, because (barring race conditions) files that are hard-linked
2220 in the source tree will also be hard-linked in the destination tree.
2222 Sometimes, when preserving links, we have to record dev/ino even
2223 though st_nlink == 1:
2224 - when in move_mode, since we may be moving a group of N hard-linked
2225 files (via two or more command line arguments) to a different
2226 partition; the links may be distributed among the command line
2227 arguments (possibly hierarchies) so that the link count of
2228 the final, once-linked source file is reduced to 1 when it is
2229 considered below. But in this case (for mv) we don't need to
2230 incur the expense of recording the dev/ino => name mapping; all we
2231 really need is a lookup, to see if the dev/ino pair has already
2233 - when using -H and processing a command line argument;
2234 that command line argument could be a symlink pointing to another
2235 command line argument. With 'cp -H --preserve=link', we hard-link
2236 those two destination files.
2237 - likewise for -L except that it applies to all files, not just
2238 command line arguments.
2240 Also, with --recursive, record dev/ino of each command-line directory.
2241 We'll use that info to detect this problem: cp -R dir dir. */
2243 if (x
->recursive
&& S_ISDIR (src_mode
))
2245 if (command_line_arg
)
2246 earlier_file
= remember_copied (dst_name
, src_sb
.st_ino
, src_sb
.st_dev
);
2248 earlier_file
= src_to_dest_lookup (src_sb
.st_ino
, src_sb
.st_dev
);
2250 else if (x
->move_mode
&& src_sb
.st_nlink
== 1)
2252 earlier_file
= src_to_dest_lookup (src_sb
.st_ino
, src_sb
.st_dev
);
2254 else if (x
->preserve_links
2256 && (1 < src_sb
.st_nlink
2257 || (command_line_arg
2258 && x
->dereference
== DEREF_COMMAND_LINE_ARGUMENTS
)
2259 || x
->dereference
== DEREF_ALWAYS
))
2261 earlier_file
= remember_copied (dst_name
, src_sb
.st_ino
, src_sb
.st_dev
);
2264 /* Did we copy this inode somewhere else (in this command line argument)
2265 and therefore this is a second hard link to the inode? */
2269 /* Avoid damaging the destination file system by refusing to preserve
2270 hard-linked directories (which are found at least in Netapp snapshot
2272 if (S_ISDIR (src_mode
))
2274 /* If src_name and earlier_file refer to the same directory entry,
2275 then warn about copying a directory into itself. */
2276 if (same_name (src_name
, earlier_file
))
2278 error (0, 0, _("cannot copy a directory, %s, into itself, %s"),
2279 quoteaf_n (0, top_level_src_name
),
2280 quoteaf_n (1, top_level_dst_name
));
2281 *copy_into_self
= true;
2284 else if (same_name (dst_name
, earlier_file
))
2286 error (0, 0, _("warning: source directory %s "
2287 "specified more than once"),
2288 quoteaf (top_level_src_name
));
2289 /* In move mode, if a previous rename succeeded, then
2290 we won't be in this path as the source is missing. If the
2291 rename previously failed, then that has been handled, so
2292 pretend this attempt succeeded so the source isn't removed. */
2293 if (x
->move_mode
&& rename_succeeded
)
2294 *rename_succeeded
= true;
2295 /* We only do backups in move mode, and for non directories.
2296 So just ignore this repeated entry. */
2299 else if (x
->dereference
== DEREF_ALWAYS
2300 || (command_line_arg
2301 && x
->dereference
== DEREF_COMMAND_LINE_ARGUMENTS
))
2303 /* This happens when e.g., encountering a directory for the
2304 second or subsequent time via symlinks when cp is invoked
2305 with -R and -L. E.g.,
2306 rm -rf a b c d; mkdir a b c d; ln -s ../c a; ln -s ../c b;
2312 error (0, 0, _("will not create hard link %s to directory %s"),
2313 quoteaf_n (0, dst_name
), quoteaf_n (1, earlier_file
));
2319 if (! create_hard_link (earlier_file
, dst_name
, true, x
->verbose
,
2329 if (rename (src_name
, dst_name
) == 0)
2331 if (x
->verbose
&& S_ISDIR (src_mode
))
2332 emit_verbose (src_name
, dst_name
,
2333 backup_succeeded
? dst_backup
: NULL
);
2335 if (x
->set_security_context
)
2337 /* -Z failures are only warnings currently. */
2338 (void) set_file_security_ctx (dst_name
, false, true, x
);
2341 if (rename_succeeded
)
2342 *rename_succeeded
= true;
2344 if (command_line_arg
)
2346 /* Record destination dev/ino/name, so that if we are asked
2347 to overwrite that file again, we can detect it and fail. */
2348 /* It's fine to use the _source_ stat buffer (src_sb) to get the
2349 _destination_ dev/ino, since the rename above can't have
2350 changed those, and 'mv' always uses lstat.
2351 We could limit it further by operating
2352 only on non-directories. */
2353 record_file (x
->dest_info
, dst_name
, &src_sb
);
2359 /* FIXME: someday, consider what to do when moving a directory into
2360 itself but when source and destination are on different devices. */
2362 /* This happens when attempting to rename a directory to a
2363 subdirectory of itself. */
2364 if (errno
== EINVAL
)
2366 /* FIXME: this is a little fragile in that it relies on rename(2)
2367 failing with a specific errno value. Expect problems on
2368 non-POSIX systems. */
2369 error (0, 0, _("cannot move %s to a subdirectory of itself, %s"),
2370 quoteaf_n (0, top_level_src_name
),
2371 quoteaf_n (1, top_level_dst_name
));
2373 /* Note that there is no need to call forget_created here,
2374 (compare with the other calls in this file) since the
2375 destination directory didn't exist before. */
2377 *copy_into_self
= true;
2378 /* FIXME-cleanup: Don't return true here; adjust mv.c accordingly.
2379 The only caller that uses this code (mv.c) ends up setting its
2380 exit status to nonzero when copy_into_self is nonzero. */
2384 /* WARNING: there probably exist systems for which an inter-device
2385 rename fails with a value of errno not handled here.
2386 If/as those are reported, add them to the condition below.
2387 If this happens to you, please do the following and send the output
2388 to the bug-reporting address (e.g., in the output of cp --help):
2389 touch k; perl -e 'rename "k","/tmp/k" or print "$!(",$!+0,")\n"'
2390 where your current directory is on one partition and /tmp is the other.
2391 Also, please try to find the E* errno macro name corresponding to
2392 the diagnostic and parenthesized integer, and include that in your
2393 e-mail. One way to do that is to run a command like this
2394 find /usr/include/. -type f \
2395 | xargs grep 'define.*\<E[A-Z]*\>.*\<18\>' /dev/null
2396 where you'd replace '18' with the integer in parentheses that
2397 was output from the perl one-liner above.
2398 If necessary, of course, change '/tmp' to some other directory. */
2401 /* There are many ways this can happen due to a race condition.
2402 When something happens between the initial XSTAT and the
2403 subsequent rename, we can get many different types of errors.
2404 For example, if the destination is initially a non-directory
2405 or non-existent, but it is created as a directory, the rename
2406 fails. If two 'mv' commands try to rename the same file at
2407 about the same time, one will succeed and the other will fail.
2408 If the permissions on the directory containing the source or
2409 destination file are made too restrictive, the rename will
2412 _("cannot move %s to %s"),
2413 quoteaf_n (0, src_name
), quoteaf_n (1, dst_name
));
2414 forget_created (src_sb
.st_ino
, src_sb
.st_dev
);
2418 /* The rename attempt has failed. Remove any existing destination
2419 file so that a cross-device 'mv' acts as if it were really using
2420 the rename syscall. Note both src and dst must both be directories
2421 or not, and this is enforced above. Therefore we check the src_mode
2422 and operate on dst_name here as a tighter constraint and also because
2423 src_mode is readily available here. */
2424 if ((S_ISDIR (src_mode
) ? rmdir (dst_name
) : unlink (dst_name
)) != 0
2428 _("inter-device move failed: %s to %s; unable to remove target"),
2429 quoteaf_n (0, src_name
), quoteaf_n (1, dst_name
));
2430 forget_created (src_sb
.st_ino
, src_sb
.st_dev
);
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;
2528 emit_verbose (src_name
, dst_name
, NULL
);
2532 omitted_permissions
= 0;
2534 /* For directories, the process global context could be reset for
2535 descendents, so use it to set the context for existing dirs here.
2536 This will also give earlier indication of failure to set ctx. */
2537 if (x
->set_security_context
|| x
->preserve_security_context
)
2538 if (! set_file_security_ctx (dst_name
, x
->preserve_security_context
,
2541 if (x
->require_preserve_context
)
2546 /* Decide whether to copy the contents of the directory. */
2547 if (x
->one_file_system
&& parent
&& parent
->st_dev
!= src_sb
.st_dev
)
2549 /* Here, we are crossing a file system boundary and cp's -x option
2550 is in effect: so don't copy the contents of this directory. */
2554 /* Copy the contents of the directory. Don't just return if
2555 this fails -- otherwise, the failure to read a single file
2556 in a source directory would cause the containing destination
2557 directory not to have owner/perms set properly. */
2558 delayed_ok
= copy_dir (src_name
, dst_name
, new_dst
, &src_sb
, dir
, x
,
2559 first_dir_created_per_command_line_arg
,
2563 else if (x
->symbolic_link
)
2565 dest_is_symlink
= true;
2566 if (*src_name
!= '/')
2568 /* Check that DST_NAME denotes a file in the current directory. */
2570 struct stat dst_parent_sb
;
2572 bool in_current_dir
;
2574 dst_parent
= dir_name (dst_name
);
2576 in_current_dir
= (STREQ (".", dst_parent
)
2577 /* If either stat call fails, it's ok not to report
2578 the failure and say dst_name is in the current
2579 directory. Other things will fail later. */
2580 || stat (".", &dot_sb
) != 0
2581 || stat (dst_parent
, &dst_parent_sb
) != 0
2582 || SAME_INODE (dot_sb
, dst_parent_sb
));
2585 if (! in_current_dir
)
2588 _("%s: can make relative symbolic links only in current directory"),
2593 if (symlink (src_name
, dst_name
) != 0)
2595 error (0, errno
, _("cannot create symbolic link %s to %s"),
2596 quoteaf_n (0, dst_name
), quoteaf_n (1, src_name
));
2601 /* POSIX 2008 states that it is implementation-defined whether
2602 link() on a symlink creates a hard-link to the symlink, or only
2603 to the referent (effectively dereferencing the symlink) (POSIX
2604 2001 required the latter behavior, although many systems provided
2605 the former). Yet cp, invoked with '--link --no-dereference',
2606 should not follow the link. We can approximate the desired
2607 behavior by skipping this hard-link creating block and instead
2608 copying the symlink, via the 'S_ISLNK'- copying code below.
2610 Note gnulib's linkat module, guarantees that the symlink is not
2611 dereferenced. However its emulation currently doesn't maintain
2612 timestamps or ownership so we only call it when we know the
2613 emulation will not be needed. */
2614 else if (x
->hard_link
2615 && !(! CAN_HARDLINK_SYMLINKS
&& S_ISLNK (src_mode
)
2616 && x
->dereference
== DEREF_NEVER
))
2618 if (! create_hard_link (src_name
, dst_name
, false, false, dereference
))
2621 else if (S_ISREG (src_mode
)
2622 || (x
->copy_as_regular
&& !S_ISLNK (src_mode
)))
2624 copied_as_regular
= true;
2625 /* POSIX says the permission bits of the source file must be
2626 used as the 3rd argument in the open call. Historical
2627 practice passed all the source mode bits to 'open', but the extra
2628 bits were ignored, so it should be the same either way.
2630 This call uses DST_MODE_BITS, not SRC_MODE. These are
2631 normally the same, and the exception (where x->set_mode) is
2632 used only by 'install', which POSIX does not specify and
2633 where DST_MODE_BITS is what's wanted. */
2634 if (! copy_reg (src_name
, dst_name
, x
, dst_mode_bits
& S_IRWXUGO
,
2635 omitted_permissions
, &new_dst
, &src_sb
))
2638 else if (S_ISFIFO (src_mode
))
2640 /* Use mknod, rather than mkfifo, because the former preserves
2641 the special mode bits of a fifo on Solaris 10, while mkfifo
2642 does not. But fall back on mkfifo, because on some BSD systems,
2643 mknod always fails when asked to create a FIFO. */
2644 if (mknod (dst_name
, src_mode
& ~omitted_permissions
, 0) != 0)
2645 if (mkfifo (dst_name
, src_mode
& ~S_IFIFO
& ~omitted_permissions
) != 0)
2647 error (0, errno
, _("cannot create fifo %s"), quoteaf (dst_name
));
2651 else if (S_ISBLK (src_mode
) || S_ISCHR (src_mode
) || S_ISSOCK (src_mode
))
2653 if (mknod (dst_name
, src_mode
& ~omitted_permissions
, src_sb
.st_rdev
)
2656 error (0, errno
, _("cannot create special file %s"),
2657 quoteaf (dst_name
));
2661 else if (S_ISLNK (src_mode
))
2663 char *src_link_val
= areadlink_with_size (src_name
, src_sb
.st_size
);
2664 dest_is_symlink
= true;
2665 if (src_link_val
== NULL
)
2667 error (0, errno
, _("cannot read symbolic link %s"),
2668 quoteaf (src_name
));
2672 if (symlink (src_link_val
, dst_name
) == 0)
2673 free (src_link_val
);
2676 int saved_errno
= errno
;
2677 bool same_link
= false;
2678 if (x
->update
&& !new_dst
&& S_ISLNK (dst_sb
.st_mode
)
2679 && dst_sb
.st_size
== strlen (src_link_val
))
2681 /* See if the destination is already the desired symlink.
2682 FIXME: This behavior isn't documented, and seems wrong
2683 in some cases, e.g., if the destination symlink has the
2684 wrong ownership, permissions, or time stamps. */
2685 char *dest_link_val
=
2686 areadlink_with_size (dst_name
, dst_sb
.st_size
);
2687 if (dest_link_val
&& STREQ (dest_link_val
, src_link_val
))
2689 free (dest_link_val
);
2691 free (src_link_val
);
2695 error (0, saved_errno
, _("cannot create symbolic link %s"),
2696 quoteaf (dst_name
));
2701 if (x
->preserve_security_context
)
2702 restore_default_fscreatecon_or_die ();
2704 if (x
->preserve_ownership
)
2706 /* Preserve the owner and group of the just-'copied'
2707 symbolic link, if possible. */
2709 && lchown (dst_name
, src_sb
.st_uid
, src_sb
.st_gid
) != 0
2710 && ! chown_failure_ok (x
))
2712 error (0, errno
, _("failed to preserve ownership for %s"),
2718 /* Can't preserve ownership of symlinks.
2719 FIXME: maybe give a warning or even error for symlinks
2720 in directories with the sticky bit set -- there, not
2721 preserving owner/group is a potential security problem. */
2727 error (0, 0, _("%s has unknown file type"), quoteaf (src_name
));
2731 /* With -Z or --preserve=context, set the context for existing files.
2732 Note this is done already for copy_reg() for reasons described therein. */
2733 if (!new_dst
&& !x
->copy_as_regular
&& !S_ISDIR (src_mode
)
2734 && (x
->set_security_context
|| x
->preserve_security_context
))
2736 if (! set_file_security_ctx (dst_name
, x
->preserve_security_context
,
2739 if (x
->require_preserve_context
)
2744 if (command_line_arg
&& x
->dest_info
)
2746 /* Now that the destination file is very likely to exist,
2747 add its info to the set. */
2749 if (lstat (dst_name
, &sb
) == 0)
2750 record_file (x
->dest_info
, dst_name
, &sb
);
2753 /* If we've just created a hard-link due to cp's --link option,
2755 if (x
->hard_link
&& ! S_ISDIR (src_mode
)
2756 && !(! CAN_HARDLINK_SYMLINKS
&& S_ISLNK (src_mode
)
2757 && x
->dereference
== DEREF_NEVER
))
2760 if (copied_as_regular
)
2763 /* POSIX says that 'cp -p' must restore the following:
2765 - setuid, setgid bits
2767 If it fails to restore any of those, we may give a warning but
2768 the destination must not be removed.
2769 FIXME: implement the above. */
2771 /* Adjust the times (and if possible, ownership) for the copy.
2772 chown turns off set[ug]id bits for non-root,
2773 so do the chmod last. */
2775 if (x
->preserve_timestamps
)
2777 struct timespec timespec
[2];
2778 timespec
[0] = get_stat_atime (&src_sb
);
2779 timespec
[1] = get_stat_mtime (&src_sb
);
2781 if ((dest_is_symlink
2782 ? utimens_symlink (dst_name
, timespec
)
2783 : utimens (dst_name
, timespec
))
2786 error (0, errno
, _("preserving times for %s"), quoteaf (dst_name
));
2787 if (x
->require_preserve
)
2792 /* Avoid calling chown if we know it's not necessary. */
2793 if (!dest_is_symlink
&& x
->preserve_ownership
2794 && (new_dst
|| !SAME_OWNER_AND_GROUP (src_sb
, dst_sb
)))
2796 switch (set_owner (x
, dst_name
, -1, &src_sb
, new_dst
, &dst_sb
))
2802 src_mode
&= ~ (S_ISUID
| S_ISGID
| S_ISVTX
);
2807 /* Set xattrs after ownership as changing owners will clear capabilities. */
2808 if (x
->preserve_xattr
&& ! copy_attr (src_name
, -1, dst_name
, -1, x
)
2809 && x
->require_preserve_xattr
)
2812 /* The operations beyond this point may dereference a symlink. */
2813 if (dest_is_symlink
)
2816 set_author (dst_name
, -1, &src_sb
);
2818 if (x
->preserve_mode
|| x
->move_mode
)
2820 if (copy_acl (src_name
, -1, dst_name
, -1, src_mode
) != 0
2821 && x
->require_preserve
)
2824 else if (x
->set_mode
)
2826 if (set_acl (dst_name
, -1, x
->mode
) != 0)
2829 else if (x
->explicit_no_preserve_mode
)
2831 if (set_acl (dst_name
, -1, 0777 & ~cached_umask ()) != 0)
2836 if (omitted_permissions
)
2838 omitted_permissions
&= ~ cached_umask ();
2840 if (omitted_permissions
&& !restore_dst_mode
)
2842 /* Permissions were deliberately omitted when the file
2843 was created due to security concerns. See whether
2844 they need to be re-added now. It'd be faster to omit
2845 the lstat, but deducing the current destination mode
2846 is tricky in the presence of implementation-defined
2847 rules for special mode bits. */
2848 if (new_dst
&& lstat (dst_name
, &dst_sb
) != 0)
2850 error (0, errno
, _("cannot stat %s"), quoteaf (dst_name
));
2853 dst_mode
= dst_sb
.st_mode
;
2854 if (omitted_permissions
& ~dst_mode
)
2855 restore_dst_mode
= true;
2859 if (restore_dst_mode
)
2861 if (lchmod (dst_name
, dst_mode
| omitted_permissions
) != 0)
2863 error (0, errno
, _("preserving permissions for %s"),
2864 quoteaf (dst_name
));
2865 if (x
->require_preserve
)
2875 if (x
->preserve_security_context
)
2876 restore_default_fscreatecon_or_die ();
2878 /* We have failed to create the destination file.
2879 If we've just added a dev/ino entry via the remember_copied
2880 call above (i.e., unless we've just failed to create a hard link),
2881 remove the entry associating the source dev/ino with the
2882 destination file name, so we don't try to 'preserve' a link
2883 to a file we didn't create. */
2884 if (earlier_file
== NULL
)
2885 forget_created (src_sb
.st_ino
, src_sb
.st_dev
);
2889 if (rename (dst_backup
, dst_name
) != 0)
2890 error (0, errno
, _("cannot un-backup %s"), quoteaf (dst_name
));
2894 printf (_("%s -> %s (unbackup)\n"),
2895 quoteaf_n (0, dst_backup
), quoteaf_n (1, dst_name
));
2901 static bool _GL_ATTRIBUTE_PURE
2902 valid_options (const struct cp_options
*co
)
2904 assert (co
!= NULL
);
2905 assert (VALID_BACKUP_TYPE (co
->backup_type
));
2906 assert (VALID_SPARSE_MODE (co
->sparse_mode
));
2907 assert (VALID_REFLINK_MODE (co
->reflink_mode
));
2908 assert (!(co
->hard_link
&& co
->symbolic_link
));
2910 (co
->reflink_mode
== REFLINK_ALWAYS
2911 && co
->sparse_mode
!= SPARSE_AUTO
));
2915 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
2916 any type. NONEXISTENT_DST should be true if the file DST_NAME
2917 is known not to exist (e.g., because its parent directory was just
2918 created); NONEXISTENT_DST should be false if DST_NAME might already
2919 exist. OPTIONS is ... FIXME-describe
2920 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
2921 same as) DST_NAME; otherwise, set clear it.
2922 Return true if successful. */
2925 copy (char const *src_name
, char const *dst_name
,
2926 bool nonexistent_dst
, const struct cp_options
*options
,
2927 bool *copy_into_self
, bool *rename_succeeded
)
2929 assert (valid_options (options
));
2931 /* Record the file names: they're used in case of error, when copying
2932 a directory into itself. I don't like to make these tools do *any*
2933 extra work in the common case when that work is solely to handle
2934 exceptional cases, but in this case, I don't see a way to derive the
2935 top level source and destination directory names where they're used.
2936 An alternative is to use COPY_INTO_SELF and print the diagnostic
2937 from every caller -- but I don't want to do that. */
2938 top_level_src_name
= src_name
;
2939 top_level_dst_name
= dst_name
;
2941 bool first_dir_created_per_command_line_arg
= false;
2942 return copy_internal (src_name
, dst_name
, nonexistent_dst
, NULL
, NULL
,
2944 &first_dir_created_per_command_line_arg
,
2945 copy_into_self
, rename_succeeded
);
2948 /* Set *X to the default options for a value of type struct cp_options. */
2951 cp_options_default (struct cp_options
*x
)
2953 memset (x
, 0, sizeof *x
);
2954 #ifdef PRIV_FILE_CHOWN
2956 priv_set_t
*pset
= priv_allocset ();
2959 if (getppriv (PRIV_EFFECTIVE
, pset
) == 0)
2961 x
->chown_privileges
= priv_ismember (pset
, PRIV_FILE_CHOWN
);
2962 x
->owner_privileges
= priv_ismember (pset
, PRIV_FILE_OWNER
);
2964 priv_freeset (pset
);
2967 x
->chown_privileges
= x
->owner_privileges
= (geteuid () == ROOT_UID
);
2971 /* Return true if it's OK for chown to fail, where errno is
2972 the error number that chown failed with and X is the copying
2976 chown_failure_ok (struct cp_options
const *x
)
2978 /* If non-root uses -p, it's ok if we can't preserve ownership.
2979 But root probably wants to know, e.g. if NFS disallows it,
2980 or if the target system doesn't support file ownership. */
2982 return ((errno
== EPERM
|| errno
== EINVAL
) && !x
->chown_privileges
);
2985 /* Similarly, return true if it's OK for chmod and similar operations
2986 to fail, where errno is the error number that chmod failed with and
2987 X is the copying option set. */
2990 owner_failure_ok (struct cp_options
const *x
)
2992 return ((errno
== EPERM
|| errno
== EINVAL
) && !x
->owner_privileges
);
2995 /* Return the user's umask, caching the result.
2997 FIXME: If the destination's parent directory has has a default ACL,
2998 some operating systems (e.g., GNU/Linux's "POSIX" ACLs) use that
2999 ACL's mask rather than the process umask. Currently, the callers
3000 of cached_umask incorrectly assume that this situation cannot occur. */
3004 static mode_t mask
= (mode_t
) -1;
3005 if (mask
== (mode_t
) -1)