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"
47 #include "filenamecat.h"
48 #include "full-write.h"
50 #include "hash-triple.h"
51 #include "ignore-value.h"
52 #include "ioblksize.h"
57 #include "stat-size.h"
58 #include "stat-time.h"
61 #include "write-any-file.h"
62 #include "areadlink.h"
67 # include <attr/error_context.h>
68 # include <attr/libattr.h>
73 #if HAVE_LINUX_FALLOC_H
74 # include <linux/falloc.h>
78 # define HAVE_FCHOWN false
79 # define fchown(fd, uid, gid) (-1)
83 # define HAVE_LCHOWN false
84 # define lchown(name, uid, gid) chown (name, uid, gid)
89 rpl_mkfifo (char const *file
, mode_t mode
)
94 # define mkfifo rpl_mkfifo
101 #define SAME_OWNER(A, B) ((A).st_uid == (B).st_uid)
102 #define SAME_GROUP(A, B) ((A).st_gid == (B).st_gid)
103 #define SAME_OWNER_AND_GROUP(A, B) (SAME_OWNER (A, B) && SAME_GROUP (A, B))
105 /* LINK_FOLLOWS_SYMLINKS is tri-state; if it is -1, we don't know
106 how link() behaves, so assume we can't hardlink symlinks in that case. */
107 #if (defined HAVE_LINKAT && ! LINKAT_SYMLINK_NOTSUP) || ! LINK_FOLLOWS_SYMLINKS
108 # define CAN_HARDLINK_SYMLINKS 1
110 # define CAN_HARDLINK_SYMLINKS 0
115 struct dir_list
*parent
;
120 /* Initial size of the cp.dest_info hash table. */
121 #define DEST_INFO_INITIAL_CAPACITY 61
123 static bool copy_internal (char const *src_name
, char const *dst_name
,
124 bool new_dst
, struct stat
const *parent
,
125 struct dir_list
*ancestors
,
126 const struct cp_options
*x
,
127 bool command_line_arg
,
128 bool *first_dir_created_per_command_line_arg
,
129 bool *copy_into_self
,
130 bool *rename_succeeded
);
131 static bool owner_failure_ok (struct cp_options
const *x
);
133 /* Pointers to the file names: they're used in the diagnostic that is issued
134 when we detect the user is trying to copy a directory into itself. */
135 static char const *top_level_src_name
;
136 static char const *top_level_dst_name
;
138 /* Set the timestamp of symlink, FILE, to TIMESPEC.
139 If this system lacks support for that, simply return 0. */
141 utimens_symlink (char const *file
, struct timespec
const *timespec
)
143 int err
= lutimens (file
, timespec
);
144 /* When configuring on a system with new headers and libraries, and
145 running on one with a kernel that is old enough to lack the syscall,
146 utimensat fails with ENOSYS. Ignore that. */
147 if (err
&& errno
== ENOSYS
)
152 /* Attempt to punch a hole to avoid any permanent
153 speculative preallocation on file systems such as XFS.
154 Return values as per fallocate(2) except ENOSYS etc. are ignored. */
157 punch_hole (int fd
, off_t offset
, off_t length
)
161 # if defined FALLOC_FL_PUNCH_HOLE && defined FALLOC_FL_KEEP_SIZE
162 ret
= fallocate (fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
164 if (ret
< 0 && (is_ENOTSUP (errno
) || errno
== ENOSYS
))
171 /* Create a hole at the end of a file,
172 avoiding preallocation if requested. */
175 create_hole (int fd
, char const *name
, bool punch_holes
, off_t size
)
177 off_t file_end
= lseek (fd
, size
, SEEK_CUR
);
181 error (0, errno
, _("cannot lseek %s"), quoteaf (name
));
185 /* Some file systems (like XFS) preallocate when write extending a file.
186 I.e., a previous write() may have preallocated extra space
187 that the seek above will not discard. A subsequent write() could
188 then make this allocation permanent. */
189 if (punch_holes
&& punch_hole (fd
, file_end
- size
, size
) < 0)
191 error (0, errno
, _("error deallocating %s"), quoteaf (name
));
199 /* Copy the regular file open on SRC_FD/SRC_NAME to DST_FD/DST_NAME,
200 honoring the MAKE_HOLES setting and using the BUF_SIZE-byte buffer
201 BUF for temporary storage. Copy no more than MAX_N_READ bytes.
202 Return true upon successful completion;
203 print a diagnostic and return false upon error.
204 Note that for best results, BUF should be "well"-aligned.
205 BUF must have sizeof(uintptr_t)-1 bytes of additional space
206 beyond BUF[BUF_SIZE-1].
207 Set *LAST_WRITE_MADE_HOLE to true if the final operation on
208 DEST_FD introduced a hole. Set *TOTAL_N_READ to the number of
211 sparse_copy (int src_fd
, int dest_fd
, char *buf
, size_t buf_size
,
212 size_t hole_size
, bool punch_holes
,
213 char const *src_name
, char const *dst_name
,
214 uintmax_t max_n_read
, off_t
*total_n_read
,
215 bool *last_write_made_hole
)
217 *last_write_made_hole
= false;
219 bool make_hole
= false;
224 ssize_t n_read
= read (src_fd
, buf
, MIN (max_n_read
, buf_size
));
229 error (0, errno
, _("error reading %s"), quoteaf (src_name
));
234 max_n_read
-= n_read
;
235 *total_n_read
+= n_read
;
237 /* Loop over the input buffer in chunks of hole_size. */
238 size_t csize
= hole_size
? hole_size
: buf_size
;
244 bool prev_hole
= make_hole
;
245 csize
= MIN (csize
, n_read
);
247 if (hole_size
&& csize
)
248 make_hole
= is_nul (cbuf
, csize
);
250 bool transition
= (make_hole
!= prev_hole
) && psize
;
251 bool last_chunk
= (n_read
== csize
&& ! make_hole
) || ! csize
;
253 if (transition
|| last_chunk
)
260 if (full_write (dest_fd
, pbuf
, psize
) != psize
)
262 error (0, errno
, _("error writing %s"),
269 if (! create_hole (dest_fd
, dst_name
, punch_holes
, psize
))
279 n_read
= 0; /* Finished processing buffer. */
282 csize
= 0; /* Loop again to deal with last chunk. */
284 psize
= 0; /* Reset for next read loop. */
287 else /* Coalesce writes/seeks. */
289 if (psize
<= OFF_T_MAX
- csize
)
293 error (0, 0, _("overflow reading %s"), quoteaf (src_name
));
302 *last_write_made_hole
= make_hole
;
304 /* It's tempting to break early here upon a short read from
305 a regular file. That would save the final read syscall
306 for each file. Unfortunately that doesn't work for
307 certain files in /proc or /sys with linux kernels. */
310 /* Ensure a trailing hole is created, so that subsequent
311 calls of sparse_copy() start at the correct offset. */
312 if (make_hole
&& ! create_hole (dest_fd
, dst_name
, punch_holes
, psize
))
318 /* Perform the O(1) btrfs clone operation, if possible.
319 Upon success, return 0. Otherwise, return -1 and set errno. */
321 clone_file (int dest_fd
, int src_fd
)
324 # undef BTRFS_IOCTL_MAGIC
325 # define BTRFS_IOCTL_MAGIC 0x94
326 # undef BTRFS_IOC_CLONE
327 # define BTRFS_IOC_CLONE _IOW (BTRFS_IOCTL_MAGIC, 9, int)
328 return ioctl (dest_fd
, BTRFS_IOC_CLONE
, src_fd
);
337 /* Write N_BYTES zero bytes to file descriptor FD. Return true if successful.
338 Upon write failure, set errno and return false. */
340 write_zeros (int fd
, off_t n_bytes
)
343 static size_t nz
= IO_BUFSIZE
;
345 /* Attempt to use a relatively large calloc'd source buffer for
346 efficiency, but if that allocation fails, resort to a smaller
347 statically allocated one. */
350 static char fallback
[1024];
351 zeros
= calloc (nz
, 1);
355 nz
= sizeof fallback
;
361 size_t n
= MIN (nz
, n_bytes
);
362 if ((full_write (fd
, zeros
, n
)) != n
)
370 /* Perform an efficient extent copy, if possible. This avoids
371 the overhead of detecting holes in hole-introducing/preserving
372 copy, and thus makes copying sparse files much more efficient.
373 Upon a successful copy, return true. If the initial extent scan
374 fails, set *NORMAL_COPY_REQUIRED to true and return false.
375 Upon any other failure, set *NORMAL_COPY_REQUIRED to false and
378 extent_copy (int src_fd
, int dest_fd
, char *buf
, size_t buf_size
,
379 size_t hole_size
, off_t src_total_size
,
380 enum Sparse_type sparse_mode
,
381 char const *src_name
, char const *dst_name
,
382 bool *require_normal_copy
)
384 struct extent_scan scan
;
385 off_t last_ext_start
= 0;
386 off_t last_ext_len
= 0;
388 /* Keep track of the output position.
389 We may need this at the end, for a final ftruncate. */
392 extent_scan_init (src_fd
, &scan
);
394 *require_normal_copy
= false;
395 bool wrote_hole_at_eof
= true;
398 bool ok
= extent_scan_read (&scan
);
401 if (scan
.hit_final_extent
)
404 if (scan
.initial_scan_failed
)
406 *require_normal_copy
= true;
410 error (0, errno
, _("%s: failed to get extents info"),
416 bool empty_extent
= false;
417 for (i
= 0; i
< scan
.ei_count
|| empty_extent
; i
++)
423 if (i
< scan
.ei_count
)
425 ext_start
= scan
.ext_info
[i
].ext_logical
;
426 ext_len
= scan
.ext_info
[i
].ext_length
;
428 else /* empty extent at EOF. */
431 ext_start
= last_ext_start
+ scan
.ext_info
[i
].ext_length
;
435 /* Truncate extent to EOF. Extents starting after EOF are
436 treated as zero length extents starting right after EOF.
437 Generally this will trigger with an extent starting after
438 src_total_size, and result in creating a hole or zeros until EOF.
439 Though in a file in which extents have changed since src_total_size
440 was determined, we might have an extent spanning that size,
441 in which case we'll only copy data up to that size. */
442 if (src_total_size
< ext_start
+ ext_len
)
444 if (src_total_size
< ext_start
)
445 ext_start
= src_total_size
;
446 ext_len
= src_total_size
- ext_start
;
449 ext_hole_size
= ext_start
- last_ext_start
- last_ext_len
;
451 wrote_hole_at_eof
= false;
455 if (lseek (src_fd
, ext_start
, SEEK_SET
) < 0)
457 error (0, errno
, _("cannot lseek %s"), quoteaf (src_name
));
459 extent_scan_free (&scan
);
463 if ((empty_extent
&& sparse_mode
== SPARSE_ALWAYS
)
464 || (!empty_extent
&& sparse_mode
!= SPARSE_NEVER
))
466 if (! create_hole (dest_fd
, dst_name
,
467 sparse_mode
== SPARSE_ALWAYS
,
470 wrote_hole_at_eof
= true;
474 /* When not inducing holes and when there is a hole between
475 the end of the previous extent and the beginning of the
476 current one, write zeros to the destination file. */
477 off_t nzeros
= ext_hole_size
;
479 nzeros
= MIN (src_total_size
- dest_pos
, ext_hole_size
);
481 if (! write_zeros (dest_fd
, nzeros
))
483 error (0, errno
, _("%s: write failed"),
488 dest_pos
= MIN (src_total_size
, ext_start
);
492 last_ext_start
= ext_start
;
494 /* Treat an unwritten but allocated extent much like a hole.
495 I.e., don't read, but don't convert to a hole in the destination,
496 unless SPARSE_ALWAYS. */
497 /* For now, do not treat FIEMAP_EXTENT_UNWRITTEN specially,
498 because that (in combination with no sync) would lead to data
499 loss at least on XFS and ext4 when using 2.6.39-rc3 kernels. */
500 if (0 && (scan
.ext_info
[i
].ext_flags
& FIEMAP_EXTENT_UNWRITTEN
))
504 if (ext_len
== 0) /* The last extent is empty and processed. */
505 empty_extent
= false;
510 empty_extent
= false;
511 last_ext_len
= ext_len
;
514 if ( ! sparse_copy (src_fd
, dest_fd
, buf
, buf_size
,
515 sparse_mode
== SPARSE_ALWAYS
? hole_size
: 0,
516 true, src_name
, dst_name
, ext_len
, &n_read
,
520 dest_pos
= ext_start
+ n_read
;
522 wrote_hole_at_eof
= read_hole
;
525 /* If the file ends with unwritten extents not accounted for in the
526 size, then skip processing them, and the associated redundant
527 read() calls which will always return 0. We will need to
528 remove this when we add fallocate() so that we can maintain
529 extents beyond the apparent size. */
530 if (dest_pos
== src_total_size
)
532 scan
.hit_final_extent
= true;
537 /* Release the space allocated to scan->ext_info. */
538 extent_scan_free (&scan
);
541 while (! scan
.hit_final_extent
);
543 /* When the source file ends with a hole, we have to do a little more work,
544 since the above copied only up to and including the final extent.
545 In order to complete the copy, we may have to insert a hole or write
546 zeros in the destination corresponding to the source file's hole-at-EOF.
548 In addition, if the final extent was a block of zeros at EOF and we've
549 just converted them to a hole in the destination, we must call ftruncate
550 here in order to record the proper length in the destination. */
551 if ((dest_pos
< src_total_size
|| wrote_hole_at_eof
)
552 && (sparse_mode
!= SPARSE_NEVER
553 ? ftruncate (dest_fd
, src_total_size
)
554 : ! write_zeros (dest_fd
, src_total_size
- dest_pos
)))
556 error (0, errno
, _("failed to extend %s"), quoteaf (dst_name
));
560 if (sparse_mode
== SPARSE_ALWAYS
&& dest_pos
< src_total_size
561 && punch_hole (dest_fd
, dest_pos
, src_total_size
- dest_pos
) < 0)
563 error (0, errno
, _("error deallocating %s"), quoteaf (dst_name
));
570 /* FIXME: describe */
571 /* FIXME: rewrite this to use a hash table so we avoid the quadratic
572 performance hit that's probably noticeable only on trees deeper
573 than a few hundred levels. See use of active_dir_map in remove.c */
575 static bool _GL_ATTRIBUTE_PURE
576 is_ancestor (const struct stat
*sb
, const struct dir_list
*ancestors
)
578 while (ancestors
!= 0)
580 if (ancestors
->ino
== sb
->st_ino
&& ancestors
->dev
== sb
->st_dev
)
582 ancestors
= ancestors
->parent
;
588 errno_unsupported (int err
)
590 return err
== ENOTSUP
|| err
== ENODATA
;
595 copy_attr_error (struct error_context
*ctx _GL_UNUSED
,
596 char const *fmt
, ...)
598 if (!errno_unsupported (errno
))
603 /* use verror module to print error message */
605 verror (0, err
, fmt
, ap
);
611 copy_attr_allerror (struct error_context
*ctx _GL_UNUSED
,
612 char const *fmt
, ...)
617 /* use verror module to print error message */
619 verror (0, err
, fmt
, ap
);
624 copy_attr_quote (struct error_context
*ctx _GL_UNUSED
, char const *str
)
626 return quoteaf (str
);
630 copy_attr_free (struct error_context
*ctx _GL_UNUSED
,
631 char const *str _GL_UNUSED
)
635 /* Exclude SELinux extended attributes that are otherwise handled,
636 and are problematic to copy again. Also honor attributes
637 configured for exclusion in /etc/xattr.conf.
638 FIXME: Should we handle POSIX ACLs similarly?
639 Return zero to skip. */
641 check_selinux_attr (const char *name
, struct error_context
*ctx
)
643 return STRNCMP_LIT (name
, "security.selinux")
644 && attr_copy_check_permissions (name
, ctx
);
647 /* If positive SRC_FD and DST_FD descriptors are passed,
648 then copy by fd, otherwise copy by name. */
651 copy_attr (char const *src_path
, int src_fd
,
652 char const *dst_path
, int dst_fd
, struct cp_options
const *x
)
655 bool all_errors
= (!x
->data_copy_required
|| x
->require_preserve_xattr
);
656 bool some_errors
= (!all_errors
&& !x
->reduce_diagnostics
);
657 bool selinux_done
= (x
->preserve_security_context
|| x
->set_security_context
);
658 struct error_context ctx
=
660 .error
= all_errors
? copy_attr_allerror
: copy_attr_error
,
661 .quote
= copy_attr_quote
,
662 .quote_free
= copy_attr_free
664 if (0 <= src_fd
&& 0 <= dst_fd
)
665 ret
= attr_copy_fd (src_path
, src_fd
, dst_path
, dst_fd
,
666 selinux_done
? check_selinux_attr
: NULL
,
667 (all_errors
|| some_errors
? &ctx
: NULL
));
669 ret
= attr_copy_file (src_path
, dst_path
,
670 selinux_done
? check_selinux_attr
: NULL
,
671 (all_errors
|| some_errors
? &ctx
: NULL
));
675 #else /* USE_XATTR */
678 copy_attr (char const *src_path _GL_UNUSED
,
679 int src_fd _GL_UNUSED
,
680 char const *dst_path _GL_UNUSED
,
681 int dst_fd _GL_UNUSED
,
682 struct cp_options
const *x _GL_UNUSED
)
686 #endif /* USE_XATTR */
688 /* Read the contents of the directory SRC_NAME_IN, and recursively
689 copy the contents to DST_NAME_IN. NEW_DST is true if
690 DST_NAME_IN is a directory that was created previously in the
691 recursion. SRC_SB and ANCESTORS describe SRC_NAME_IN.
692 Set *COPY_INTO_SELF if SRC_NAME_IN is a parent of
693 (or the same as) DST_NAME_IN; otherwise, clear it.
694 Propagate *FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG from
695 caller to each invocation of copy_internal. Be careful to
696 pass the address of a temporary, and to update
697 *FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG only upon completion.
698 Return true if successful. */
701 copy_dir (char const *src_name_in
, char const *dst_name_in
, bool new_dst
,
702 const struct stat
*src_sb
, struct dir_list
*ancestors
,
703 const struct cp_options
*x
,
704 bool *first_dir_created_per_command_line_arg
,
705 bool *copy_into_self
)
709 struct cp_options non_command_line_options
= *x
;
712 name_space
= savedir (src_name_in
, SAVEDIR_SORT_FASTREAD
);
713 if (name_space
== NULL
)
715 /* This diagnostic is a bit vague because savedir can fail in
716 several different ways. */
717 error (0, errno
, _("cannot access %s"), quoteaf (src_name_in
));
721 /* For cp's -H option, dereference command line arguments, but do not
722 dereference symlinks that are found via recursive traversal. */
723 if (x
->dereference
== DEREF_COMMAND_LINE_ARGUMENTS
)
724 non_command_line_options
.dereference
= DEREF_NEVER
;
726 bool new_first_dir_created
= false;
728 while (*namep
!= '\0')
730 bool local_copy_into_self
;
731 char *src_name
= file_name_concat (src_name_in
, namep
, NULL
);
732 char *dst_name
= file_name_concat (dst_name_in
, namep
, NULL
);
733 bool first_dir_created
= *first_dir_created_per_command_line_arg
;
735 ok
&= copy_internal (src_name
, dst_name
, new_dst
, src_sb
,
736 ancestors
, &non_command_line_options
, false,
738 &local_copy_into_self
, NULL
);
739 *copy_into_self
|= local_copy_into_self
;
744 /* If we're copying into self, there's no point in continuing,
745 and in fact, that would even infloop, now that we record only
746 the first created directory per command line argument. */
747 if (local_copy_into_self
)
750 new_first_dir_created
|= first_dir_created
;
751 namep
+= strlen (namep
) + 1;
754 *first_dir_created_per_command_line_arg
= new_first_dir_created
;
759 /* Set the owner and owning group of DEST_DESC to the st_uid and
760 st_gid fields of SRC_SB. If DEST_DESC is undefined (-1), set
761 the owner and owning group of DST_NAME instead; for
762 safety prefer lchown if the system supports it since no
763 symbolic links should be involved. DEST_DESC must
764 refer to the same file as DEST_NAME if defined.
765 Upon failure to set both UID and GID, try to set only the GID.
766 NEW_DST is true if the file was newly created; otherwise,
767 DST_SB is the status of the destination.
768 Return 1 if the initial syscall succeeds, 0 if it fails but it's OK
769 not to preserve ownership, -1 otherwise. */
772 set_owner (const struct cp_options
*x
, char const *dst_name
, int dest_desc
,
773 struct stat
const *src_sb
, bool new_dst
,
774 struct stat
const *dst_sb
)
776 uid_t uid
= src_sb
->st_uid
;
777 gid_t gid
= src_sb
->st_gid
;
779 /* Naively changing the ownership of an already-existing file before
780 changing its permissions would create a window of vulnerability if
781 the file's old permissions are too generous for the new owner and
782 group. Avoid the window by first changing to a restrictive
783 temporary mode if necessary. */
785 if (!new_dst
&& (x
->preserve_mode
|| x
->move_mode
|| x
->set_mode
))
787 mode_t old_mode
= dst_sb
->st_mode
;
789 (x
->preserve_mode
|| x
->move_mode
? src_sb
->st_mode
: x
->mode
);
790 mode_t restrictive_temp_mode
= old_mode
& new_mode
& S_IRWXU
;
793 || (old_mode
& CHMOD_MODE_BITS
794 & (~new_mode
| S_ISUID
| S_ISGID
| S_ISVTX
)))
795 && qset_acl (dst_name
, dest_desc
, restrictive_temp_mode
) != 0)
797 if (! owner_failure_ok (x
))
798 error (0, errno
, _("clearing permissions for %s"),
800 return -x
->require_preserve
;
804 if (HAVE_FCHOWN
&& dest_desc
!= -1)
806 if (fchown (dest_desc
, uid
, gid
) == 0)
808 if (errno
== EPERM
|| errno
== EINVAL
)
810 /* We've failed to set *both*. Now, try to set just the group
811 ID, but ignore any failure here, and don't change errno. */
812 int saved_errno
= errno
;
813 ignore_value (fchown (dest_desc
, -1, gid
));
819 if (lchown (dst_name
, uid
, gid
) == 0)
821 if (errno
== EPERM
|| errno
== EINVAL
)
823 /* We've failed to set *both*. Now, try to set just the group
824 ID, but ignore any failure here, and don't change errno. */
825 int saved_errno
= errno
;
826 ignore_value (lchown (dst_name
, -1, gid
));
831 if (! chown_failure_ok (x
))
833 error (0, errno
, _("failed to preserve ownership for %s"),
835 if (x
->require_preserve
)
842 /* Set the st_author field of DEST_DESC to the st_author field of
843 SRC_SB. If DEST_DESC is undefined (-1), set the st_author field
844 of DST_NAME instead. DEST_DESC must refer to the same file as
845 DEST_NAME if defined. */
848 set_author (const char *dst_name
, int dest_desc
, const struct stat
*src_sb
)
850 #if HAVE_STRUCT_STAT_ST_AUTHOR
851 /* FIXME: Modify the following code so that it does not
852 follow symbolic links. */
854 /* Preserve the st_author field. */
855 file_t file
= (dest_desc
< 0
856 ? file_name_lookup (dst_name
, 0, 0)
857 : getdport (dest_desc
));
858 if (file
== MACH_PORT_NULL
)
859 error (0, errno
, _("failed to lookup file %s"), quoteaf (dst_name
));
862 error_t err
= file_chauthor (file
, src_sb
->st_author
);
864 error (0, err
, _("failed to preserve authorship for %s"),
866 mach_port_deallocate (mach_task_self (), file
);
875 /* Set the default security context for the process. New files will
876 have this security context set. Also existing files can have their
877 context adjusted based on this process context, by
878 set_file_security_ctx() called with PROCESS_LOCAL=true.
879 This should be called before files are created so there is no race
880 where a file may be present without an appropriate security context.
881 Based on CP_OPTIONS, diagnose warnings and fail when appropriate.
882 Return FALSE on failure, TRUE on success. */
885 set_process_security_ctx (char const *src_name
, char const *dst_name
,
886 mode_t mode
, bool new_dst
, const struct cp_options
*x
)
888 if (x
->preserve_security_context
)
890 /* Set the default context for the process to match the source. */
891 bool all_errors
= !x
->data_copy_required
|| x
->require_preserve_context
;
892 bool some_errors
= !all_errors
&& !x
->reduce_diagnostics
;
895 if (0 <= lgetfilecon (src_name
, &con
))
897 if (setfscreatecon (con
) < 0)
899 if (all_errors
|| (some_errors
&& !errno_unsupported (errno
)))
901 _("failed to set default file creation context to %s"),
903 if (x
->require_preserve_context
)
913 if (all_errors
|| (some_errors
&& !errno_unsupported (errno
)))
916 _("failed to get security context of %s"),
919 if (x
->require_preserve_context
)
923 else if (x
->set_security_context
)
925 /* With -Z, adjust the default context for the process
926 to have the type component adjusted as per the destination path. */
927 if (new_dst
&& defaultcon (dst_name
, mode
) < 0
928 && ! ignorable_ctx_err (errno
))
931 _("failed to set default file creation context for %s"),
939 /* Reset the security context of DST_NAME, to that already set
940 as the process default if PROCESS_LOCAL is true. Otherwise
941 adjust the type component of DST_NAME's security context as
942 per the system default for that path. Issue warnings upon
943 failure, when allowed by various settings in CP_OPTIONS.
944 Return FALSE on failure, TRUE on success. */
947 set_file_security_ctx (char const *dst_name
, bool process_local
,
948 bool recurse
, const struct cp_options
*x
)
950 bool all_errors
= (!x
->data_copy_required
951 || x
->require_preserve_context
);
952 bool some_errors
= !all_errors
&& !x
->reduce_diagnostics
;
954 if (! restorecon (dst_name
, recurse
, process_local
))
956 if (all_errors
|| (some_errors
&& !errno_unsupported (errno
)))
957 error (0, errno
, _("failed to set the security context of %s"),
958 quoteaf_n (0, dst_name
));
965 /* Change the file mode bits of the file identified by DESC or NAME to MODE.
966 Use DESC if DESC is valid and fchmod is available, NAME otherwise. */
969 fchmod_or_lchmod (int desc
, char const *name
, mode_t mode
)
973 return fchmod (desc
, mode
);
975 return lchmod (name
, mode
);
978 #ifndef HAVE_STRUCT_STAT_ST_BLOCKS
979 # define HAVE_STRUCT_STAT_ST_BLOCKS 0
982 /* Use a heuristic to determine whether stat buffer SB comes from a file
983 with sparse blocks. If the file has fewer blocks than would normally
984 be needed for a file of its size, then at least one of the blocks in
985 the file is a hole. In that case, return true. */
987 is_probably_sparse (struct stat
const *sb
)
989 return (HAVE_STRUCT_STAT_ST_BLOCKS
990 && S_ISREG (sb
->st_mode
)
991 && ST_NBLOCKS (*sb
) < sb
->st_size
/ ST_NBLOCKSIZE
);
995 /* Copy a regular file from SRC_NAME to DST_NAME.
996 If the source file contains holes, copies holes and blocks of zeros
997 in the source file as holes in the destination file.
998 (Holes are read as zeroes by the 'read' system call.)
999 When creating the destination, use DST_MODE & ~OMITTED_PERMISSIONS
1000 as the third argument in the call to open, adding
1001 OMITTED_PERMISSIONS after copying as needed.
1002 X provides many option settings.
1003 Return true if successful.
1004 *NEW_DST is as in copy_internal.
1005 SRC_SB is the result of calling XSTAT (aka stat) on SRC_NAME. */
1008 copy_reg (char const *src_name
, char const *dst_name
,
1009 const struct cp_options
*x
,
1010 mode_t dst_mode
, mode_t omitted_permissions
, bool *new_dst
,
1011 struct stat
const *src_sb
)
1014 char *buf_alloc
= NULL
;
1015 char *name_alloc
= NULL
;
1019 mode_t src_mode
= src_sb
->st_mode
;
1021 struct stat src_open_sb
;
1022 bool return_val
= true;
1023 bool data_copy_required
= x
->data_copy_required
;
1025 source_desc
= open (src_name
,
1026 (O_RDONLY
| O_BINARY
1027 | (x
->dereference
== DEREF_NEVER
? O_NOFOLLOW
: 0)));
1028 if (source_desc
< 0)
1030 error (0, errno
, _("cannot open %s for reading"), quoteaf (src_name
));
1034 if (fstat (source_desc
, &src_open_sb
) != 0)
1036 error (0, errno
, _("cannot fstat %s"), quoteaf (src_name
));
1038 goto close_src_desc
;
1041 /* Compare the source dev/ino from the open file to the incoming,
1042 saved ones obtained via a previous call to stat. */
1043 if (! SAME_INODE (*src_sb
, src_open_sb
))
1046 _("skipping file %s, as it was replaced while being copied"),
1047 quoteaf (src_name
));
1049 goto close_src_desc
;
1052 /* The semantics of the following open calls are mandated
1053 by the specs for both cp and mv. */
1057 O_WRONLY
| O_BINARY
| (x
->data_copy_required
? O_TRUNC
: 0);
1058 dest_desc
= open (dst_name
, open_flags
);
1061 /* When using cp --preserve=context to copy to an existing destination,
1062 reset the context as per the default context, which has already been
1063 set according to the src.
1064 When using the mutually exclusive -Z option, then adjust the type of
1065 the existing context according to the system default for the dest.
1066 Note we set the context here, _after_ the file is opened, lest the
1067 new context disallow that. */
1068 if ((x
->set_security_context
|| x
->preserve_security_context
)
1071 if (! set_file_security_ctx (dst_name
, x
->preserve_security_context
,
1074 if (x
->require_preserve_context
)
1077 goto close_src_and_dst_desc
;
1082 if (dest_desc
< 0 && x
->unlink_dest_after_failed_open
)
1084 if (unlink (dst_name
) != 0)
1086 error (0, errno
, _("cannot remove %s"), quoteaf (dst_name
));
1088 goto close_src_desc
;
1091 printf (_("removed %s\n"), quoteaf (dst_name
));
1093 /* Tell caller that the destination file was unlinked. */
1096 /* Ensure there is no race where a file may be left without
1097 an appropriate security context. */
1098 if (x
->set_security_context
)
1100 if (! set_process_security_ctx (src_name
, dst_name
, dst_mode
,
1104 goto close_src_desc
;
1114 int open_flags
= O_WRONLY
| O_CREAT
| O_BINARY
;
1115 dest_desc
= open (dst_name
, open_flags
| O_EXCL
,
1116 dst_mode
& ~omitted_permissions
);
1119 /* When trying to copy through a dangling destination symlink,
1120 the above open fails with EEXIST. If that happens, and
1121 lstat'ing the DST_NAME shows that it is a symlink, then we
1122 have a problem: trying to resolve this dangling symlink to
1123 a directory/destination-entry pair is fundamentally racy,
1124 so punt. If x->open_dangling_dest_symlink is set (cp sets
1125 that when POSIXLY_CORRECT is set in the environment), simply
1126 call open again, but without O_EXCL (potentially dangerous).
1127 If not, fail with a diagnostic. These shenanigans are necessary
1128 only when copying, i.e., not in move_mode. */
1129 if (dest_desc
< 0 && dest_errno
== EEXIST
&& ! x
->move_mode
)
1131 struct stat dangling_link_sb
;
1132 if (lstat (dst_name
, &dangling_link_sb
) == 0
1133 && S_ISLNK (dangling_link_sb
.st_mode
))
1135 if (x
->open_dangling_dest_symlink
)
1137 dest_desc
= open (dst_name
, open_flags
,
1138 dst_mode
& ~omitted_permissions
);
1143 error (0, 0, _("not writing through dangling symlink %s"),
1144 quoteaf (dst_name
));
1146 goto close_src_desc
;
1151 /* Improve quality of diagnostic when a nonexistent dst_name
1152 ends in a slash and open fails with errno == EISDIR. */
1153 if (dest_desc
< 0 && dest_errno
== EISDIR
1154 && *dst_name
&& dst_name
[strlen (dst_name
) - 1] == '/')
1155 dest_errno
= ENOTDIR
;
1159 omitted_permissions
= 0;
1164 /* If we've just failed due to ENOENT for an ostensibly preexisting
1165 destination (*new_dst was 0), that's a bit of a contradiction/race:
1166 the prior stat/lstat said the file existed (*new_dst was 0), yet
1167 the subsequent open-existing-file failed with ENOENT. With NFS,
1168 the race window is wider still, since its meta-data caching tends
1169 to make the stat succeed for a just-removed remote file, while the
1170 more-definitive initial open call will fail with ENOENT. When this
1171 situation arises, we attempt to open again, but this time with
1172 O_CREAT. Do this only when not in move-mode, since when handling
1173 a cross-device move, we must never open an existing destination. */
1174 if (dest_errno
== ENOENT
&& ! *new_dst
&& ! x
->move_mode
)
1177 goto open_with_O_CREAT
;
1180 /* Otherwise, it's an error. */
1181 error (0, dest_errno
, _("cannot create regular file %s"),
1182 quoteaf (dst_name
));
1184 goto close_src_desc
;
1187 if (fstat (dest_desc
, &sb
) != 0)
1189 error (0, errno
, _("cannot fstat %s"), quoteaf (dst_name
));
1191 goto close_src_and_dst_desc
;
1194 /* --attributes-only overrides --reflink. */
1195 if (data_copy_required
&& x
->reflink_mode
)
1197 bool clone_ok
= clone_file (dest_desc
, source_desc
) == 0;
1198 if (clone_ok
|| x
->reflink_mode
== REFLINK_ALWAYS
)
1202 error (0, errno
, _("failed to clone %s from %s"),
1203 quoteaf_n (0, dst_name
), quoteaf_n (1, src_name
));
1205 goto close_src_and_dst_desc
;
1207 data_copy_required
= false;
1211 if (data_copy_required
)
1213 /* Choose a suitable buffer size; it may be adjusted later. */
1214 size_t buf_alignment
= getpagesize ();
1215 size_t buf_size
= io_blksize (sb
);
1216 size_t hole_size
= ST_BLKSIZE (sb
);
1218 fdadvise (source_desc
, 0, 0, FADVISE_SEQUENTIAL
);
1220 /* Deal with sparse files. */
1221 bool make_holes
= false;
1222 bool sparse_src
= is_probably_sparse (&src_open_sb
);
1224 if (S_ISREG (sb
.st_mode
))
1226 /* Even with --sparse=always, try to create holes only
1227 if the destination is a regular file. */
1228 if (x
->sparse_mode
== SPARSE_ALWAYS
)
1231 /* Use a heuristic to determine whether SRC_NAME contains any sparse
1232 blocks. If the file has fewer blocks than would normally be
1233 needed for a file of its size, then at least one of the blocks in
1234 the file is a hole. */
1235 if (x
->sparse_mode
== SPARSE_AUTO
&& sparse_src
)
1239 /* If not making a sparse file, try to use a more-efficient
1243 /* Compute the least common multiple of the input and output
1244 buffer sizes, adjusting for outlandish values. */
1245 size_t blcm_max
= MIN (SIZE_MAX
, SSIZE_MAX
) - buf_alignment
;
1246 size_t blcm
= buffer_lcm (io_blksize (src_open_sb
), buf_size
,
1249 /* Do not bother with a buffer larger than the input file, plus one
1250 byte to make sure the file has not grown while reading it. */
1251 if (S_ISREG (src_open_sb
.st_mode
) && src_open_sb
.st_size
< buf_size
)
1252 buf_size
= src_open_sb
.st_size
+ 1;
1254 /* However, stick with a block size that is a positive multiple of
1255 blcm, overriding the above adjustments. Watch out for
1257 buf_size
+= blcm
- 1;
1258 buf_size
-= buf_size
% blcm
;
1259 if (buf_size
== 0 || blcm_max
< buf_size
)
1263 buf_alloc
= xmalloc (buf_size
+ buf_alignment
);
1264 buf
= ptr_align (buf_alloc
, buf_alignment
);
1268 bool normal_copy_required
;
1270 /* Perform an efficient extent-based copy, falling back to the
1271 standard copy only if the initial extent scan fails. If the
1272 '--sparse=never' option is specified, write all data but use
1273 any extents to read more efficiently. */
1274 if (extent_copy (source_desc
, dest_desc
, buf
, buf_size
, hole_size
,
1275 src_open_sb
.st_size
,
1276 make_holes
? x
->sparse_mode
: SPARSE_NEVER
,
1277 src_name
, dst_name
, &normal_copy_required
))
1278 goto preserve_metadata
;
1280 if (! normal_copy_required
)
1283 goto close_src_and_dst_desc
;
1288 bool wrote_hole_at_eof
;
1289 if (! sparse_copy (source_desc
, dest_desc
, buf
, buf_size
,
1290 make_holes
? hole_size
: 0,
1291 x
->sparse_mode
== SPARSE_ALWAYS
, src_name
, dst_name
,
1292 UINTMAX_MAX
, &n_read
,
1293 &wrote_hole_at_eof
))
1296 goto close_src_and_dst_desc
;
1298 else if (wrote_hole_at_eof
&& ftruncate (dest_desc
, n_read
) < 0)
1300 error (0, errno
, _("failed to extend %s"), quoteaf (dst_name
));
1302 goto close_src_and_dst_desc
;
1307 if (x
->preserve_timestamps
)
1309 struct timespec timespec
[2];
1310 timespec
[0] = get_stat_atime (src_sb
);
1311 timespec
[1] = get_stat_mtime (src_sb
);
1313 if (fdutimens (dest_desc
, dst_name
, timespec
) != 0)
1315 error (0, errno
, _("preserving times for %s"), quoteaf (dst_name
));
1316 if (x
->require_preserve
)
1319 goto close_src_and_dst_desc
;
1324 /* Set ownership before xattrs as changing owners will
1325 clear capabilities. */
1326 if (x
->preserve_ownership
&& ! SAME_OWNER_AND_GROUP (*src_sb
, sb
))
1328 switch (set_owner (x
, dst_name
, dest_desc
, src_sb
, *new_dst
, &sb
))
1332 goto close_src_and_dst_desc
;
1335 src_mode
&= ~ (S_ISUID
| S_ISGID
| S_ISVTX
);
1340 /* To allow copying xattrs on read-only files, temporarily chmod u+rw.
1341 This workaround is required as an inode permission check is done
1342 by xattr_permission() in fs/xattr.c of the GNU/Linux kernel tree. */
1343 if (x
->preserve_xattr
)
1345 bool access_changed
= false;
1347 if (!(sb
.st_mode
& S_IWUSR
) && geteuid () != ROOT_UID
)
1348 access_changed
= fchmod_or_lchmod (dest_desc
, dst_name
, 0600) == 0;
1350 if (!copy_attr (src_name
, source_desc
, dst_name
, dest_desc
, x
)
1351 && x
->require_preserve_xattr
)
1355 fchmod_or_lchmod (dest_desc
, dst_name
, dst_mode
& ~omitted_permissions
);
1358 set_author (dst_name
, dest_desc
, src_sb
);
1360 if (x
->preserve_mode
|| x
->move_mode
)
1362 if (copy_acl (src_name
, source_desc
, dst_name
, dest_desc
, src_mode
) != 0
1363 && x
->require_preserve
)
1366 else if (x
->set_mode
)
1368 if (set_acl (dst_name
, dest_desc
, x
->mode
) != 0)
1371 else if (x
->explicit_no_preserve_mode
)
1373 if (set_acl (dst_name
, dest_desc
, 0666 & ~cached_umask ()) != 0)
1376 else if (omitted_permissions
)
1378 omitted_permissions
&= ~ cached_umask ();
1379 if (omitted_permissions
1380 && fchmod_or_lchmod (dest_desc
, dst_name
, dst_mode
) != 0)
1382 error (0, errno
, _("preserving permissions for %s"),
1383 quoteaf (dst_name
));
1384 if (x
->require_preserve
)
1389 close_src_and_dst_desc
:
1390 if (close (dest_desc
) < 0)
1392 error (0, errno
, _("failed to close %s"), quoteaf (dst_name
));
1396 if (close (source_desc
) < 0)
1398 error (0, errno
, _("failed to close %s"), quoteaf (src_name
));
1407 /* Return true if it's ok that the source and destination
1408 files are the 'same' by some measure. The goal is to avoid
1409 making the 'copy' operation remove both copies of the file
1410 in that case, while still allowing the user to e.g., move or
1411 copy a regular file onto a symlink that points to it.
1412 Try to minimize the cost of this function in the common case.
1413 Set *RETURN_NOW if we've determined that the caller has no more
1414 work to do and should return successfully, right away. */
1417 same_file_ok (char const *src_name
, struct stat
const *src_sb
,
1418 char const *dst_name
, struct stat
const *dst_sb
,
1419 const struct cp_options
*x
, bool *return_now
)
1421 const struct stat
*src_sb_link
;
1422 const struct stat
*dst_sb_link
;
1423 struct stat tmp_dst_sb
;
1424 struct stat tmp_src_sb
;
1427 bool same
= SAME_INODE (*src_sb
, *dst_sb
);
1429 *return_now
= false;
1431 /* FIXME: this should (at the very least) be moved into the following
1432 if-block. More likely, it should be removed, because it inhibits
1433 making backups. But removing it will result in a change in behavior
1434 that will probably have to be documented -- and tests will have to
1436 if (same
&& x
->hard_link
)
1442 if (x
->dereference
== DEREF_NEVER
)
1446 /* If both the source and destination files are symlinks (and we'll
1447 know this here IFF preserving symlinks), then it's usually ok
1448 when they are distinct. */
1449 if (S_ISLNK (src_sb
->st_mode
) && S_ISLNK (dst_sb
->st_mode
))
1451 bool sn
= same_name (src_name
, dst_name
);
1454 /* It's fine when we're making any type of backup. */
1455 if (x
->backup_type
!= no_backups
)
1458 /* Here we have two symlinks that are hard-linked together,
1459 and we're not making backups. In this unusual case, simply
1460 returning true would lead to mv calling "rename(A,B)",
1461 which would do nothing and return 0. */
1465 return ! x
->move_mode
;
1472 src_sb_link
= src_sb
;
1473 dst_sb_link
= dst_sb
;
1480 if (lstat (dst_name
, &tmp_dst_sb
) != 0
1481 || lstat (src_name
, &tmp_src_sb
) != 0)
1484 src_sb_link
= &tmp_src_sb
;
1485 dst_sb_link
= &tmp_dst_sb
;
1487 same_link
= SAME_INODE (*src_sb_link
, *dst_sb_link
);
1489 /* If both are symlinks, then it's ok, but only if the destination
1490 will be unlinked before being opened. This is like the test
1491 above, but with the addition of the unlink_dest_before_opening
1492 conjunct because otherwise, with two symlinks to the same target,
1493 we'd end up truncating the source file. */
1494 if (S_ISLNK (src_sb_link
->st_mode
) && S_ISLNK (dst_sb_link
->st_mode
)
1495 && x
->unlink_dest_before_opening
)
1499 /* The backup code ensures there's a copy, so it's usually ok to
1500 remove any destination file. One exception is when both
1501 source and destination are the same directory entry. In that
1502 case, moving the destination file aside (in making the backup)
1503 would also rename the source file and result in an error. */
1504 if (x
->backup_type
!= no_backups
)
1508 /* In copy mode when dereferencing symlinks, if the source is a
1509 symlink and the dest is not, then backing up the destination
1510 (moving it aside) would make it a dangling symlink, and the
1511 subsequent attempt to open it in copy_reg would fail with
1512 a misleading diagnostic. Avoid that by returning zero in
1513 that case so the caller can make cp (or mv when it has to
1514 resort to reading the source file) fail now. */
1516 /* FIXME-note: even with the following kludge, we can still provoke
1517 the offending diagnostic. It's just a little harder to do :-)
1518 $ rm -f a b c; touch c; ln -s c b; ln -s b a; cp -b a b
1519 cp: cannot open 'a' for reading: No such file or directory
1520 That's misleading, since a subsequent 'ls' shows that 'a'
1522 One solution would be to open the source file *before* moving
1523 aside the destination, but that'd involve a big rewrite. */
1525 && x
->dereference
!= DEREF_NEVER
1526 && S_ISLNK (src_sb_link
->st_mode
)
1527 && ! S_ISLNK (dst_sb_link
->st_mode
))
1533 /* FIXME: What about case insensitive file systems ? */
1534 return ! same_name (src_name
, dst_name
);
1538 /* FIXME: use or remove */
1540 /* If we're making a backup, we'll detect the problem case in
1541 copy_reg because SRC_NAME will no longer exist. Allowing
1542 the test to be deferred lets cp do some useful things.
1543 But when creating hardlinks and SRC_NAME is a symlink
1544 but DST_NAME is not we must test anyway. */
1546 || !S_ISLNK (src_sb_link
->st_mode
)
1547 || S_ISLNK (dst_sb_link
->st_mode
))
1550 if (x
->dereference
!= DEREF_NEVER
)
1554 if (x
->move_mode
|| x
->unlink_dest_before_opening
)
1556 /* They may refer to the same file if we're in move mode and the
1557 target is a symlink. That is ok, since we remove any existing
1558 destination file before opening it -- via 'rename' if they're on
1559 the same file system, via 'unlink (DST_NAME)' otherwise. */
1560 if (S_ISLNK (dst_sb_link
->st_mode
))
1563 /* It's not ok if they're distinct hard links to the same file as
1564 this causes a race condition and we may lose data in this case. */
1566 && 1 < dst_sb_link
->st_nlink
1567 && ! same_name (src_name
, dst_name
))
1568 return ! x
->move_mode
;
1571 /* If neither is a symlink, then it's ok as long as they aren't
1572 hard links to the same file. */
1573 if (!S_ISLNK (src_sb_link
->st_mode
) && !S_ISLNK (dst_sb_link
->st_mode
))
1575 if (!SAME_INODE (*src_sb_link
, *dst_sb_link
))
1578 /* If they are the same file, it's ok if we're making hard links. */
1586 /* At this point, it is normally an error (data loss) to move a symlink
1587 onto its referent, but in at least one narrow case, it is not:
1589 1) src is a symlink,
1590 2) dest has a link count of 2 or more and
1591 3) dest and the referent of src are not the same directory entry,
1592 then it's ok, since while we'll lose one of those hard links,
1593 src will still point to a remaining link.
1594 Note that technically, condition #3 obviates condition #2, but we
1595 retain the 1 < st_nlink condition because that means fewer invocations
1596 of the more expensive #3.
1599 $ touch f && ln f l && ln -s f s
1601 -rw-------. 2 0 Jan 4 22:46 f
1602 -rw-------. 2 0 Jan 4 22:46 l
1603 lrwxrwxrwx. 1 1 Jan 4 22:46 s -> f
1604 this must fail: mv s f
1605 this must succeed: mv s l */
1607 && S_ISLNK (src_sb
->st_mode
)
1608 && 1 < dst_sb_link
->st_nlink
)
1610 char *abs_src
= canonicalize_file_name (src_name
);
1613 bool result
= ! same_name (abs_src
, dst_name
);
1619 /* It's ok to remove a destination symlink. But that works only when we
1620 unlink before opening the destination and when the source and destination
1621 files are on the same partition. */
1622 if (x
->unlink_dest_before_opening
1623 && S_ISLNK (dst_sb_link
->st_mode
))
1624 return dst_sb_link
->st_dev
== src_sb_link
->st_dev
;
1626 if (x
->dereference
== DEREF_NEVER
)
1628 if ( ! S_ISLNK (src_sb_link
->st_mode
))
1629 tmp_src_sb
= *src_sb_link
;
1630 else if (stat (src_name
, &tmp_src_sb
) != 0)
1633 if ( ! S_ISLNK (dst_sb_link
->st_mode
))
1634 tmp_dst_sb
= *dst_sb_link
;
1635 else if (stat (dst_name
, &tmp_dst_sb
) != 0)
1638 if ( ! SAME_INODE (tmp_src_sb
, tmp_dst_sb
))
1641 /* FIXME: shouldn't this be testing whether we're making symlinks? */
1652 /* Return true if FILE, with mode MODE, is writable in the sense of 'mv'.
1653 Always consider a symbolic link to be writable. */
1655 writable_destination (char const *file
, mode_t mode
)
1657 return (S_ISLNK (mode
)
1658 || can_write_any_file ()
1659 || euidaccess (file
, W_OK
) == 0);
1663 overwrite_ok (struct cp_options
const *x
, char const *dst_name
,
1664 struct stat
const *dst_sb
)
1666 if (! writable_destination (dst_name
, dst_sb
->st_mode
))
1668 char perms
[12]; /* "-rwxrwxrwx " ls-style modes. */
1669 strmode (dst_sb
->st_mode
, perms
);
1672 (x
->move_mode
|| x
->unlink_dest_before_opening
1673 || x
->unlink_dest_after_failed_open
)
1674 ? _("%s: replace %s, overriding mode %04lo (%s)? ")
1675 : _("%s: unwritable %s (mode %04lo, %s); try anyway? "),
1676 program_name
, quoteaf (dst_name
),
1677 (unsigned long int) (dst_sb
->st_mode
& CHMOD_MODE_BITS
),
1682 fprintf (stderr
, _("%s: overwrite %s? "),
1683 program_name
, quoteaf (dst_name
));
1689 /* Initialize the hash table implementing a set of F_triple entries
1690 corresponding to destination files. */
1692 dest_info_init (struct cp_options
*x
)
1695 = hash_initialize (DEST_INFO_INITIAL_CAPACITY
,
1702 /* Initialize the hash table implementing a set of F_triple entries
1703 corresponding to source files listed on the command line. */
1705 src_info_init (struct cp_options
*x
)
1708 /* Note that we use triple_hash_no_name here.
1709 Contrast with the use of triple_hash above.
1710 That is necessary because a source file may be specified
1711 in many different ways. We want to warn about this
1717 = hash_initialize (DEST_INFO_INITIAL_CAPACITY
,
1719 triple_hash_no_name
,
1724 /* When effecting a move (e.g., for mv(1)), and given the name DST_NAME
1725 of the destination and a corresponding stat buffer, DST_SB, return
1726 true if the logical 'move' operation should _not_ proceed.
1727 Otherwise, return false.
1728 Depending on options specified in X, this code may issue an
1729 interactive prompt asking whether it's ok to overwrite DST_NAME. */
1731 abandon_move (const struct cp_options
*x
,
1732 char const *dst_name
,
1733 struct stat
const *dst_sb
)
1735 assert (x
->move_mode
);
1736 return (x
->interactive
== I_ALWAYS_NO
1737 || ((x
->interactive
== I_ASK_USER
1738 || (x
->interactive
== I_UNSPECIFIED
1740 && ! writable_destination (dst_name
, dst_sb
->st_mode
)))
1741 && ! overwrite_ok (x
, dst_name
, dst_sb
)));
1744 /* Print --verbose output on standard output, e.g. 'new' -> 'old'.
1745 If BACKUP_DST_NAME is non-NULL, then also indicate that it is
1746 the name of a backup file. */
1748 emit_verbose (char const *src
, char const *dst
, char const *backup_dst_name
)
1750 printf ("%s -> %s", quoteaf_n (0, src
), quoteaf_n (1, dst
));
1751 if (backup_dst_name
)
1752 printf (_(" (backup: %s)"), quoteaf (backup_dst_name
));
1756 /* A wrapper around "setfscreatecon (NULL)" that exits upon failure. */
1758 restore_default_fscreatecon_or_die (void)
1760 if (setfscreatecon (NULL
) != 0)
1761 error (EXIT_FAILURE
, errno
,
1762 _("failed to restore the default file creation context"));
1765 /* Create a hard link DST_NAME to SRC_NAME, honoring the REPLACE, VERBOSE and
1766 DEREFERENCE settings. Return true upon success. Otherwise, diagnose the
1767 failure and return false. If SRC_NAME is a symbolic link, then it will not
1768 be followed unless DEREFERENCE is true.
1769 If the system doesn't support hard links to symbolic links, then DST_NAME
1770 will be created as a symbolic link to SRC_NAME. */
1772 create_hard_link (char const *src_name
, char const *dst_name
,
1773 bool replace
, bool verbose
, bool dereference
)
1775 /* We want to guarantee that symlinks are not followed, unless requested. */
1778 flags
= AT_SYMLINK_FOLLOW
;
1780 bool link_failed
= (linkat (AT_FDCWD
, src_name
, AT_FDCWD
, dst_name
, flags
)
1783 /* If the link failed because of an existing destination,
1784 remove that file and then call link again. */
1785 if (link_failed
&& replace
&& errno
== EEXIST
)
1787 if (unlink (dst_name
) != 0)
1789 error (0, errno
, _("cannot remove %s"), quoteaf (dst_name
));
1793 printf (_("removed %s\n"), quoteaf (dst_name
));
1794 link_failed
= (linkat (AT_FDCWD
, src_name
, AT_FDCWD
, dst_name
, flags
)
1800 error (0, errno
, _("cannot create hard link %s to %s"),
1801 quoteaf_n (0, dst_name
), quoteaf_n (1, src_name
));
1808 /* Return true if the current file should be (tried to be) dereferenced:
1809 either for DEREF_ALWAYS or for DEREF_COMMAND_LINE_ARGUMENTS in the case
1810 where the current file is a COMMAND_LINE_ARG; otherwise return false. */
1811 static inline bool _GL_ATTRIBUTE_PURE
1812 should_dereference (const struct cp_options
*x
, bool command_line_arg
)
1814 return x
->dereference
== DEREF_ALWAYS
1815 || (x
->dereference
== DEREF_COMMAND_LINE_ARGUMENTS
1816 && command_line_arg
);
1819 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
1820 any type. NEW_DST should be true if the file DST_NAME cannot
1821 exist because its parent directory was just created; NEW_DST should
1822 be false if DST_NAME might already exist. A non-null PARENT describes the
1823 parent directory. ANCESTORS points to a linked, null terminated list of
1824 devices and inodes of parent directories of SRC_NAME. COMMAND_LINE_ARG
1825 is true iff SRC_NAME was specified on the command line.
1826 FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG is both input and output.
1827 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
1828 same as) DST_NAME; otherwise, clear it.
1829 Return true if successful. */
1831 copy_internal (char const *src_name
, char const *dst_name
,
1833 struct stat
const *parent
,
1834 struct dir_list
*ancestors
,
1835 const struct cp_options
*x
,
1836 bool command_line_arg
,
1837 bool *first_dir_created_per_command_line_arg
,
1838 bool *copy_into_self
,
1839 bool *rename_succeeded
)
1844 mode_t dst_mode
IF_LINT ( = 0);
1845 mode_t dst_mode_bits
;
1846 mode_t omitted_permissions
;
1847 bool restore_dst_mode
= false;
1848 char *earlier_file
= NULL
;
1849 char *dst_backup
= NULL
;
1850 bool backup_succeeded
= false;
1852 bool copied_as_regular
= false;
1853 bool dest_is_symlink
= false;
1854 bool have_dst_lstat
= false;
1856 if (x
->move_mode
&& rename_succeeded
)
1857 *rename_succeeded
= false;
1859 *copy_into_self
= false;
1861 if (XSTAT (x
, src_name
, &src_sb
) != 0)
1863 error (0, errno
, _("cannot stat %s"), quoteaf (src_name
));
1867 src_mode
= src_sb
.st_mode
;
1869 if (S_ISDIR (src_mode
) && !x
->recursive
)
1871 error (0, 0, _("omitting directory %s"), quoteaf (src_name
));
1875 /* Detect the case in which the same source file appears more than
1876 once on the command line and no backup option has been selected.
1877 If so, simply warn and don't copy it the second time.
1878 This check is enabled only if x->src_info is non-NULL. */
1879 if (command_line_arg
)
1881 if ( ! S_ISDIR (src_sb
.st_mode
)
1882 && x
->backup_type
== no_backups
1883 && seen_file (x
->src_info
, src_name
, &src_sb
))
1885 error (0, 0, _("warning: source file %s specified more than once"),
1886 quoteaf (src_name
));
1890 record_file (x
->src_info
, src_name
, &src_sb
);
1893 bool dereference
= should_dereference (x
, command_line_arg
);
1897 /* Regular files can be created by writing through symbolic
1898 links, but other files cannot. So use stat on the
1899 destination when copying a regular file, and lstat otherwise.
1900 However, if we intend to unlink or remove the destination
1901 first, use lstat, since a copy won't actually be made to the
1902 destination in that case. */
1904 ((S_ISREG (src_mode
)
1905 || (x
->copy_as_regular
1906 && ! (S_ISDIR (src_mode
) || S_ISLNK (src_mode
))))
1907 && ! (x
->move_mode
|| x
->symbolic_link
|| x
->hard_link
1908 || x
->backup_type
!= no_backups
1909 || x
->unlink_dest_before_opening
));
1911 ? stat (dst_name
, &dst_sb
)
1912 : lstat (dst_name
, &dst_sb
))
1915 if (errno
!= ENOENT
)
1917 error (0, errno
, _("cannot stat %s"), quoteaf (dst_name
));
1926 { /* Here, we know that dst_name exists, at least to the point
1927 that it is stat'able or lstat'able. */
1930 have_dst_lstat
= !use_stat
;
1931 if (! same_file_ok (src_name
, &src_sb
, dst_name
, &dst_sb
,
1934 error (0, 0, _("%s and %s are the same file"),
1935 quoteaf_n (0, src_name
), quoteaf_n (1, dst_name
));
1939 if (!S_ISDIR (src_mode
) && x
->update
)
1941 /* When preserving time stamps (but not moving within a file
1942 system), don't worry if the destination time stamp is
1943 less than the source merely because of time stamp
1945 int options
= ((x
->preserve_timestamps
1947 && dst_sb
.st_dev
== src_sb
.st_dev
))
1948 ? UTIMECMP_TRUNCATE_SOURCE
1951 if (0 <= utimecmp (dst_name
, &dst_sb
, &src_sb
, options
))
1953 /* We're using --update and the destination is not older
1954 than the source, so do not copy or move. Pretend the
1955 rename succeeded, so the caller (if it's mv) doesn't
1956 end up removing the source file. */
1957 if (rename_succeeded
)
1958 *rename_succeeded
= true;
1960 /* However, we still must record that we've processed
1961 this src/dest pair, in case this source file is
1962 hard-linked to another one. In that case, we'll use
1963 the mapping information to link the corresponding
1964 destination names. */
1965 earlier_file
= remember_copied (dst_name
, src_sb
.st_ino
,
1969 /* Note we currently replace DST_NAME unconditionally,
1970 even if it was a newer separate file. */
1971 if (! create_hard_link (earlier_file
, dst_name
, true,
1972 x
->verbose
, dereference
))
1982 /* When there is an existing destination file, we may end up
1983 returning early, and hence not copying/moving the file.
1984 This may be due to an interactive 'negative' reply to the
1985 prompt about the existing file. It may also be due to the
1986 use of the --no-clobber option.
1988 cp and mv treat -i and -f differently. */
1991 if (abandon_move (x
, dst_name
, &dst_sb
))
1993 /* Pretend the rename succeeded, so the caller (mv)
1994 doesn't end up removing the source file. */
1995 if (rename_succeeded
)
1996 *rename_succeeded
= true;
2002 if (! S_ISDIR (src_mode
)
2003 && (x
->interactive
== I_ALWAYS_NO
2004 || (x
->interactive
== I_ASK_USER
2005 && ! overwrite_ok (x
, dst_name
, &dst_sb
))))
2012 if (!S_ISDIR (dst_sb
.st_mode
))
2014 if (S_ISDIR (src_mode
))
2016 if (x
->move_mode
&& x
->backup_type
!= no_backups
)
2018 /* Moving a directory onto an existing
2019 non-directory is ok only with --backup. */
2024 _("cannot overwrite non-directory %s with directory %s"),
2025 quoteaf_n (0, dst_name
), quoteaf_n (1, src_name
));
2030 /* Don't let the user destroy their data, even if they try hard:
2031 This mv command must fail (likewise for cp):
2032 rm -rf a b c; mkdir a b c; touch a/f b/f; mv a/f b/f c
2033 Otherwise, the contents of b/f would be lost.
2034 In the case of 'cp', b/f would be lost if the user simulated
2035 a move using cp and rm.
2036 Note that it works fine if you use --backup=numbered. */
2037 if (command_line_arg
2038 && x
->backup_type
!= numbered_backups
2039 && seen_file (x
->dest_info
, dst_name
, &dst_sb
))
2042 _("will not overwrite just-created %s with %s"),
2043 quoteaf_n (0, dst_name
), quoteaf_n (1, src_name
));
2048 if (!S_ISDIR (src_mode
))
2050 if (S_ISDIR (dst_sb
.st_mode
))
2052 if (x
->move_mode
&& x
->backup_type
!= no_backups
)
2054 /* Moving a non-directory onto an existing
2055 directory is ok only with --backup. */
2060 _("cannot overwrite directory %s with non-directory"),
2061 quoteaf (dst_name
));
2069 /* Don't allow user to move a directory onto a non-directory. */
2070 if (S_ISDIR (src_sb
.st_mode
) && !S_ISDIR (dst_sb
.st_mode
)
2071 && x
->backup_type
== no_backups
)
2074 _("cannot move directory onto non-directory: %s -> %s"),
2075 quotef_n (0, src_name
), quotef_n (0, dst_name
));
2080 if (x
->backup_type
!= no_backups
2081 /* Don't try to back up a destination if the last
2082 component of src_name is "." or "..". */
2083 && ! dot_or_dotdot (last_component (src_name
))
2084 /* Create a backup of each destination directory in move mode,
2085 but not in copy mode. FIXME: it might make sense to add an
2086 option to suppress backup creation also for move mode.
2087 That would let one use mv to merge new content into an
2088 existing hierarchy. */
2089 && (x
->move_mode
|| ! S_ISDIR (dst_sb
.st_mode
)))
2091 char *tmp_backup
= find_backup_file_name (dst_name
,
2094 /* Detect (and fail) when creating the backup file would
2095 destroy the source file. Before, running the commands
2096 cd /tmp; rm -f a a~; : > a; echo A > a~; cp --b=simple a~ a
2097 would leave two zero-length files: a and a~. */
2098 /* FIXME: but simply change e.g., the final a~ to './a~'
2099 and the source will still be destroyed. */
2100 if (STREQ (tmp_backup
, src_name
))
2104 ? _("backing up %s would destroy source; %s not moved")
2105 : _("backing up %s would destroy source; %s not copied"));
2107 quoteaf_n (0, dst_name
),
2108 quoteaf_n (1, src_name
));
2114 Using alloca for a file name that may be arbitrarily
2115 long is not recommended. In fact, even forming such a name
2116 should be discouraged. Eventually, this code will be rewritten
2117 to use fts, so using alloca here will be less of a problem. */
2118 ASSIGN_STRDUPA (dst_backup
, tmp_backup
);
2120 /* In move mode, when src_name and dst_name are on the
2121 same partition (FIXME, and when they are non-directories),
2122 make the operation atomic: link dest
2123 to backup, then rename src to dest. */
2124 if (rename (dst_name
, dst_backup
) != 0)
2126 if (errno
!= ENOENT
)
2128 error (0, errno
, _("cannot backup %s"),
2129 quoteaf (dst_name
));
2139 backup_succeeded
= true;
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. */
2202 if (x
->verbose
&& !S_ISDIR (src_mode
))
2203 emit_verbose (src_name
, dst_name
, backup_succeeded
? dst_backup
: NULL
);
2205 /* Associate the destination file name with the source device and inode
2206 so that if we encounter a matching dev/ino pair in the source tree
2207 we can arrange to create a hard link between the corresponding names
2208 in the destination tree.
2210 When using the --link (-l) option, there is no need to take special
2211 measures, because (barring race conditions) files that are hard-linked
2212 in the source tree will also be hard-linked in the destination tree.
2214 Sometimes, when preserving links, we have to record dev/ino even
2215 though st_nlink == 1:
2216 - when in move_mode, since we may be moving a group of N hard-linked
2217 files (via two or more command line arguments) to a different
2218 partition; the links may be distributed among the command line
2219 arguments (possibly hierarchies) so that the link count of
2220 the final, once-linked source file is reduced to 1 when it is
2221 considered below. But in this case (for mv) we don't need to
2222 incur the expense of recording the dev/ino => name mapping; all we
2223 really need is a lookup, to see if the dev/ino pair has already
2225 - when using -H and processing a command line argument;
2226 that command line argument could be a symlink pointing to another
2227 command line argument. With 'cp -H --preserve=link', we hard-link
2228 those two destination files.
2229 - likewise for -L except that it applies to all files, not just
2230 command line arguments.
2232 Also, with --recursive, record dev/ino of each command-line directory.
2233 We'll use that info to detect this problem: cp -R dir dir. */
2235 if (x
->recursive
&& S_ISDIR (src_mode
))
2237 if (command_line_arg
)
2238 earlier_file
= remember_copied (dst_name
, src_sb
.st_ino
, src_sb
.st_dev
);
2240 earlier_file
= src_to_dest_lookup (src_sb
.st_ino
, src_sb
.st_dev
);
2242 else if (x
->move_mode
&& src_sb
.st_nlink
== 1)
2244 earlier_file
= src_to_dest_lookup (src_sb
.st_ino
, src_sb
.st_dev
);
2246 else if (x
->preserve_links
2248 && (1 < src_sb
.st_nlink
2249 || (command_line_arg
2250 && x
->dereference
== DEREF_COMMAND_LINE_ARGUMENTS
)
2251 || x
->dereference
== DEREF_ALWAYS
))
2253 earlier_file
= remember_copied (dst_name
, src_sb
.st_ino
, src_sb
.st_dev
);
2256 /* Did we copy this inode somewhere else (in this command line argument)
2257 and therefore this is a second hard link to the inode? */
2261 /* Avoid damaging the destination file system by refusing to preserve
2262 hard-linked directories (which are found at least in Netapp snapshot
2264 if (S_ISDIR (src_mode
))
2266 /* If src_name and earlier_file refer to the same directory entry,
2267 then warn about copying a directory into itself. */
2268 if (same_name (src_name
, earlier_file
))
2270 error (0, 0, _("cannot copy a directory, %s, into itself, %s"),
2271 quoteaf_n (0, top_level_src_name
),
2272 quoteaf_n (1, top_level_dst_name
));
2273 *copy_into_self
= true;
2276 else if (same_name (dst_name
, earlier_file
))
2278 error (0, 0, _("warning: source directory %s "
2279 "specified more than once"),
2280 quoteaf (top_level_src_name
));
2281 /* In move mode, if a previous rename succeeded, then
2282 we won't be in this path as the source is missing. If the
2283 rename previously failed, then that has been handled, so
2284 pretend this attempt succeeded so the source isn't removed. */
2285 if (x
->move_mode
&& rename_succeeded
)
2286 *rename_succeeded
= true;
2287 /* We only do backups in move mode, and for non directories.
2288 So just ignore this repeated entry. */
2291 else if (x
->dereference
== DEREF_ALWAYS
2292 || (command_line_arg
2293 && x
->dereference
== DEREF_COMMAND_LINE_ARGUMENTS
))
2295 /* This happens when e.g., encountering a directory for the
2296 second or subsequent time via symlinks when cp is invoked
2297 with -R and -L. E.g.,
2298 rm -rf a b c d; mkdir a b c d; ln -s ../c a; ln -s ../c b;
2304 error (0, 0, _("will not create hard link %s to directory %s"),
2305 quoteaf_n (0, dst_name
), quoteaf_n (1, earlier_file
));
2311 if (! create_hard_link (earlier_file
, dst_name
, true, x
->verbose
,
2321 if (rename (src_name
, dst_name
) == 0)
2323 if (x
->verbose
&& S_ISDIR (src_mode
))
2324 emit_verbose (src_name
, dst_name
,
2325 backup_succeeded
? dst_backup
: NULL
);
2327 if (x
->set_security_context
)
2329 /* -Z failures are only warnings currently. */
2330 (void) set_file_security_ctx (dst_name
, false, true, x
);
2333 if (rename_succeeded
)
2334 *rename_succeeded
= true;
2336 if (command_line_arg
)
2338 /* Record destination dev/ino/name, so that if we are asked
2339 to overwrite that file again, we can detect it and fail. */
2340 /* It's fine to use the _source_ stat buffer (src_sb) to get the
2341 _destination_ dev/ino, since the rename above can't have
2342 changed those, and 'mv' always uses lstat.
2343 We could limit it further by operating
2344 only on non-directories. */
2345 record_file (x
->dest_info
, dst_name
, &src_sb
);
2351 /* FIXME: someday, consider what to do when moving a directory into
2352 itself but when source and destination are on different devices. */
2354 /* This happens when attempting to rename a directory to a
2355 subdirectory of itself. */
2356 if (errno
== EINVAL
)
2358 /* FIXME: this is a little fragile in that it relies on rename(2)
2359 failing with a specific errno value. Expect problems on
2360 non-POSIX systems. */
2361 error (0, 0, _("cannot move %s to a subdirectory of itself, %s"),
2362 quoteaf_n (0, top_level_src_name
),
2363 quoteaf_n (1, top_level_dst_name
));
2365 /* Note that there is no need to call forget_created here,
2366 (compare with the other calls in this file) since the
2367 destination directory didn't exist before. */
2369 *copy_into_self
= true;
2370 /* FIXME-cleanup: Don't return true here; adjust mv.c accordingly.
2371 The only caller that uses this code (mv.c) ends up setting its
2372 exit status to nonzero when copy_into_self is nonzero. */
2376 /* WARNING: there probably exist systems for which an inter-device
2377 rename fails with a value of errno not handled here.
2378 If/as those are reported, add them to the condition below.
2379 If this happens to you, please do the following and send the output
2380 to the bug-reporting address (e.g., in the output of cp --help):
2381 touch k; perl -e 'rename "k","/tmp/k" or print "$!(",$!+0,")\n"'
2382 where your current directory is on one partition and /tmp is the other.
2383 Also, please try to find the E* errno macro name corresponding to
2384 the diagnostic and parenthesized integer, and include that in your
2385 e-mail. One way to do that is to run a command like this
2386 find /usr/include/. -type f \
2387 | xargs grep 'define.*\<E[A-Z]*\>.*\<18\>' /dev/null
2388 where you'd replace '18' with the integer in parentheses that
2389 was output from the perl one-liner above.
2390 If necessary, of course, change '/tmp' to some other directory. */
2393 /* There are many ways this can happen due to a race condition.
2394 When something happens between the initial XSTAT and the
2395 subsequent rename, we can get many different types of errors.
2396 For example, if the destination is initially a non-directory
2397 or non-existent, but it is created as a directory, the rename
2398 fails. If two 'mv' commands try to rename the same file at
2399 about the same time, one will succeed and the other will fail.
2400 If the permissions on the directory containing the source or
2401 destination file are made too restrictive, the rename will
2404 _("cannot move %s to %s"),
2405 quoteaf_n (0, src_name
), quoteaf_n (1, dst_name
));
2406 forget_created (src_sb
.st_ino
, src_sb
.st_dev
);
2410 /* The rename attempt has failed. Remove any existing destination
2411 file so that a cross-device 'mv' acts as if it were really using
2412 the rename syscall. Note both src and dst must both be directories
2413 or not, and this is enforced above. Therefore we check the src_mode
2414 and operate on dst_name here as a tighter constraint and also because
2415 src_mode is readily available here. */
2416 if ((S_ISDIR (src_mode
) ? rmdir (dst_name
) : unlink (dst_name
)) != 0
2420 _("inter-device move failed: %s to %s; unable to remove target"),
2421 quoteaf_n (0, src_name
), quoteaf_n (1, dst_name
));
2422 forget_created (src_sb
.st_ino
, src_sb
.st_dev
);
2429 /* If the ownership might change, or if it is a directory (whose
2430 special mode bits may change after the directory is created),
2431 omit some permissions at first, so unauthorized users cannot nip
2432 in before the file is ready. */
2433 dst_mode_bits
= (x
->set_mode
? x
->mode
: src_mode
) & CHMOD_MODE_BITS
;
2434 omitted_permissions
=
2436 & (x
->preserve_ownership
? S_IRWXG
| S_IRWXO
2437 : S_ISDIR (src_mode
) ? S_IWGRP
| S_IWOTH
2442 /* If required, set the default security context for new files.
2443 Also for existing files this is used as a reference
2444 when copying the context with --preserve=context.
2445 FIXME: Do we need to consider dst_mode_bits here? */
2446 if (! set_process_security_ctx (src_name
, dst_name
, src_mode
, new_dst
, x
))
2449 if (S_ISDIR (src_mode
))
2451 struct dir_list
*dir
;
2453 /* If this directory has been copied before during the
2454 recursion, there is a symbolic link to an ancestor
2455 directory of the symbolic link. It is impossible to
2456 continue to copy this, unless we've got an infinite disk. */
2458 if (is_ancestor (&src_sb
, ancestors
))
2460 error (0, 0, _("cannot copy cyclic symbolic link %s"),
2461 quoteaf (src_name
));
2465 /* Insert the current directory in the list of parents. */
2467 dir
= alloca (sizeof *dir
);
2468 dir
->parent
= ancestors
;
2469 dir
->ino
= src_sb
.st_ino
;
2470 dir
->dev
= src_sb
.st_dev
;
2472 if (new_dst
|| !S_ISDIR (dst_sb
.st_mode
))
2474 /* POSIX says mkdir's behavior is implementation-defined when
2475 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
2476 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
2477 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
2478 if (mkdir (dst_name
, dst_mode_bits
& ~omitted_permissions
) != 0)
2480 error (0, errno
, _("cannot create directory %s"),
2481 quoteaf (dst_name
));
2485 /* We need search and write permissions to the new directory
2486 for writing the directory's contents. Check if these
2487 permissions are there. */
2489 if (lstat (dst_name
, &dst_sb
) != 0)
2491 error (0, errno
, _("cannot stat %s"), quoteaf (dst_name
));
2494 else if ((dst_sb
.st_mode
& S_IRWXU
) != S_IRWXU
)
2496 /* Make the new directory searchable and writable. */
2498 dst_mode
= dst_sb
.st_mode
;
2499 restore_dst_mode
= true;
2501 if (lchmod (dst_name
, dst_mode
| S_IRWXU
) != 0)
2503 error (0, errno
, _("setting permissions for %s"),
2504 quoteaf (dst_name
));
2509 /* Record the created directory's inode and device numbers into
2510 the search structure, so that we can avoid copying it again.
2511 Do this only for the first directory that is created for each
2512 source command line argument. */
2513 if (!*first_dir_created_per_command_line_arg
)
2515 remember_copied (dst_name
, dst_sb
.st_ino
, dst_sb
.st_dev
);
2516 *first_dir_created_per_command_line_arg
= true;
2520 emit_verbose (src_name
, dst_name
, NULL
);
2524 omitted_permissions
= 0;
2526 /* For directories, the process global context could be reset for
2527 descendents, so use it to set the context for existing dirs here.
2528 This will also give earlier indication of failure to set ctx. */
2529 if (x
->set_security_context
|| x
->preserve_security_context
)
2530 if (! set_file_security_ctx (dst_name
, x
->preserve_security_context
,
2533 if (x
->require_preserve_context
)
2538 /* Decide whether to copy the contents of the directory. */
2539 if (x
->one_file_system
&& parent
&& parent
->st_dev
!= src_sb
.st_dev
)
2541 /* Here, we are crossing a file system boundary and cp's -x option
2542 is in effect: so don't copy the contents of this directory. */
2546 /* Copy the contents of the directory. Don't just return if
2547 this fails -- otherwise, the failure to read a single file
2548 in a source directory would cause the containing destination
2549 directory not to have owner/perms set properly. */
2550 delayed_ok
= copy_dir (src_name
, dst_name
, new_dst
, &src_sb
, dir
, x
,
2551 first_dir_created_per_command_line_arg
,
2555 else if (x
->symbolic_link
)
2557 dest_is_symlink
= true;
2558 if (*src_name
!= '/')
2560 /* Check that DST_NAME denotes a file in the current directory. */
2562 struct stat dst_parent_sb
;
2564 bool in_current_dir
;
2566 dst_parent
= dir_name (dst_name
);
2568 in_current_dir
= (STREQ (".", dst_parent
)
2569 /* If either stat call fails, it's ok not to report
2570 the failure and say dst_name is in the current
2571 directory. Other things will fail later. */
2572 || stat (".", &dot_sb
) != 0
2573 || stat (dst_parent
, &dst_parent_sb
) != 0
2574 || SAME_INODE (dot_sb
, dst_parent_sb
));
2577 if (! in_current_dir
)
2580 _("%s: can make relative symbolic links only in current directory"),
2585 if (symlink (src_name
, dst_name
) != 0)
2587 error (0, errno
, _("cannot create symbolic link %s to %s"),
2588 quoteaf_n (0, dst_name
), quoteaf_n (1, src_name
));
2593 /* POSIX 2008 states that it is implementation-defined whether
2594 link() on a symlink creates a hard-link to the symlink, or only
2595 to the referent (effectively dereferencing the symlink) (POSIX
2596 2001 required the latter behavior, although many systems provided
2597 the former). Yet cp, invoked with '--link --no-dereference',
2598 should not follow the link. We can approximate the desired
2599 behavior by skipping this hard-link creating block and instead
2600 copying the symlink, via the 'S_ISLNK'- copying code below.
2602 Note gnulib's linkat module, guarantees that the symlink is not
2603 dereferenced. However its emulation currently doesn't maintain
2604 timestamps or ownership so we only call it when we know the
2605 emulation will not be needed. */
2606 else if (x
->hard_link
2607 && !(! CAN_HARDLINK_SYMLINKS
&& S_ISLNK (src_mode
)
2608 && x
->dereference
== DEREF_NEVER
))
2610 if (! create_hard_link (src_name
, dst_name
, false, false, dereference
))
2613 else if (S_ISREG (src_mode
)
2614 || (x
->copy_as_regular
&& !S_ISLNK (src_mode
)))
2616 copied_as_regular
= true;
2617 /* POSIX says the permission bits of the source file must be
2618 used as the 3rd argument in the open call. Historical
2619 practice passed all the source mode bits to 'open', but the extra
2620 bits were ignored, so it should be the same either way.
2622 This call uses DST_MODE_BITS, not SRC_MODE. These are
2623 normally the same, and the exception (where x->set_mode) is
2624 used only by 'install', which POSIX does not specify and
2625 where DST_MODE_BITS is what's wanted. */
2626 if (! copy_reg (src_name
, dst_name
, x
, dst_mode_bits
& S_IRWXUGO
,
2627 omitted_permissions
, &new_dst
, &src_sb
))
2630 else if (S_ISFIFO (src_mode
))
2632 /* Use mknod, rather than mkfifo, because the former preserves
2633 the special mode bits of a fifo on Solaris 10, while mkfifo
2634 does not. But fall back on mkfifo, because on some BSD systems,
2635 mknod always fails when asked to create a FIFO. */
2636 if (mknod (dst_name
, src_mode
& ~omitted_permissions
, 0) != 0)
2637 if (mkfifo (dst_name
, src_mode
& ~S_IFIFO
& ~omitted_permissions
) != 0)
2639 error (0, errno
, _("cannot create fifo %s"), quoteaf (dst_name
));
2643 else if (S_ISBLK (src_mode
) || S_ISCHR (src_mode
) || S_ISSOCK (src_mode
))
2645 if (mknod (dst_name
, src_mode
& ~omitted_permissions
, src_sb
.st_rdev
)
2648 error (0, errno
, _("cannot create special file %s"),
2649 quoteaf (dst_name
));
2653 else if (S_ISLNK (src_mode
))
2655 char *src_link_val
= areadlink_with_size (src_name
, src_sb
.st_size
);
2656 dest_is_symlink
= true;
2657 if (src_link_val
== NULL
)
2659 error (0, errno
, _("cannot read symbolic link %s"),
2660 quoteaf (src_name
));
2664 if (symlink (src_link_val
, dst_name
) == 0)
2665 free (src_link_val
);
2668 int saved_errno
= errno
;
2669 bool same_link
= false;
2670 if (x
->update
&& !new_dst
&& S_ISLNK (dst_sb
.st_mode
)
2671 && dst_sb
.st_size
== strlen (src_link_val
))
2673 /* See if the destination is already the desired symlink.
2674 FIXME: This behavior isn't documented, and seems wrong
2675 in some cases, e.g., if the destination symlink has the
2676 wrong ownership, permissions, or time stamps. */
2677 char *dest_link_val
=
2678 areadlink_with_size (dst_name
, dst_sb
.st_size
);
2679 if (dest_link_val
&& STREQ (dest_link_val
, src_link_val
))
2681 free (dest_link_val
);
2683 free (src_link_val
);
2687 error (0, saved_errno
, _("cannot create symbolic link %s"),
2688 quoteaf (dst_name
));
2693 if (x
->preserve_security_context
)
2694 restore_default_fscreatecon_or_die ();
2696 if (x
->preserve_ownership
)
2698 /* Preserve the owner and group of the just-'copied'
2699 symbolic link, if possible. */
2701 && lchown (dst_name
, src_sb
.st_uid
, src_sb
.st_gid
) != 0
2702 && ! chown_failure_ok (x
))
2704 error (0, errno
, _("failed to preserve ownership for %s"),
2710 /* Can't preserve ownership of symlinks.
2711 FIXME: maybe give a warning or even error for symlinks
2712 in directories with the sticky bit set -- there, not
2713 preserving owner/group is a potential security problem. */
2719 error (0, 0, _("%s has unknown file type"), quoteaf (src_name
));
2723 /* With -Z or --preserve=context, set the context for existing files.
2724 Note this is done already for copy_reg() for reasons described therein. */
2725 if (!new_dst
&& !x
->copy_as_regular
&& !S_ISDIR (src_mode
)
2726 && (x
->set_security_context
|| x
->preserve_security_context
))
2728 if (! set_file_security_ctx (dst_name
, x
->preserve_security_context
,
2731 if (x
->require_preserve_context
)
2736 if (command_line_arg
&& x
->dest_info
)
2738 /* Now that the destination file is very likely to exist,
2739 add its info to the set. */
2741 if (lstat (dst_name
, &sb
) == 0)
2742 record_file (x
->dest_info
, dst_name
, &sb
);
2745 /* If we've just created a hard-link due to cp's --link option,
2747 if (x
->hard_link
&& ! S_ISDIR (src_mode
)
2748 && !(! CAN_HARDLINK_SYMLINKS
&& S_ISLNK (src_mode
)
2749 && x
->dereference
== DEREF_NEVER
))
2752 if (copied_as_regular
)
2755 /* POSIX says that 'cp -p' must restore the following:
2757 - setuid, setgid bits
2759 If it fails to restore any of those, we may give a warning but
2760 the destination must not be removed.
2761 FIXME: implement the above. */
2763 /* Adjust the times (and if possible, ownership) for the copy.
2764 chown turns off set[ug]id bits for non-root,
2765 so do the chmod last. */
2767 if (x
->preserve_timestamps
)
2769 struct timespec timespec
[2];
2770 timespec
[0] = get_stat_atime (&src_sb
);
2771 timespec
[1] = get_stat_mtime (&src_sb
);
2773 if ((dest_is_symlink
2774 ? utimens_symlink (dst_name
, timespec
)
2775 : utimens (dst_name
, timespec
))
2778 error (0, errno
, _("preserving times for %s"), quoteaf (dst_name
));
2779 if (x
->require_preserve
)
2784 /* Avoid calling chown if we know it's not necessary. */
2785 if (!dest_is_symlink
&& x
->preserve_ownership
2786 && (new_dst
|| !SAME_OWNER_AND_GROUP (src_sb
, dst_sb
)))
2788 switch (set_owner (x
, dst_name
, -1, &src_sb
, new_dst
, &dst_sb
))
2794 src_mode
&= ~ (S_ISUID
| S_ISGID
| S_ISVTX
);
2799 /* Set xattrs after ownership as changing owners will clear capabilities. */
2800 if (x
->preserve_xattr
&& ! copy_attr (src_name
, -1, dst_name
, -1, x
)
2801 && x
->require_preserve_xattr
)
2804 /* The operations beyond this point may dereference a symlink. */
2805 if (dest_is_symlink
)
2808 set_author (dst_name
, -1, &src_sb
);
2810 if (x
->preserve_mode
|| x
->move_mode
)
2812 if (copy_acl (src_name
, -1, dst_name
, -1, src_mode
) != 0
2813 && x
->require_preserve
)
2816 else if (x
->set_mode
)
2818 if (set_acl (dst_name
, -1, x
->mode
) != 0)
2821 else if (x
->explicit_no_preserve_mode
)
2823 if (set_acl (dst_name
, -1, 0777 & ~cached_umask ()) != 0)
2828 if (omitted_permissions
)
2830 omitted_permissions
&= ~ cached_umask ();
2832 if (omitted_permissions
&& !restore_dst_mode
)
2834 /* Permissions were deliberately omitted when the file
2835 was created due to security concerns. See whether
2836 they need to be re-added now. It'd be faster to omit
2837 the lstat, but deducing the current destination mode
2838 is tricky in the presence of implementation-defined
2839 rules for special mode bits. */
2840 if (new_dst
&& lstat (dst_name
, &dst_sb
) != 0)
2842 error (0, errno
, _("cannot stat %s"), quoteaf (dst_name
));
2845 dst_mode
= dst_sb
.st_mode
;
2846 if (omitted_permissions
& ~dst_mode
)
2847 restore_dst_mode
= true;
2851 if (restore_dst_mode
)
2853 if (lchmod (dst_name
, dst_mode
| omitted_permissions
) != 0)
2855 error (0, errno
, _("preserving permissions for %s"),
2856 quoteaf (dst_name
));
2857 if (x
->require_preserve
)
2867 if (x
->preserve_security_context
)
2868 restore_default_fscreatecon_or_die ();
2870 /* We have failed to create the destination file.
2871 If we've just added a dev/ino entry via the remember_copied
2872 call above (i.e., unless we've just failed to create a hard link),
2873 remove the entry associating the source dev/ino with the
2874 destination file name, so we don't try to 'preserve' a link
2875 to a file we didn't create. */
2876 if (earlier_file
== NULL
)
2877 forget_created (src_sb
.st_ino
, src_sb
.st_dev
);
2881 if (rename (dst_backup
, dst_name
) != 0)
2882 error (0, errno
, _("cannot un-backup %s"), quoteaf (dst_name
));
2886 printf (_("%s -> %s (unbackup)\n"),
2887 quoteaf_n (0, dst_backup
), quoteaf_n (1, dst_name
));
2893 static bool _GL_ATTRIBUTE_PURE
2894 valid_options (const struct cp_options
*co
)
2896 assert (co
!= NULL
);
2897 assert (VALID_BACKUP_TYPE (co
->backup_type
));
2898 assert (VALID_SPARSE_MODE (co
->sparse_mode
));
2899 assert (VALID_REFLINK_MODE (co
->reflink_mode
));
2900 assert (!(co
->hard_link
&& co
->symbolic_link
));
2902 (co
->reflink_mode
== REFLINK_ALWAYS
2903 && co
->sparse_mode
!= SPARSE_AUTO
));
2907 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
2908 any type. NONEXISTENT_DST should be true if the file DST_NAME
2909 is known not to exist (e.g., because its parent directory was just
2910 created); NONEXISTENT_DST should be false if DST_NAME might already
2911 exist. OPTIONS is ... FIXME-describe
2912 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
2913 same as) DST_NAME; otherwise, set clear it.
2914 Return true if successful. */
2917 copy (char const *src_name
, char const *dst_name
,
2918 bool nonexistent_dst
, const struct cp_options
*options
,
2919 bool *copy_into_self
, bool *rename_succeeded
)
2921 assert (valid_options (options
));
2923 /* Record the file names: they're used in case of error, when copying
2924 a directory into itself. I don't like to make these tools do *any*
2925 extra work in the common case when that work is solely to handle
2926 exceptional cases, but in this case, I don't see a way to derive the
2927 top level source and destination directory names where they're used.
2928 An alternative is to use COPY_INTO_SELF and print the diagnostic
2929 from every caller -- but I don't want to do that. */
2930 top_level_src_name
= src_name
;
2931 top_level_dst_name
= dst_name
;
2933 bool first_dir_created_per_command_line_arg
= false;
2934 return copy_internal (src_name
, dst_name
, nonexistent_dst
, NULL
, NULL
,
2936 &first_dir_created_per_command_line_arg
,
2937 copy_into_self
, rename_succeeded
);
2940 /* Set *X to the default options for a value of type struct cp_options. */
2943 cp_options_default (struct cp_options
*x
)
2945 memset (x
, 0, sizeof *x
);
2946 #ifdef PRIV_FILE_CHOWN
2948 priv_set_t
*pset
= priv_allocset ();
2951 if (getppriv (PRIV_EFFECTIVE
, pset
) == 0)
2953 x
->chown_privileges
= priv_ismember (pset
, PRIV_FILE_CHOWN
);
2954 x
->owner_privileges
= priv_ismember (pset
, PRIV_FILE_OWNER
);
2956 priv_freeset (pset
);
2959 x
->chown_privileges
= x
->owner_privileges
= (geteuid () == ROOT_UID
);
2963 /* Return true if it's OK for chown to fail, where errno is
2964 the error number that chown failed with and X is the copying
2968 chown_failure_ok (struct cp_options
const *x
)
2970 /* If non-root uses -p, it's ok if we can't preserve ownership.
2971 But root probably wants to know, e.g. if NFS disallows it,
2972 or if the target system doesn't support file ownership. */
2974 return ((errno
== EPERM
|| errno
== EINVAL
) && !x
->chown_privileges
);
2977 /* Similarly, return true if it's OK for chmod and similar operations
2978 to fail, where errno is the error number that chmod failed with and
2979 X is the copying option set. */
2982 owner_failure_ok (struct cp_options
const *x
)
2984 return ((errno
== EPERM
|| errno
== EINVAL
) && !x
->owner_privileges
);
2987 /* Return the user's umask, caching the result.
2989 FIXME: If the destination's parent directory has has a default ACL,
2990 some operating systems (e.g., GNU/Linux's "POSIX" ACLs) use that
2991 ACL's mask rather than the process umask. Currently, the callers
2992 of cached_umask incorrectly assume that this situation cannot occur. */
2996 static mode_t mask
= (mode_t
) -1;
2997 if (mask
== (mode_t
) -1)