1 /* copy.c -- core functions for copying files and directories
2 Copyright (C) 1989-1991, 1995-2011 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"
39 #include "extent-scan.h"
45 #include "filenamecat.h"
46 #include "full-write.h"
48 #include "hash-triple.h"
49 #include "ignore-value.h"
53 #include "stat-time.h"
56 #include "write-any-file.h"
57 #include "areadlink.h"
61 # include <attr/error_context.h>
62 # include <attr/libattr.h>
68 # define HAVE_FCHOWN false
69 # define fchown(fd, uid, gid) (-1)
73 # define HAVE_LCHOWN false
74 # define lchown(name, uid, gid) chown (name, uid, gid)
79 rpl_mkfifo (char const *file
, mode_t mode
)
84 # define mkfifo rpl_mkfifo
91 #define SAME_OWNER(A, B) ((A).st_uid == (B).st_uid)
92 #define SAME_GROUP(A, B) ((A).st_gid == (B).st_gid)
93 #define SAME_OWNER_AND_GROUP(A, B) (SAME_OWNER (A, B) && SAME_GROUP (A, B))
97 struct dir_list
*parent
;
102 /* Initial size of the cp.dest_info hash table. */
103 #define DEST_INFO_INITIAL_CAPACITY 61
105 static bool copy_internal (char const *src_name
, char const *dst_name
,
106 bool new_dst
, dev_t device
,
107 struct dir_list
*ancestors
,
108 const struct cp_options
*x
,
109 bool command_line_arg
,
110 bool *first_dir_created_per_command_line_arg
,
111 bool *copy_into_self
,
112 bool *rename_succeeded
);
113 static bool owner_failure_ok (struct cp_options
const *x
);
115 /* Pointers to the file names: they're used in the diagnostic that is issued
116 when we detect the user is trying to copy a directory into itself. */
117 static char const *top_level_src_name
;
118 static char const *top_level_dst_name
;
120 /* Set the timestamp of symlink, FILE, to TIMESPEC.
121 If this system lacks support for that, simply return 0. */
123 utimens_symlink (char const *file
, struct timespec
const *timespec
)
125 int err
= lutimens (file
, timespec
);
126 /* When configuring on a system with new headers and libraries, and
127 running on one with a kernel that is old enough to lack the syscall,
128 utimensat fails with ENOSYS. Ignore that. */
129 if (err
&& errno
== ENOSYS
)
134 /* Copy the regular file open on SRC_FD/SRC_NAME to DST_FD/DST_NAME,
135 honoring the MAKE_HOLES setting and using the BUF_SIZE-byte buffer
136 BUF for temporary storage. Copy no more than MAX_N_READ bytes.
137 Return true upon successful completion;
138 print a diagnostic and return false upon error.
139 Note that for best results, BUF should be "well"-aligned.
140 BUF must have sizeof(uintptr_t)-1 bytes of additional space
141 beyond BUF[BUF_SIZE-1].
142 Set *LAST_WRITE_MADE_HOLE to true if the final operation on
143 DEST_FD introduced a hole. Set *TOTAL_N_READ to the number of
146 sparse_copy (int src_fd
, int dest_fd
, char *buf
, size_t buf_size
,
148 char const *src_name
, char const *dst_name
,
149 uintmax_t max_n_read
, off_t
*total_n_read
,
150 bool *last_write_made_hole
)
152 typedef uintptr_t word
;
153 *last_write_made_hole
= false;
160 ssize_t n_read
= read (src_fd
, buf
, MIN (max_n_read
, buf_size
));
165 error (0, errno
, _("reading %s"), quote (src_name
));
170 max_n_read
-= n_read
;
171 *total_n_read
+= n_read
;
177 /* Sentinel to stop loop. */
180 /* Usually, buf[n_read] is not the byte just before a "word"
181 (aka uintptr_t) boundary. In that case, the word-oriented
182 test below (*wp++ == 0) would read some uninitialized bytes
183 after the sentinel. To avoid false-positive reports about
184 this condition (e.g., from a tool like valgrind), set the
185 remaining bytes -- to any value. */
186 memset (buf
+ n_read
+ 1, 0, sizeof (word
) - 1);
189 /* Find first nonzero *word*, or the word with the sentinel. */
195 /* Find the first nonzero *byte*, or the sentinel. */
197 cp
= (char *) (wp
- 1);
201 if (cp
<= buf
+ n_read
)
202 /* Clear to indicate that a normal write is needed. */
206 /* We found the sentinel, so the whole input block was zero.
208 if (lseek (dest_fd
, n_read
, SEEK_CUR
) < 0)
210 error (0, errno
, _("cannot lseek %s"), quote (dst_name
));
213 *last_write_made_hole
= true;
220 if (full_write (dest_fd
, buf
, n
) != n
)
222 error (0, errno
, _("writing %s"), quote (dst_name
));
225 *last_write_made_hole
= false;
227 /* It is tempting to return early here upon a short read from a
228 regular file. That would save the final read syscall for each
229 file. Unfortunately that doesn't work for certain files in
230 /proc with linux kernels from at least 2.6.9 .. 2.6.29. */
237 /* Perform the O(1) btrfs clone operation, if possible.
238 Upon success, return 0. Otherwise, return -1 and set errno. */
240 clone_file (int dest_fd
, int src_fd
)
243 # undef BTRFS_IOCTL_MAGIC
244 # define BTRFS_IOCTL_MAGIC 0x94
245 # undef BTRFS_IOC_CLONE
246 # define BTRFS_IOC_CLONE _IOW (BTRFS_IOCTL_MAGIC, 9, int)
247 return ioctl (dest_fd
, BTRFS_IOC_CLONE
, src_fd
);
256 /* Write N_BYTES zero bytes to file descriptor FD. Return true if successful.
257 Upon write failure, set errno and return false. */
259 write_zeros (int fd
, uint64_t n_bytes
)
262 static size_t nz
= IO_BUFSIZE
;
264 /* Attempt to use a relatively large calloc'd source buffer for
265 efficiency, but if that allocation fails, resort to a smaller
266 statically allocated one. */
269 static char fallback
[1024];
270 zeros
= calloc (nz
, 1);
274 nz
= sizeof fallback
;
280 uint64_t n
= MIN (nz
, n_bytes
);
281 if ((full_write (fd
, zeros
, n
)) != n
)
289 /* Perform an efficient extent copy, if possible. This avoids
290 the overhead of detecting holes in hole-introducing/preserving
291 copy, and thus makes copying sparse files much more efficient.
292 Upon a successful copy, return true. If the initial extent scan
293 fails, set *NORMAL_COPY_REQUIRED to true and return false.
294 Upon any other failure, set *NORMAL_COPY_REQUIRED to false and
297 extent_copy (int src_fd
, int dest_fd
, char *buf
, size_t buf_size
,
298 off_t src_total_size
, enum Sparse_type sparse_mode
,
299 char const *src_name
, char const *dst_name
,
300 bool *require_normal_copy
)
302 struct extent_scan scan
;
303 off_t last_ext_start
= 0;
304 uint64_t last_ext_len
= 0;
306 /* Keep track of the output position.
307 We may need this at the end, for a final ftruncate. */
310 extent_scan_init (src_fd
, &scan
);
312 *require_normal_copy
= false;
313 bool wrote_hole_at_eof
= true;
316 bool ok
= extent_scan_read (&scan
);
319 if (scan
.hit_final_extent
)
322 if (scan
.initial_scan_failed
)
324 *require_normal_copy
= true;
328 error (0, errno
, _("%s: failed to get extents info"),
334 bool empty_extent
= false;
335 for (i
= 0; i
< scan
.ei_count
|| empty_extent
; i
++)
341 if (i
< scan
.ei_count
)
343 ext_start
= scan
.ext_info
[i
].ext_logical
;
344 ext_len
= scan
.ext_info
[i
].ext_length
;
346 else /* empty extent at EOF. */
349 ext_start
= last_ext_start
+ scan
.ext_info
[i
].ext_length
;
353 hole_size
= ext_start
- last_ext_start
- last_ext_len
;
355 wrote_hole_at_eof
= false;
359 if (lseek (src_fd
, ext_start
, SEEK_SET
) < 0)
361 error (0, errno
, _("cannot lseek %s"), quote (src_name
));
363 extent_scan_free (&scan
);
367 if ((empty_extent
&& sparse_mode
== SPARSE_ALWAYS
)
368 || (!empty_extent
&& sparse_mode
!= SPARSE_NEVER
))
370 if (lseek (dest_fd
, ext_start
, SEEK_SET
) < 0)
372 error (0, errno
, _("cannot lseek %s"), quote (dst_name
));
375 wrote_hole_at_eof
= true;
379 /* When not inducing holes and when there is a hole between
380 the end of the previous extent and the beginning of the
381 current one, write zeros to the destination file. */
382 off_t nzeros
= hole_size
;
384 nzeros
= MIN (src_total_size
- dest_pos
, hole_size
);
386 if (! write_zeros (dest_fd
, nzeros
))
388 error (0, errno
, _("%s: write failed"), quote (dst_name
));
392 dest_pos
= MIN (src_total_size
, ext_start
);
396 last_ext_start
= ext_start
;
398 /* Treat an unwritten but allocated extent much like a hole.
399 I.E. don't read, but don't convert to a hole in the destination,
400 unless SPARSE_ALWAYS. */
401 /* For now, do not treat FIEMAP_EXTENT_UNWRITTEN specially,
402 because that (in combination with no sync) would lead to data
403 loss at least on XFS and ext4 when using 2.6.39-rc3 kernels. */
404 if (0 && (scan
.ext_info
[i
].ext_flags
& FIEMAP_EXTENT_UNWRITTEN
))
408 if (ext_len
== 0) /* The last extent is empty and processed. */
409 empty_extent
= false;
414 empty_extent
= false;
415 last_ext_len
= ext_len
;
417 if ( ! sparse_copy (src_fd
, dest_fd
, buf
, buf_size
,
418 sparse_mode
== SPARSE_ALWAYS
,
419 src_name
, dst_name
, ext_len
, &n_read
,
423 dest_pos
= ext_start
+ n_read
;
426 /* If the file ends with unwritten extents not accounted for in the
427 size, then skip processing them, and the associated redundant
428 read() calls which will always return 0. We will need to
429 remove this when we add fallocate() so that we can maintain
430 extents beyond the apparent size. */
431 if (dest_pos
== src_total_size
)
433 scan
.hit_final_extent
= true;
438 /* Release the space allocated to scan->ext_info. */
439 extent_scan_free (&scan
);
442 while (! scan
.hit_final_extent
);
444 /* When the source file ends with a hole, we have to do a little more work,
445 since the above copied only up to and including the final extent.
446 In order to complete the copy, we may have to insert a hole or write
447 zeros in the destination corresponding to the source file's hole-at-EOF.
449 In addition, if the final extent was a block of zeros at EOF and we've
450 just converted them to a hole in the destination, we must call ftruncate
451 here in order to record the proper length in the destination. */
452 if ((dest_pos
< src_total_size
|| wrote_hole_at_eof
)
453 && (sparse_mode
!= SPARSE_NEVER
454 ? ftruncate (dest_fd
, src_total_size
)
455 : ! write_zeros (dest_fd
, src_total_size
- dest_pos
)))
457 error (0, errno
, _("failed to extend %s"), quote (dst_name
));
464 /* FIXME: describe */
465 /* FIXME: rewrite this to use a hash table so we avoid the quadratic
466 performance hit that's probably noticeable only on trees deeper
467 than a few hundred levels. See use of active_dir_map in remove.c */
470 is_ancestor (const struct stat
*sb
, const struct dir_list
*ancestors
)
472 while (ancestors
!= 0)
474 if (ancestors
->ino
== sb
->st_ino
&& ancestors
->dev
== sb
->st_dev
)
476 ancestors
= ancestors
->parent
;
482 errno_unsupported (int err
)
484 return err
== ENOTSUP
|| err
== ENODATA
;
489 copy_attr_error (struct error_context
*ctx ATTRIBUTE_UNUSED
,
490 char const *fmt
, ...)
492 if (!errno_unsupported (errno
))
497 /* use verror module to print error message */
499 verror (0, err
, fmt
, ap
);
505 copy_attr_allerror (struct error_context
*ctx ATTRIBUTE_UNUSED
,
506 char const *fmt
, ...)
511 /* use verror module to print error message */
513 verror (0, err
, fmt
, ap
);
518 copy_attr_quote (struct error_context
*ctx ATTRIBUTE_UNUSED
, char const *str
)
524 copy_attr_free (struct error_context
*ctx ATTRIBUTE_UNUSED
,
525 char const *str ATTRIBUTE_UNUSED
)
529 /* If positive SRC_FD and DST_FD descriptors are passed,
530 then copy by fd, otherwise copy by name. */
533 copy_attr (char const *src_path
, int src_fd
,
534 char const *dst_path
, int dst_fd
, struct cp_options
const *x
)
537 bool all_errors
= (!x
->data_copy_required
|| x
->require_preserve_xattr
);
538 bool some_errors
= (!all_errors
&& !x
->reduce_diagnostics
);
539 struct error_context ctx
=
541 .error
= all_errors
? copy_attr_allerror
: copy_attr_error
,
542 .quote
= copy_attr_quote
,
543 .quote_free
= copy_attr_free
545 if (0 <= src_fd
&& 0 <= dst_fd
)
546 ret
= attr_copy_fd (src_path
, src_fd
, dst_path
, dst_fd
, 0,
547 (all_errors
|| some_errors
? &ctx
: NULL
));
549 ret
= attr_copy_file (src_path
, dst_path
, 0,
550 (all_errors
|| some_errors
? &ctx
: NULL
));
554 #else /* USE_XATTR */
557 copy_attr (char const *src_path ATTRIBUTE_UNUSED
,
558 int src_fd ATTRIBUTE_UNUSED
,
559 char const *dst_path ATTRIBUTE_UNUSED
,
560 int dst_fd ATTRIBUTE_UNUSED
,
561 struct cp_options
const *x ATTRIBUTE_UNUSED
)
565 #endif /* USE_XATTR */
567 /* Read the contents of the directory SRC_NAME_IN, and recursively
568 copy the contents to DST_NAME_IN. NEW_DST is true if
569 DST_NAME_IN is a directory that was created previously in the
570 recursion. SRC_SB and ANCESTORS describe SRC_NAME_IN.
571 Set *COPY_INTO_SELF if SRC_NAME_IN is a parent of
572 (or the same as) DST_NAME_IN; otherwise, clear it.
573 Propagate *FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG from
574 caller to each invocation of copy_internal. Be careful to
575 pass the address of a temporary, and to update
576 *FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG only upon completion.
577 Return true if successful. */
580 copy_dir (char const *src_name_in
, char const *dst_name_in
, bool new_dst
,
581 const struct stat
*src_sb
, struct dir_list
*ancestors
,
582 const struct cp_options
*x
,
583 bool *first_dir_created_per_command_line_arg
,
584 bool *copy_into_self
)
588 struct cp_options non_command_line_options
= *x
;
591 name_space
= savedir (src_name_in
);
592 if (name_space
== NULL
)
594 /* This diagnostic is a bit vague because savedir can fail in
595 several different ways. */
596 error (0, errno
, _("cannot access %s"), quote (src_name_in
));
600 /* For cp's -H option, dereference command line arguments, but do not
601 dereference symlinks that are found via recursive traversal. */
602 if (x
->dereference
== DEREF_COMMAND_LINE_ARGUMENTS
)
603 non_command_line_options
.dereference
= DEREF_NEVER
;
605 bool new_first_dir_created
= false;
607 while (*namep
!= '\0')
609 bool local_copy_into_self
;
610 char *src_name
= file_name_concat (src_name_in
, namep
, NULL
);
611 char *dst_name
= file_name_concat (dst_name_in
, namep
, NULL
);
612 bool first_dir_created
= *first_dir_created_per_command_line_arg
;
614 ok
&= copy_internal (src_name
, dst_name
, new_dst
, src_sb
->st_dev
,
615 ancestors
, &non_command_line_options
, false,
617 &local_copy_into_self
, NULL
);
618 *copy_into_self
|= local_copy_into_self
;
623 /* If we're copying into self, there's no point in continuing,
624 and in fact, that would even infloop, now that we record only
625 the first created directory per command line argument. */
626 if (local_copy_into_self
)
629 new_first_dir_created
|= first_dir_created
;
630 namep
+= strlen (namep
) + 1;
633 *first_dir_created_per_command_line_arg
= new_first_dir_created
;
638 /* Set the owner and owning group of DEST_DESC to the st_uid and
639 st_gid fields of SRC_SB. If DEST_DESC is undefined (-1), set
640 the owner and owning group of DST_NAME instead; for
641 safety prefer lchown if the system supports it since no
642 symbolic links should be involved. DEST_DESC must
643 refer to the same file as DEST_NAME if defined.
644 Upon failure to set both UID and GID, try to set only the GID.
645 NEW_DST is true if the file was newly created; otherwise,
646 DST_SB is the status of the destination.
647 Return 1 if the initial syscall succeeds, 0 if it fails but it's OK
648 not to preserve ownership, -1 otherwise. */
651 set_owner (const struct cp_options
*x
, char const *dst_name
, int dest_desc
,
652 struct stat
const *src_sb
, bool new_dst
,
653 struct stat
const *dst_sb
)
655 uid_t uid
= src_sb
->st_uid
;
656 gid_t gid
= src_sb
->st_gid
;
658 /* Naively changing the ownership of an already-existing file before
659 changing its permissions would create a window of vulnerability if
660 the file's old permissions are too generous for the new owner and
661 group. Avoid the window by first changing to a restrictive
662 temporary mode if necessary. */
664 if (!new_dst
&& (x
->preserve_mode
|| x
->move_mode
|| x
->set_mode
))
666 mode_t old_mode
= dst_sb
->st_mode
;
668 (x
->preserve_mode
|| x
->move_mode
? src_sb
->st_mode
: x
->mode
);
669 mode_t restrictive_temp_mode
= old_mode
& new_mode
& S_IRWXU
;
672 || (old_mode
& CHMOD_MODE_BITS
673 & (~new_mode
| S_ISUID
| S_ISGID
| S_ISVTX
)))
674 && qset_acl (dst_name
, dest_desc
, restrictive_temp_mode
) != 0)
676 if (! owner_failure_ok (x
))
677 error (0, errno
, _("clearing permissions for %s"),
679 return -x
->require_preserve
;
683 if (HAVE_FCHOWN
&& dest_desc
!= -1)
685 if (fchown (dest_desc
, uid
, gid
) == 0)
687 if (errno
== EPERM
|| errno
== EINVAL
)
689 /* We've failed to set *both*. Now, try to set just the group
690 ID, but ignore any failure here, and don't change errno. */
691 int saved_errno
= errno
;
692 ignore_value (fchown (dest_desc
, -1, gid
));
698 if (lchown (dst_name
, uid
, gid
) == 0)
700 if (errno
== EPERM
|| errno
== EINVAL
)
702 /* We've failed to set *both*. Now, try to set just the group
703 ID, but ignore any failure here, and don't change errno. */
704 int saved_errno
= errno
;
705 ignore_value (lchown (dst_name
, -1, gid
));
710 if (! chown_failure_ok (x
))
712 error (0, errno
, _("failed to preserve ownership for %s"),
714 if (x
->require_preserve
)
721 /* Set the st_author field of DEST_DESC to the st_author field of
722 SRC_SB. If DEST_DESC is undefined (-1), set the st_author field
723 of DST_NAME instead. DEST_DESC must refer to the same file as
724 DEST_NAME if defined. */
727 set_author (const char *dst_name
, int dest_desc
, const struct stat
*src_sb
)
729 #if HAVE_STRUCT_STAT_ST_AUTHOR
730 /* FIXME: Modify the following code so that it does not
731 follow symbolic links. */
733 /* Preserve the st_author field. */
734 file_t file
= (dest_desc
< 0
735 ? file_name_lookup (dst_name
, 0, 0)
736 : getdport (dest_desc
));
737 if (file
== MACH_PORT_NULL
)
738 error (0, errno
, _("failed to lookup file %s"), quote (dst_name
));
741 error_t err
= file_chauthor (file
, src_sb
->st_author
);
743 error (0, err
, _("failed to preserve authorship for %s"),
745 mach_port_deallocate (mach_task_self (), file
);
754 /* Change the file mode bits of the file identified by DESC or NAME to MODE.
755 Use DESC if DESC is valid and fchmod is available, NAME otherwise. */
758 fchmod_or_lchmod (int desc
, char const *name
, mode_t mode
)
762 return fchmod (desc
, mode
);
764 return lchmod (name
, mode
);
767 #ifndef HAVE_STRUCT_STAT_ST_BLOCKS
768 # define HAVE_STRUCT_STAT_ST_BLOCKS 0
771 /* Use a heuristic to determine whether stat buffer SB comes from a file
772 with sparse blocks. If the file has fewer blocks than would normally
773 be needed for a file of its size, then at least one of the blocks in
774 the file is a hole. In that case, return true. */
776 is_probably_sparse (struct stat
const *sb
)
778 return (HAVE_STRUCT_STAT_ST_BLOCKS
779 && S_ISREG (sb
->st_mode
)
780 && ST_NBLOCKS (*sb
) < sb
->st_size
/ ST_NBLOCKSIZE
);
784 /* Copy a regular file from SRC_NAME to DST_NAME.
785 If the source file contains holes, copies holes and blocks of zeros
786 in the source file as holes in the destination file.
787 (Holes are read as zeroes by the `read' system call.)
788 When creating the destination, use DST_MODE & ~OMITTED_PERMISSIONS
789 as the third argument in the call to open, adding
790 OMITTED_PERMISSIONS after copying as needed.
791 X provides many option settings.
792 Return true if successful.
793 *NEW_DST is as in copy_internal.
794 SRC_SB is the result of calling XSTAT (aka stat) on SRC_NAME. */
797 copy_reg (char const *src_name
, char const *dst_name
,
798 const struct cp_options
*x
,
799 mode_t dst_mode
, mode_t omitted_permissions
, bool *new_dst
,
800 struct stat
const *src_sb
)
803 char *buf_alloc
= NULL
;
804 char *name_alloc
= NULL
;
808 mode_t src_mode
= src_sb
->st_mode
;
810 struct stat src_open_sb
;
811 bool return_val
= true;
812 bool data_copy_required
= x
->data_copy_required
;
814 source_desc
= open (src_name
,
816 | (x
->dereference
== DEREF_NEVER
? O_NOFOLLOW
: 0)));
819 error (0, errno
, _("cannot open %s for reading"), quote (src_name
));
823 if (fstat (source_desc
, &src_open_sb
) != 0)
825 error (0, errno
, _("cannot fstat %s"), quote (src_name
));
830 /* Compare the source dev/ino from the open file to the incoming,
831 saved ones obtained via a previous call to stat. */
832 if (! SAME_INODE (*src_sb
, src_open_sb
))
835 _("skipping file %s, as it was replaced while being copied"),
841 /* The semantics of the following open calls are mandated
842 by the specs for both cp and mv. */
845 dest_desc
= open (dst_name
, O_WRONLY
| O_TRUNC
| O_BINARY
);
848 /* When using cp --preserve=context to copy to an existing destination,
849 use the default context rather than that of the source. Why?
850 1) the src context may prohibit writing, and
851 2) because it's more consistent to use the same context
852 that is used when the destination file doesn't already exist. */
853 if (x
->preserve_security_context
&& 0 <= dest_desc
)
855 bool all_errors
= (!x
->data_copy_required
856 || x
->require_preserve_context
);
857 bool some_errors
= !all_errors
&& !x
->reduce_diagnostics
;
858 security_context_t con
= NULL
;
860 if (getfscreatecon (&con
) < 0)
862 if (all_errors
|| (some_errors
&& !errno_unsupported (errno
)))
863 error (0, errno
, _("failed to get file system create context"));
864 if (x
->require_preserve_context
)
867 goto close_src_and_dst_desc
;
873 if (fsetfilecon (dest_desc
, con
) < 0)
875 if (all_errors
|| (some_errors
&& !errno_unsupported (errno
)))
877 _("failed to set the security context of %s to %s"),
878 quote_n (0, dst_name
), quote_n (1, con
));
879 if (x
->require_preserve_context
)
883 goto close_src_and_dst_desc
;
890 if (dest_desc
< 0 && x
->unlink_dest_after_failed_open
)
892 if (unlink (dst_name
) != 0)
894 error (0, errno
, _("cannot remove %s"), quote (dst_name
));
899 printf (_("removed %s\n"), quote (dst_name
));
901 /* Tell caller that the destination file was unlinked. */
908 int open_flags
= O_WRONLY
| O_CREAT
| O_BINARY
;
909 dest_desc
= open (dst_name
, open_flags
| O_EXCL
,
910 dst_mode
& ~omitted_permissions
);
913 /* When trying to copy through a dangling destination symlink,
914 the above open fails with EEXIST. If that happens, and
915 lstat'ing the DST_NAME shows that it is a symlink, then we
916 have a problem: trying to resolve this dangling symlink to
917 a directory/destination-entry pair is fundamentally racy,
918 so punt. If x->open_dangling_dest_symlink is set (cp sets
919 that when POSIXLY_CORRECT is set in the environment), simply
920 call open again, but without O_EXCL (potentially dangerous).
921 If not, fail with a diagnostic. These shenanigans are necessary
922 only when copying, i.e., not in move_mode. */
923 if (dest_desc
< 0 && dest_errno
== EEXIST
&& ! x
->move_mode
)
925 struct stat dangling_link_sb
;
926 if (lstat (dst_name
, &dangling_link_sb
) == 0
927 && S_ISLNK (dangling_link_sb
.st_mode
))
929 if (x
->open_dangling_dest_symlink
)
931 dest_desc
= open (dst_name
, open_flags
,
932 dst_mode
& ~omitted_permissions
);
937 error (0, 0, _("not writing through dangling symlink %s"),
945 /* Improve quality of diagnostic when a nonexistent dst_name
946 ends in a slash and open fails with errno == EISDIR. */
947 if (dest_desc
< 0 && dest_errno
== EISDIR
948 && *dst_name
&& dst_name
[strlen (dst_name
) - 1] == '/')
949 dest_errno
= ENOTDIR
;
952 omitted_permissions
= 0;
956 error (0, dest_errno
, _("cannot create regular file %s"),
962 if (fstat (dest_desc
, &sb
) != 0)
964 error (0, errno
, _("cannot fstat %s"), quote (dst_name
));
966 goto close_src_and_dst_desc
;
969 /* --attributes-only overrides --reflink. */
970 if (data_copy_required
&& x
->reflink_mode
)
972 bool clone_ok
= clone_file (dest_desc
, source_desc
) == 0;
973 if (clone_ok
|| x
->reflink_mode
== REFLINK_ALWAYS
)
977 error (0, errno
, _("failed to clone %s"), quote (dst_name
));
979 goto close_src_and_dst_desc
;
981 data_copy_required
= false;
985 if (data_copy_required
)
987 typedef uintptr_t word
;
989 /* Choose a suitable buffer size; it may be adjusted later. */
990 size_t buf_alignment
= lcm (getpagesize (), sizeof (word
));
991 size_t buf_alignment_slop
= sizeof (word
) + buf_alignment
- 1;
992 size_t buf_size
= io_blksize (sb
);
994 /* Deal with sparse files. */
995 bool make_holes
= false;
996 bool sparse_src
= false;
998 if (S_ISREG (sb
.st_mode
))
1000 /* Even with --sparse=always, try to create holes only
1001 if the destination is a regular file. */
1002 if (x
->sparse_mode
== SPARSE_ALWAYS
)
1005 /* Use a heuristic to determine whether SRC_NAME contains any sparse
1006 blocks. If the file has fewer blocks than would normally be
1007 needed for a file of its size, then at least one of the blocks in
1008 the file is a hole. */
1009 sparse_src
= is_probably_sparse (&src_open_sb
);
1010 if (x
->sparse_mode
== SPARSE_AUTO
&& sparse_src
)
1014 /* If not making a sparse file, try to use a more-efficient
1018 /* Compute the least common multiple of the input and output
1019 buffer sizes, adjusting for outlandish values. */
1020 size_t blcm_max
= MIN (SIZE_MAX
, SSIZE_MAX
) - buf_alignment_slop
;
1021 size_t blcm
= buffer_lcm (io_blksize (src_open_sb
), buf_size
,
1024 /* Do not bother with a buffer larger than the input file, plus one
1025 byte to make sure the file has not grown while reading it. */
1026 if (S_ISREG (src_open_sb
.st_mode
) && src_open_sb
.st_size
< buf_size
)
1027 buf_size
= src_open_sb
.st_size
+ 1;
1029 /* However, stick with a block size that is a positive multiple of
1030 blcm, overriding the above adjustments. Watch out for
1032 buf_size
+= blcm
- 1;
1033 buf_size
-= buf_size
% blcm
;
1034 if (buf_size
== 0 || blcm_max
< buf_size
)
1038 /* Make a buffer with space for a sentinel at the end. */
1039 buf_alloc
= xmalloc (buf_size
+ buf_alignment_slop
);
1040 buf
= ptr_align (buf_alloc
, buf_alignment
);
1044 bool normal_copy_required
;
1046 /* Perform an efficient extent-based copy, falling back to the
1047 standard copy only if the initial extent scan fails. If the
1048 '--sparse=never' option is specified, write all data but use
1049 any extents to read more efficiently. */
1050 if (extent_copy (source_desc
, dest_desc
, buf
, buf_size
,
1051 src_open_sb
.st_size
,
1052 S_ISREG (sb
.st_mode
) ? x
->sparse_mode
: SPARSE_NEVER
,
1053 src_name
, dst_name
, &normal_copy_required
))
1054 goto preserve_metadata
;
1056 if (! normal_copy_required
)
1059 goto close_src_and_dst_desc
;
1064 bool wrote_hole_at_eof
;
1065 if ( ! sparse_copy (source_desc
, dest_desc
, buf
, buf_size
,
1066 make_holes
, src_name
, dst_name
,
1067 UINTMAX_MAX
, &n_read
,
1069 || (wrote_hole_at_eof
&&
1070 ftruncate (dest_desc
, n_read
) < 0))
1072 error (0, errno
, _("failed to extend %s"), quote (dst_name
));
1074 goto close_src_and_dst_desc
;
1079 if (x
->preserve_timestamps
)
1081 struct timespec timespec
[2];
1082 timespec
[0] = get_stat_atime (src_sb
);
1083 timespec
[1] = get_stat_mtime (src_sb
);
1085 if (fdutimens (dest_desc
, dst_name
, timespec
) != 0)
1087 error (0, errno
, _("preserving times for %s"), quote (dst_name
));
1088 if (x
->require_preserve
)
1091 goto close_src_and_dst_desc
;
1096 /* Set ownership before xattrs as changing owners will
1097 clear capabilities. */
1098 if (x
->preserve_ownership
&& ! SAME_OWNER_AND_GROUP (*src_sb
, sb
))
1100 switch (set_owner (x
, dst_name
, dest_desc
, src_sb
, *new_dst
, &sb
))
1104 goto close_src_and_dst_desc
;
1107 src_mode
&= ~ (S_ISUID
| S_ISGID
| S_ISVTX
);
1112 /* To allow copying xattrs on read-only files, temporarily chmod u+rw.
1113 This workaround is required as an inode permission check is done
1114 by xattr_permission() in fs/xattr.c of the GNU/Linux kernel tree. */
1115 if (x
->preserve_xattr
)
1117 bool access_changed
= false;
1119 if (!(sb
.st_mode
& S_IWUSR
) && geteuid () != 0)
1120 access_changed
= fchmod_or_lchmod (dest_desc
, dst_name
, 0600) == 0;
1122 if (!copy_attr (src_name
, source_desc
, dst_name
, dest_desc
, x
)
1123 && x
->require_preserve_xattr
)
1127 fchmod_or_lchmod (dest_desc
, dst_name
, dst_mode
& ~omitted_permissions
);
1130 set_author (dst_name
, dest_desc
, src_sb
);
1132 if (x
->preserve_mode
|| x
->move_mode
)
1134 if (copy_acl (src_name
, source_desc
, dst_name
, dest_desc
, src_mode
) != 0
1135 && x
->require_preserve
)
1138 else if (x
->set_mode
)
1140 if (set_acl (dst_name
, dest_desc
, x
->mode
) != 0)
1143 else if (omitted_permissions
)
1145 omitted_permissions
&= ~ cached_umask ();
1146 if (omitted_permissions
1147 && fchmod_or_lchmod (dest_desc
, dst_name
, dst_mode
) != 0)
1149 error (0, errno
, _("preserving permissions for %s"),
1151 if (x
->require_preserve
)
1156 close_src_and_dst_desc
:
1157 if (close (dest_desc
) < 0)
1159 error (0, errno
, _("closing %s"), quote (dst_name
));
1163 if (close (source_desc
) < 0)
1165 error (0, errno
, _("closing %s"), quote (src_name
));
1174 /* Return true if it's ok that the source and destination
1175 files are the `same' by some measure. The goal is to avoid
1176 making the `copy' operation remove both copies of the file
1177 in that case, while still allowing the user to e.g., move or
1178 copy a regular file onto a symlink that points to it.
1179 Try to minimize the cost of this function in the common case.
1180 Set *RETURN_NOW if we've determined that the caller has no more
1181 work to do and should return successfully, right away.
1183 Set *UNLINK_SRC if we've determined that the caller wants to do
1184 `rename (a, b)' where `a' and `b' are distinct hard links to the same
1185 file. In that case, the caller should try to unlink `a' and then return
1186 successfully. Ideally, we wouldn't have to do that, and we'd be
1187 able to rely on rename to remove the source file. However, POSIX
1188 mistakenly requires that such a rename call do *nothing* and return
1192 same_file_ok (char const *src_name
, struct stat
const *src_sb
,
1193 char const *dst_name
, struct stat
const *dst_sb
,
1194 const struct cp_options
*x
, bool *return_now
, bool *unlink_src
)
1196 const struct stat
*src_sb_link
;
1197 const struct stat
*dst_sb_link
;
1198 struct stat tmp_dst_sb
;
1199 struct stat tmp_src_sb
;
1202 bool same
= SAME_INODE (*src_sb
, *dst_sb
);
1204 *return_now
= false;
1205 *unlink_src
= false;
1207 /* FIXME: this should (at the very least) be moved into the following
1208 if-block. More likely, it should be removed, because it inhibits
1209 making backups. But removing it will result in a change in behavior
1210 that will probably have to be documented -- and tests will have to
1212 if (same
&& x
->hard_link
)
1218 if (x
->dereference
== DEREF_NEVER
)
1222 /* If both the source and destination files are symlinks (and we'll
1223 know this here IFF preserving symlinks), then it's ok -- as long
1224 as they are distinct. */
1225 if (S_ISLNK (src_sb
->st_mode
) && S_ISLNK (dst_sb
->st_mode
))
1226 return ! same_name (src_name
, dst_name
);
1228 src_sb_link
= src_sb
;
1229 dst_sb_link
= dst_sb
;
1236 if (lstat (dst_name
, &tmp_dst_sb
) != 0
1237 || lstat (src_name
, &tmp_src_sb
) != 0)
1240 src_sb_link
= &tmp_src_sb
;
1241 dst_sb_link
= &tmp_dst_sb
;
1243 same_link
= SAME_INODE (*src_sb_link
, *dst_sb_link
);
1245 /* If both are symlinks, then it's ok, but only if the destination
1246 will be unlinked before being opened. This is like the test
1247 above, but with the addition of the unlink_dest_before_opening
1248 conjunct because otherwise, with two symlinks to the same target,
1249 we'd end up truncating the source file. */
1250 if (S_ISLNK (src_sb_link
->st_mode
) && S_ISLNK (dst_sb_link
->st_mode
)
1251 && x
->unlink_dest_before_opening
)
1255 /* The backup code ensures there's a copy, so it's usually ok to
1256 remove any destination file. One exception is when both
1257 source and destination are the same directory entry. In that
1258 case, moving the destination file aside (in making the backup)
1259 would also rename the source file and result in an error. */
1260 if (x
->backup_type
!= no_backups
)
1264 /* In copy mode when dereferencing symlinks, if the source is a
1265 symlink and the dest is not, then backing up the destination
1266 (moving it aside) would make it a dangling symlink, and the
1267 subsequent attempt to open it in copy_reg would fail with
1268 a misleading diagnostic. Avoid that by returning zero in
1269 that case so the caller can make cp (or mv when it has to
1270 resort to reading the source file) fail now. */
1272 /* FIXME-note: even with the following kludge, we can still provoke
1273 the offending diagnostic. It's just a little harder to do :-)
1274 $ rm -f a b c; touch c; ln -s c b; ln -s b a; cp -b a b
1275 cp: cannot open `a' for reading: No such file or directory
1276 That's misleading, since a subsequent `ls' shows that `a'
1278 One solution would be to open the source file *before* moving
1279 aside the destination, but that'd involve a big rewrite. */
1281 && x
->dereference
!= DEREF_NEVER
1282 && S_ISLNK (src_sb_link
->st_mode
)
1283 && ! S_ISLNK (dst_sb_link
->st_mode
))
1289 return ! same_name (src_name
, dst_name
);
1293 /* FIXME: use or remove */
1295 /* If we're making a backup, we'll detect the problem case in
1296 copy_reg because SRC_NAME will no longer exist. Allowing
1297 the test to be deferred lets cp do some useful things.
1298 But when creating hardlinks and SRC_NAME is a symlink
1299 but DST_NAME is not we must test anyway. */
1301 || !S_ISLNK (src_sb_link
->st_mode
)
1302 || S_ISLNK (dst_sb_link
->st_mode
))
1305 if (x
->dereference
!= DEREF_NEVER
)
1309 /* They may refer to the same file if we're in move mode and the
1310 target is a symlink. That is ok, since we remove any existing
1311 destination file before opening it -- via `rename' if they're on
1312 the same file system, via `unlink (DST_NAME)' otherwise.
1313 It's also ok if they're distinct hard links to the same file. */
1314 if (x
->move_mode
|| x
->unlink_dest_before_opening
)
1316 if (S_ISLNK (dst_sb_link
->st_mode
))
1320 && 1 < dst_sb_link
->st_nlink
1321 && ! same_name (src_name
, dst_name
))
1332 /* If neither is a symlink, then it's ok as long as they aren't
1333 hard links to the same file. */
1334 if (!S_ISLNK (src_sb_link
->st_mode
) && !S_ISLNK (dst_sb_link
->st_mode
))
1336 if (!SAME_INODE (*src_sb_link
, *dst_sb_link
))
1339 /* If they are the same file, it's ok if we're making hard links. */
1347 /* It's ok to remove a destination symlink. But that works only when we
1348 unlink before opening the destination and when the source and destination
1349 files are on the same partition. */
1350 if (x
->unlink_dest_before_opening
1351 && S_ISLNK (dst_sb_link
->st_mode
))
1352 return dst_sb_link
->st_dev
== src_sb_link
->st_dev
;
1354 if (x
->dereference
== DEREF_NEVER
)
1356 if ( ! S_ISLNK (src_sb_link
->st_mode
))
1357 tmp_src_sb
= *src_sb_link
;
1358 else if (stat (src_name
, &tmp_src_sb
) != 0)
1361 if ( ! S_ISLNK (dst_sb_link
->st_mode
))
1362 tmp_dst_sb
= *dst_sb_link
;
1363 else if (stat (dst_name
, &tmp_dst_sb
) != 0)
1366 if ( ! SAME_INODE (tmp_src_sb
, tmp_dst_sb
))
1369 /* FIXME: shouldn't this be testing whether we're making symlinks? */
1380 /* Return true if FILE, with mode MODE, is writable in the sense of 'mv'.
1381 Always consider a symbolic link to be writable. */
1383 writable_destination (char const *file
, mode_t mode
)
1385 return (S_ISLNK (mode
)
1386 || can_write_any_file ()
1387 || euidaccess (file
, W_OK
) == 0);
1391 overwrite_prompt (char const *dst_name
, struct stat
const *dst_sb
)
1393 if (! writable_destination (dst_name
, dst_sb
->st_mode
))
1395 char perms
[12]; /* "-rwxrwxrwx " ls-style modes. */
1396 strmode (dst_sb
->st_mode
, perms
);
1399 _("%s: try to overwrite %s, overriding mode %04lo (%s)? "),
1400 program_name
, quote (dst_name
),
1401 (unsigned long int) (dst_sb
->st_mode
& CHMOD_MODE_BITS
),
1406 fprintf (stderr
, _("%s: overwrite %s? "),
1407 program_name
, quote (dst_name
));
1411 /* Initialize the hash table implementing a set of F_triple entries
1412 corresponding to destination files. */
1414 dest_info_init (struct cp_options
*x
)
1417 = hash_initialize (DEST_INFO_INITIAL_CAPACITY
,
1424 /* Initialize the hash table implementing a set of F_triple entries
1425 corresponding to source files listed on the command line. */
1427 src_info_init (struct cp_options
*x
)
1430 /* Note that we use triple_hash_no_name here.
1431 Contrast with the use of triple_hash above.
1432 That is necessary because a source file may be specified
1433 in many different ways. We want to warn about this
1439 = hash_initialize (DEST_INFO_INITIAL_CAPACITY
,
1441 triple_hash_no_name
,
1446 /* When effecting a move (e.g., for mv(1)), and given the name DST_NAME
1447 of the destination and a corresponding stat buffer, DST_SB, return
1448 true if the logical `move' operation should _not_ proceed.
1449 Otherwise, return false.
1450 Depending on options specified in X, this code may issue an
1451 interactive prompt asking whether it's ok to overwrite DST_NAME. */
1453 abandon_move (const struct cp_options
*x
,
1454 char const *dst_name
,
1455 struct stat
const *dst_sb
)
1457 assert (x
->move_mode
);
1458 return (x
->interactive
== I_ALWAYS_NO
1459 || ((x
->interactive
== I_ASK_USER
1460 || (x
->interactive
== I_UNSPECIFIED
1462 && ! writable_destination (dst_name
, dst_sb
->st_mode
)))
1463 && (overwrite_prompt (dst_name
, dst_sb
), 1)
1467 /* Print --verbose output on standard output, e.g. `new' -> `old'.
1468 If BACKUP_DST_NAME is non-NULL, then also indicate that it is
1469 the name of a backup file. */
1471 emit_verbose (char const *src
, char const *dst
, char const *backup_dst_name
)
1473 printf ("%s -> %s", quote_n (0, src
), quote_n (1, dst
));
1474 if (backup_dst_name
)
1475 printf (_(" (backup: %s)"), quote (backup_dst_name
));
1479 /* A wrapper around "setfscreatecon (NULL)" that exits upon failure. */
1481 restore_default_fscreatecon_or_die (void)
1483 if (setfscreatecon (NULL
) != 0)
1484 error (EXIT_FAILURE
, errno
,
1485 _("failed to restore the default file creation context"));
1488 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
1489 any type. NEW_DST should be true if the file DST_NAME cannot
1490 exist because its parent directory was just created; NEW_DST should
1491 be false if DST_NAME might already exist. DEVICE is the device
1492 number of the parent directory, or 0 if the parent of this file is
1493 not known. ANCESTORS points to a linked, null terminated list of
1494 devices and inodes of parent directories of SRC_NAME. COMMAND_LINE_ARG
1495 is true iff SRC_NAME was specified on the command line.
1496 FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG is both input and output.
1497 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
1498 same as) DST_NAME; otherwise, clear it.
1499 Return true if successful. */
1501 copy_internal (char const *src_name
, char const *dst_name
,
1504 struct dir_list
*ancestors
,
1505 const struct cp_options
*x
,
1506 bool command_line_arg
,
1507 bool *first_dir_created_per_command_line_arg
,
1508 bool *copy_into_self
,
1509 bool *rename_succeeded
)
1514 mode_t dst_mode
IF_LINT ( = 0);
1515 mode_t dst_mode_bits
;
1516 mode_t omitted_permissions
;
1517 bool restore_dst_mode
= false;
1518 char *earlier_file
= NULL
;
1519 char *dst_backup
= NULL
;
1520 bool backup_succeeded
= false;
1522 bool copied_as_regular
= false;
1523 bool dest_is_symlink
= false;
1524 bool have_dst_lstat
= false;
1526 if (x
->move_mode
&& rename_succeeded
)
1527 *rename_succeeded
= false;
1529 *copy_into_self
= false;
1531 if (XSTAT (x
, src_name
, &src_sb
) != 0)
1533 error (0, errno
, _("cannot stat %s"), quote (src_name
));
1537 src_mode
= src_sb
.st_mode
;
1539 if (S_ISDIR (src_mode
) && !x
->recursive
)
1541 error (0, 0, _("omitting directory %s"), quote (src_name
));
1545 /* Detect the case in which the same source file appears more than
1546 once on the command line and no backup option has been selected.
1547 If so, simply warn and don't copy it the second time.
1548 This check is enabled only if x->src_info is non-NULL. */
1549 if (command_line_arg
)
1551 if ( ! S_ISDIR (src_sb
.st_mode
)
1552 && x
->backup_type
== no_backups
1553 && seen_file (x
->src_info
, src_name
, &src_sb
))
1555 error (0, 0, _("warning: source file %s specified more than once"),
1560 record_file (x
->src_info
, src_name
, &src_sb
);
1565 /* Regular files can be created by writing through symbolic
1566 links, but other files cannot. So use stat on the
1567 destination when copying a regular file, and lstat otherwise.
1568 However, if we intend to unlink or remove the destination
1569 first, use lstat, since a copy won't actually be made to the
1570 destination in that case. */
1572 ((S_ISREG (src_mode
)
1573 || (x
->copy_as_regular
1574 && ! (S_ISDIR (src_mode
) || S_ISLNK (src_mode
))))
1575 && ! (x
->move_mode
|| x
->symbolic_link
|| x
->hard_link
1576 || x
->backup_type
!= no_backups
1577 || x
->unlink_dest_before_opening
));
1579 ? stat (dst_name
, &dst_sb
)
1580 : lstat (dst_name
, &dst_sb
))
1583 if (errno
!= ENOENT
)
1585 error (0, errno
, _("cannot stat %s"), quote (dst_name
));
1594 { /* Here, we know that dst_name exists, at least to the point
1595 that it is stat'able or lstat'able. */
1599 have_dst_lstat
= !use_stat
;
1600 if (! same_file_ok (src_name
, &src_sb
, dst_name
, &dst_sb
,
1601 x
, &return_now
, &unlink_src
))
1603 error (0, 0, _("%s and %s are the same file"),
1604 quote_n (0, src_name
), quote_n (1, dst_name
));
1608 if (!S_ISDIR (src_mode
) && x
->update
)
1610 /* When preserving time stamps (but not moving within a file
1611 system), don't worry if the destination time stamp is
1612 less than the source merely because of time stamp
1614 int options
= ((x
->preserve_timestamps
1616 && dst_sb
.st_dev
== src_sb
.st_dev
))
1617 ? UTIMECMP_TRUNCATE_SOURCE
1620 if (0 <= utimecmp (dst_name
, &dst_sb
, &src_sb
, options
))
1622 /* We're using --update and the destination is not older
1623 than the source, so do not copy or move. Pretend the
1624 rename succeeded, so the caller (if it's mv) doesn't
1625 end up removing the source file. */
1626 if (rename_succeeded
)
1627 *rename_succeeded
= true;
1632 /* When there is an existing destination file, we may end up
1633 returning early, and hence not copying/moving the file.
1634 This may be due to an interactive `negative' reply to the
1635 prompt about the existing file. It may also be due to the
1636 use of the --reply=no option.
1638 cp and mv treat -i and -f differently. */
1641 if (abandon_move (x
, dst_name
, &dst_sb
)
1642 || (unlink_src
&& unlink (src_name
) == 0))
1644 /* Pretend the rename succeeded, so the caller (mv)
1645 doesn't end up removing the source file. */
1646 if (rename_succeeded
)
1647 *rename_succeeded
= true;
1648 if (unlink_src
&& x
->verbose
)
1649 printf (_("removed %s\n"), quote (src_name
));
1654 error (0, errno
, _("cannot remove %s"), quote (src_name
));
1660 if (! S_ISDIR (src_mode
)
1661 && (x
->interactive
== I_ALWAYS_NO
1662 || (x
->interactive
== I_ASK_USER
1663 && (overwrite_prompt (dst_name
, &dst_sb
), 1)
1671 if (!S_ISDIR (dst_sb
.st_mode
))
1673 if (S_ISDIR (src_mode
))
1675 if (x
->move_mode
&& x
->backup_type
!= no_backups
)
1677 /* Moving a directory onto an existing
1678 non-directory is ok only with --backup. */
1683 _("cannot overwrite non-directory %s with directory %s"),
1684 quote_n (0, dst_name
), quote_n (1, src_name
));
1689 /* Don't let the user destroy their data, even if they try hard:
1690 This mv command must fail (likewise for cp):
1691 rm -rf a b c; mkdir a b c; touch a/f b/f; mv a/f b/f c
1692 Otherwise, the contents of b/f would be lost.
1693 In the case of `cp', b/f would be lost if the user simulated
1694 a move using cp and rm.
1695 Note that it works fine if you use --backup=numbered. */
1696 if (command_line_arg
1697 && x
->backup_type
!= numbered_backups
1698 && seen_file (x
->dest_info
, dst_name
, &dst_sb
))
1701 _("will not overwrite just-created %s with %s"),
1702 quote_n (0, dst_name
), quote_n (1, src_name
));
1707 if (!S_ISDIR (src_mode
))
1709 if (S_ISDIR (dst_sb
.st_mode
))
1711 if (x
->move_mode
&& x
->backup_type
!= no_backups
)
1713 /* Moving a non-directory onto an existing
1714 directory is ok only with --backup. */
1719 _("cannot overwrite directory %s with non-directory"),
1728 /* Don't allow user to move a directory onto a non-directory. */
1729 if (S_ISDIR (src_sb
.st_mode
) && !S_ISDIR (dst_sb
.st_mode
)
1730 && x
->backup_type
== no_backups
)
1733 _("cannot move directory onto non-directory: %s -> %s"),
1734 quote_n (0, src_name
), quote_n (0, dst_name
));
1739 if (x
->backup_type
!= no_backups
1740 /* Don't try to back up a destination if the last
1741 component of src_name is "." or "..". */
1742 && ! dot_or_dotdot (last_component (src_name
))
1743 /* Create a backup of each destination directory in move mode,
1744 but not in copy mode. FIXME: it might make sense to add an
1745 option to suppress backup creation also for move mode.
1746 That would let one use mv to merge new content into an
1747 existing hierarchy. */
1748 && (x
->move_mode
|| ! S_ISDIR (dst_sb
.st_mode
)))
1750 char *tmp_backup
= find_backup_file_name (dst_name
,
1753 /* Detect (and fail) when creating the backup file would
1754 destroy the source file. Before, running the commands
1755 cd /tmp; rm -f a a~; : > a; echo A > a~; cp --b=simple a~ a
1756 would leave two zero-length files: a and a~. */
1757 /* FIXME: but simply change e.g., the final a~ to `./a~'
1758 and the source will still be destroyed. */
1759 if (STREQ (tmp_backup
, src_name
))
1763 ? _("backing up %s would destroy source; %s not moved")
1764 : _("backing up %s would destroy source; %s not copied"));
1766 quote_n (0, dst_name
),
1767 quote_n (1, src_name
));
1773 Using alloca for a file name that may be arbitrarily
1774 long is not recommended. In fact, even forming such a name
1775 should be discouraged. Eventually, this code will be rewritten
1776 to use fts, so using alloca here will be less of a problem. */
1777 ASSIGN_STRDUPA (dst_backup
, tmp_backup
);
1779 if (rename (dst_name
, dst_backup
) != 0)
1781 if (errno
!= ENOENT
)
1783 error (0, errno
, _("cannot backup %s"), quote (dst_name
));
1793 backup_succeeded
= true;
1797 else if (! S_ISDIR (dst_sb
.st_mode
)
1798 /* Never unlink dst_name when in move mode. */
1800 && (x
->unlink_dest_before_opening
1801 || (x
->preserve_links
&& 1 < dst_sb
.st_nlink
)
1802 || (x
->dereference
== DEREF_NEVER
1803 && ! S_ISREG (src_sb
.st_mode
))
1806 if (unlink (dst_name
) != 0 && errno
!= ENOENT
)
1808 error (0, errno
, _("cannot remove %s"), quote (dst_name
));
1813 printf (_("removed %s\n"), quote (dst_name
));
1818 /* Ensure we don't try to copy through a symlink that was
1819 created by a prior call to this function. */
1820 if (command_line_arg
1823 && x
->backup_type
== no_backups
)
1825 bool lstat_ok
= true;
1826 struct stat tmp_buf
;
1827 struct stat
*dst_lstat_sb
;
1829 /* If we called lstat above, good: use that data.
1830 Otherwise, call lstat here, in case dst_name is a symlink. */
1832 dst_lstat_sb
= &dst_sb
;
1835 if (lstat (dst_name
, &tmp_buf
) == 0)
1836 dst_lstat_sb
= &tmp_buf
;
1841 /* Never copy through a symlink we've just created. */
1843 && S_ISLNK (dst_lstat_sb
->st_mode
)
1844 && seen_file (x
->dest_info
, dst_name
, dst_lstat_sb
))
1847 _("will not copy %s through just-created symlink %s"),
1848 quote_n (0, src_name
), quote_n (1, dst_name
));
1853 /* If the source is a directory, we don't always create the destination
1854 directory. So --verbose should not announce anything until we're
1855 sure we'll create a directory. */
1856 if (x
->verbose
&& !S_ISDIR (src_mode
))
1857 emit_verbose (src_name
, dst_name
, backup_succeeded
? dst_backup
: NULL
);
1859 /* Associate the destination file name with the source device and inode
1860 so that if we encounter a matching dev/ino pair in the source tree
1861 we can arrange to create a hard link between the corresponding names
1862 in the destination tree.
1864 When using the --link (-l) option, there is no need to take special
1865 measures, because (barring race conditions) files that are hard-linked
1866 in the source tree will also be hard-linked in the destination tree.
1868 Sometimes, when preserving links, we have to record dev/ino even
1869 though st_nlink == 1:
1870 - when in move_mode, since we may be moving a group of N hard-linked
1871 files (via two or more command line arguments) to a different
1872 partition; the links may be distributed among the command line
1873 arguments (possibly hierarchies) so that the link count of
1874 the final, once-linked source file is reduced to 1 when it is
1875 considered below. But in this case (for mv) we don't need to
1876 incur the expense of recording the dev/ino => name mapping; all we
1877 really need is a lookup, to see if the dev/ino pair has already
1879 - when using -H and processing a command line argument;
1880 that command line argument could be a symlink pointing to another
1881 command line argument. With `cp -H --preserve=link', we hard-link
1882 those two destination files.
1883 - likewise for -L except that it applies to all files, not just
1884 command line arguments.
1886 Also, with --recursive, record dev/ino of each command-line directory.
1887 We'll use that info to detect this problem: cp -R dir dir. */
1889 if (x
->move_mode
&& src_sb
.st_nlink
== 1)
1891 earlier_file
= src_to_dest_lookup (src_sb
.st_ino
, src_sb
.st_dev
);
1893 else if (x
->preserve_links
1895 && (1 < src_sb
.st_nlink
1896 || (command_line_arg
1897 && x
->dereference
== DEREF_COMMAND_LINE_ARGUMENTS
)
1898 || x
->dereference
== DEREF_ALWAYS
))
1900 earlier_file
= remember_copied (dst_name
, src_sb
.st_ino
, src_sb
.st_dev
);
1902 else if (x
->recursive
&& S_ISDIR (src_mode
))
1904 if (command_line_arg
)
1905 earlier_file
= remember_copied (dst_name
, src_sb
.st_ino
, src_sb
.st_dev
);
1907 earlier_file
= src_to_dest_lookup (src_sb
.st_ino
, src_sb
.st_dev
);
1910 /* Did we copy this inode somewhere else (in this command line argument)
1911 and therefore this is a second hard link to the inode? */
1915 /* Avoid damaging the destination file system by refusing to preserve
1916 hard-linked directories (which are found at least in Netapp snapshot
1918 if (S_ISDIR (src_mode
))
1920 /* If src_name and earlier_file refer to the same directory entry,
1921 then warn about copying a directory into itself. */
1922 if (same_name (src_name
, earlier_file
))
1924 error (0, 0, _("cannot copy a directory, %s, into itself, %s"),
1925 quote_n (0, top_level_src_name
),
1926 quote_n (1, top_level_dst_name
));
1927 *copy_into_self
= true;
1930 else if (x
->dereference
== DEREF_ALWAYS
)
1932 /* This happens when e.g., encountering a directory for the
1933 second or subsequent time via symlinks when cp is invoked
1934 with -R and -L. E.g.,
1935 rm -rf a b c d; mkdir a b c d; ln -s ../c a; ln -s ../c b;
1941 error (0, 0, _("will not create hard link %s to directory %s"),
1942 quote_n (0, dst_name
), quote_n (1, earlier_file
));
1948 /* We want to guarantee that symlinks are not followed. */
1949 bool link_failed
= (linkat (AT_FDCWD
, earlier_file
, AT_FDCWD
,
1952 /* If the link failed because of an existing destination,
1953 remove that file and then call link again. */
1954 if (link_failed
&& errno
== EEXIST
)
1956 if (unlink (dst_name
) != 0)
1958 error (0, errno
, _("cannot remove %s"), quote (dst_name
));
1962 printf (_("removed %s\n"), quote (dst_name
));
1963 link_failed
= (linkat (AT_FDCWD
, earlier_file
, AT_FDCWD
,
1969 error (0, errno
, _("cannot create hard link %s to %s"),
1970 quote_n (0, dst_name
), quote_n (1, earlier_file
));
1980 if (rename (src_name
, dst_name
) == 0)
1982 if (x
->verbose
&& S_ISDIR (src_mode
))
1983 emit_verbose (src_name
, dst_name
,
1984 backup_succeeded
? dst_backup
: NULL
);
1986 if (rename_succeeded
)
1987 *rename_succeeded
= true;
1989 if (command_line_arg
)
1991 /* Record destination dev/ino/name, so that if we are asked
1992 to overwrite that file again, we can detect it and fail. */
1993 /* It's fine to use the _source_ stat buffer (src_sb) to get the
1994 _destination_ dev/ino, since the rename above can't have
1995 changed those, and `mv' always uses lstat.
1996 We could limit it further by operating
1997 only on non-directories. */
1998 record_file (x
->dest_info
, dst_name
, &src_sb
);
2004 /* FIXME: someday, consider what to do when moving a directory into
2005 itself but when source and destination are on different devices. */
2007 /* This happens when attempting to rename a directory to a
2008 subdirectory of itself. */
2009 if (errno
== EINVAL
)
2011 /* FIXME: this is a little fragile in that it relies on rename(2)
2012 failing with a specific errno value. Expect problems on
2013 non-POSIX systems. */
2014 error (0, 0, _("cannot move %s to a subdirectory of itself, %s"),
2015 quote_n (0, top_level_src_name
),
2016 quote_n (1, top_level_dst_name
));
2018 /* Note that there is no need to call forget_created here,
2019 (compare with the other calls in this file) since the
2020 destination directory didn't exist before. */
2022 *copy_into_self
= true;
2023 /* FIXME-cleanup: Don't return true here; adjust mv.c accordingly.
2024 The only caller that uses this code (mv.c) ends up setting its
2025 exit status to nonzero when copy_into_self is nonzero. */
2029 /* WARNING: there probably exist systems for which an inter-device
2030 rename fails with a value of errno not handled here.
2031 If/as those are reported, add them to the condition below.
2032 If this happens to you, please do the following and send the output
2033 to the bug-reporting address (e.g., in the output of cp --help):
2034 touch k; perl -e 'rename "k","/tmp/k" or print "$!(",$!+0,")\n"'
2035 where your current directory is on one partion and /tmp is the other.
2036 Also, please try to find the E* errno macro name corresponding to
2037 the diagnostic and parenthesized integer, and include that in your
2038 e-mail. One way to do that is to run a command like this
2039 find /usr/include/. -type f \
2040 | xargs grep 'define.*\<E[A-Z]*\>.*\<18\>' /dev/null
2041 where you'd replace `18' with the integer in parentheses that
2042 was output from the perl one-liner above.
2043 If necessary, of course, change `/tmp' to some other directory. */
2046 /* There are many ways this can happen due to a race condition.
2047 When something happens between the initial XSTAT and the
2048 subsequent rename, we can get many different types of errors.
2049 For example, if the destination is initially a non-directory
2050 or non-existent, but it is created as a directory, the rename
2051 fails. If two `mv' commands try to rename the same file at
2052 about the same time, one will succeed and the other will fail.
2053 If the permissions on the directory containing the source or
2054 destination file are made too restrictive, the rename will
2057 _("cannot move %s to %s"),
2058 quote_n (0, src_name
), quote_n (1, dst_name
));
2059 forget_created (src_sb
.st_ino
, src_sb
.st_dev
);
2063 /* The rename attempt has failed. Remove any existing destination
2064 file so that a cross-device `mv' acts as if it were really using
2065 the rename syscall. */
2066 if (unlink (dst_name
) != 0 && errno
!= ENOENT
)
2069 _("inter-device move failed: %s to %s; unable to remove target"),
2070 quote_n (0, src_name
), quote_n (1, dst_name
));
2071 forget_created (src_sb
.st_ino
, src_sb
.st_dev
);
2078 /* If the ownership might change, or if it is a directory (whose
2079 special mode bits may change after the directory is created),
2080 omit some permissions at first, so unauthorized users cannot nip
2081 in before the file is ready. */
2082 dst_mode_bits
= (x
->set_mode
? x
->mode
: src_mode
) & CHMOD_MODE_BITS
;
2083 omitted_permissions
=
2085 & (x
->preserve_ownership
? S_IRWXG
| S_IRWXO
2086 : S_ISDIR (src_mode
) ? S_IWGRP
| S_IWOTH
2091 if (x
->preserve_security_context
)
2093 bool all_errors
= !x
->data_copy_required
|| x
->require_preserve_context
;
2094 bool some_errors
= !all_errors
&& !x
->reduce_diagnostics
;
2095 security_context_t con
;
2097 if (0 <= lgetfilecon (src_name
, &con
))
2099 if (setfscreatecon (con
) < 0)
2101 if (all_errors
|| (some_errors
&& !errno_unsupported (errno
)))
2103 _("failed to set default file creation context to %s"),
2105 if (x
->require_preserve_context
)
2115 if (all_errors
|| (some_errors
&& !errno_unsupported (errno
)))
2118 _("failed to get security context of %s"),
2121 if (x
->require_preserve_context
)
2126 if (S_ISDIR (src_mode
))
2128 struct dir_list
*dir
;
2130 /* If this directory has been copied before during the
2131 recursion, there is a symbolic link to an ancestor
2132 directory of the symbolic link. It is impossible to
2133 continue to copy this, unless we've got an infinite disk. */
2135 if (is_ancestor (&src_sb
, ancestors
))
2137 error (0, 0, _("cannot copy cyclic symbolic link %s"),
2142 /* Insert the current directory in the list of parents. */
2144 dir
= alloca (sizeof *dir
);
2145 dir
->parent
= ancestors
;
2146 dir
->ino
= src_sb
.st_ino
;
2147 dir
->dev
= src_sb
.st_dev
;
2149 if (new_dst
|| !S_ISDIR (dst_sb
.st_mode
))
2151 /* POSIX says mkdir's behavior is implementation-defined when
2152 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
2153 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
2154 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
2155 if (mkdir (dst_name
, dst_mode_bits
& ~omitted_permissions
) != 0)
2157 error (0, errno
, _("cannot create directory %s"),
2162 /* We need search and write permissions to the new directory
2163 for writing the directory's contents. Check if these
2164 permissions are there. */
2166 if (lstat (dst_name
, &dst_sb
) != 0)
2168 error (0, errno
, _("cannot stat %s"), quote (dst_name
));
2171 else if ((dst_sb
.st_mode
& S_IRWXU
) != S_IRWXU
)
2173 /* Make the new directory searchable and writable. */
2175 dst_mode
= dst_sb
.st_mode
;
2176 restore_dst_mode
= true;
2178 if (lchmod (dst_name
, dst_mode
| S_IRWXU
) != 0)
2180 error (0, errno
, _("setting permissions for %s"),
2186 /* Record the created directory's inode and device numbers into
2187 the search structure, so that we can avoid copying it again.
2188 Do this only for the first directory that is created for each
2189 source command line argument. */
2190 if (!*first_dir_created_per_command_line_arg
)
2192 remember_copied (dst_name
, dst_sb
.st_ino
, dst_sb
.st_dev
);
2193 *first_dir_created_per_command_line_arg
= true;
2197 emit_verbose (src_name
, dst_name
, NULL
);
2200 /* Decide whether to copy the contents of the directory. */
2201 if (x
->one_file_system
&& device
!= 0 && device
!= src_sb
.st_dev
)
2203 /* Here, we are crossing a file system boundary and cp's -x option
2204 is in effect: so don't copy the contents of this directory. */
2208 /* Copy the contents of the directory. Don't just return if
2209 this fails -- otherwise, the failure to read a single file
2210 in a source directory would cause the containing destination
2211 directory not to have owner/perms set properly. */
2212 delayed_ok
= copy_dir (src_name
, dst_name
, new_dst
, &src_sb
, dir
, x
,
2213 first_dir_created_per_command_line_arg
,
2217 else if (x
->symbolic_link
)
2219 dest_is_symlink
= true;
2220 if (*src_name
!= '/')
2222 /* Check that DST_NAME denotes a file in the current directory. */
2224 struct stat dst_parent_sb
;
2226 bool in_current_dir
;
2228 dst_parent
= dir_name (dst_name
);
2230 in_current_dir
= (STREQ (".", dst_parent
)
2231 /* If either stat call fails, it's ok not to report
2232 the failure and say dst_name is in the current
2233 directory. Other things will fail later. */
2234 || stat (".", &dot_sb
) != 0
2235 || stat (dst_parent
, &dst_parent_sb
) != 0
2236 || SAME_INODE (dot_sb
, dst_parent_sb
));
2239 if (! in_current_dir
)
2242 _("%s: can make relative symbolic links only in current directory"),
2247 if (symlink (src_name
, dst_name
) != 0)
2249 error (0, errno
, _("cannot create symbolic link %s to %s"),
2250 quote_n (0, dst_name
), quote_n (1, src_name
));
2255 /* POSIX 2008 states that it is implementation-defined whether
2256 link() on a symlink creates a hard-link to the symlink, or only
2257 to the referent (effectively dereferencing the symlink) (POSIX
2258 2001 required the latter behavior, although many systems provided
2259 the former). Yet cp, invoked with `--link --no-dereference',
2260 should not follow the link. We can approximate the desired
2261 behavior by skipping this hard-link creating block and instead
2262 copying the symlink, via the `S_ISLNK'- copying code below.
2263 LINK_FOLLOWS_SYMLINKS is tri-state; if it is -1, we don't know
2264 how link() behaves, so we use the fallback case for safety.
2266 Note gnulib's linkat module, guarantees that the symlink is not
2267 dereferenced. However its emulation currently doesn't maintain
2268 timestamps or ownership so we only call it when we know the
2269 emulation will not be needed. */
2270 else if (x
->hard_link
2271 && !(LINK_FOLLOWS_SYMLINKS
&& S_ISLNK (src_mode
)
2272 && x
->dereference
== DEREF_NEVER
))
2274 if (linkat (AT_FDCWD
, src_name
, AT_FDCWD
, dst_name
, 0))
2276 error (0, errno
, _("cannot create link %s"), quote (dst_name
));
2280 else if (S_ISREG (src_mode
)
2281 || (x
->copy_as_regular
&& !S_ISLNK (src_mode
)))
2283 copied_as_regular
= true;
2284 /* POSIX says the permission bits of the source file must be
2285 used as the 3rd argument in the open call. Historical
2286 practice passed all the source mode bits to 'open', but the extra
2287 bits were ignored, so it should be the same either way. */
2288 if (! copy_reg (src_name
, dst_name
, x
, src_mode
& S_IRWXUGO
,
2289 omitted_permissions
, &new_dst
, &src_sb
))
2292 else if (S_ISFIFO (src_mode
))
2294 /* Use mknod, rather than mkfifo, because the former preserves
2295 the special mode bits of a fifo on Solaris 10, while mkfifo
2296 does not. But fall back on mkfifo, because on some BSD systems,
2297 mknod always fails when asked to create a FIFO. */
2298 if (mknod (dst_name
, src_mode
& ~omitted_permissions
, 0) != 0)
2299 if (mkfifo (dst_name
, src_mode
& ~S_IFIFO
& ~omitted_permissions
) != 0)
2301 error (0, errno
, _("cannot create fifo %s"), quote (dst_name
));
2305 else if (S_ISBLK (src_mode
) || S_ISCHR (src_mode
) || S_ISSOCK (src_mode
))
2307 if (mknod (dst_name
, src_mode
& ~omitted_permissions
, src_sb
.st_rdev
)
2310 error (0, errno
, _("cannot create special file %s"),
2315 else if (S_ISLNK (src_mode
))
2317 char *src_link_val
= areadlink_with_size (src_name
, src_sb
.st_size
);
2318 dest_is_symlink
= true;
2319 if (src_link_val
== NULL
)
2321 error (0, errno
, _("cannot read symbolic link %s"), quote (src_name
));
2325 if (symlink (src_link_val
, dst_name
) == 0)
2326 free (src_link_val
);
2329 int saved_errno
= errno
;
2330 bool same_link
= false;
2331 if (x
->update
&& !new_dst
&& S_ISLNK (dst_sb
.st_mode
)
2332 && dst_sb
.st_size
== strlen (src_link_val
))
2334 /* See if the destination is already the desired symlink.
2335 FIXME: This behavior isn't documented, and seems wrong
2336 in some cases, e.g., if the destination symlink has the
2337 wrong ownership, permissions, or time stamps. */
2338 char *dest_link_val
=
2339 areadlink_with_size (dst_name
, dst_sb
.st_size
);
2340 if (dest_link_val
&& STREQ (dest_link_val
, src_link_val
))
2342 free (dest_link_val
);
2344 free (src_link_val
);
2348 error (0, saved_errno
, _("cannot create symbolic link %s"),
2354 if (x
->preserve_security_context
)
2355 restore_default_fscreatecon_or_die ();
2357 if (x
->preserve_ownership
)
2359 /* Preserve the owner and group of the just-`copied'
2360 symbolic link, if possible. */
2362 && lchown (dst_name
, src_sb
.st_uid
, src_sb
.st_gid
) != 0
2363 && ! chown_failure_ok (x
))
2365 error (0, errno
, _("failed to preserve ownership for %s"),
2371 /* Can't preserve ownership of symlinks.
2372 FIXME: maybe give a warning or even error for symlinks
2373 in directories with the sticky bit set -- there, not
2374 preserving owner/group is a potential security problem. */
2380 error (0, 0, _("%s has unknown file type"), quote (src_name
));
2384 if (command_line_arg
&& x
->dest_info
)
2386 /* Now that the destination file is very likely to exist,
2387 add its info to the set. */
2389 if (lstat (dst_name
, &sb
) == 0)
2390 record_file (x
->dest_info
, dst_name
, &sb
);
2393 /* If we've just created a hard-link due to cp's --link option,
2395 if (x
->hard_link
&& ! S_ISDIR (src_mode
)
2396 && !(LINK_FOLLOWS_SYMLINKS
&& S_ISLNK (src_mode
)
2397 && x
->dereference
== DEREF_NEVER
))
2400 if (copied_as_regular
)
2403 /* POSIX says that `cp -p' must restore the following:
2405 - setuid, setgid bits
2407 If it fails to restore any of those, we may give a warning but
2408 the destination must not be removed.
2409 FIXME: implement the above. */
2411 /* Adjust the times (and if possible, ownership) for the copy.
2412 chown turns off set[ug]id bits for non-root,
2413 so do the chmod last. */
2415 if (x
->preserve_timestamps
)
2417 struct timespec timespec
[2];
2418 timespec
[0] = get_stat_atime (&src_sb
);
2419 timespec
[1] = get_stat_mtime (&src_sb
);
2421 if ((dest_is_symlink
2422 ? utimens_symlink (dst_name
, timespec
)
2423 : utimens (dst_name
, timespec
))
2426 error (0, errno
, _("preserving times for %s"), quote (dst_name
));
2427 if (x
->require_preserve
)
2432 /* The operations beyond this point may dereference a symlink. */
2433 if (dest_is_symlink
)
2436 /* Avoid calling chown if we know it's not necessary. */
2437 if (x
->preserve_ownership
2438 && (new_dst
|| !SAME_OWNER_AND_GROUP (src_sb
, dst_sb
)))
2440 switch (set_owner (x
, dst_name
, -1, &src_sb
, new_dst
, &dst_sb
))
2446 src_mode
&= ~ (S_ISUID
| S_ISGID
| S_ISVTX
);
2451 set_author (dst_name
, -1, &src_sb
);
2453 if (x
->preserve_xattr
&& ! copy_attr (src_name
, -1, dst_name
, -1, x
)
2454 && x
->require_preserve_xattr
)
2457 if (x
->preserve_mode
|| x
->move_mode
)
2459 if (copy_acl (src_name
, -1, dst_name
, -1, src_mode
) != 0
2460 && x
->require_preserve
)
2463 else if (x
->set_mode
)
2465 if (set_acl (dst_name
, -1, x
->mode
) != 0)
2470 if (omitted_permissions
)
2472 omitted_permissions
&= ~ cached_umask ();
2474 if (omitted_permissions
&& !restore_dst_mode
)
2476 /* Permissions were deliberately omitted when the file
2477 was created due to security concerns. See whether
2478 they need to be re-added now. It'd be faster to omit
2479 the lstat, but deducing the current destination mode
2480 is tricky in the presence of implementation-defined
2481 rules for special mode bits. */
2482 if (new_dst
&& lstat (dst_name
, &dst_sb
) != 0)
2484 error (0, errno
, _("cannot stat %s"), quote (dst_name
));
2487 dst_mode
= dst_sb
.st_mode
;
2488 if (omitted_permissions
& ~dst_mode
)
2489 restore_dst_mode
= true;
2493 if (restore_dst_mode
)
2495 if (lchmod (dst_name
, dst_mode
| omitted_permissions
) != 0)
2497 error (0, errno
, _("preserving permissions for %s"),
2499 if (x
->require_preserve
)
2509 if (x
->preserve_security_context
)
2510 restore_default_fscreatecon_or_die ();
2512 /* We have failed to create the destination file.
2513 If we've just added a dev/ino entry via the remember_copied
2514 call above (i.e., unless we've just failed to create a hard link),
2515 remove the entry associating the source dev/ino with the
2516 destination file name, so we don't try to `preserve' a link
2517 to a file we didn't create. */
2518 if (earlier_file
== NULL
)
2519 forget_created (src_sb
.st_ino
, src_sb
.st_dev
);
2523 if (rename (dst_backup
, dst_name
) != 0)
2524 error (0, errno
, _("cannot un-backup %s"), quote (dst_name
));
2528 printf (_("%s -> %s (unbackup)\n"),
2529 quote_n (0, dst_backup
), quote_n (1, dst_name
));
2536 valid_options (const struct cp_options
*co
)
2538 assert (co
!= NULL
);
2539 assert (VALID_BACKUP_TYPE (co
->backup_type
));
2540 assert (VALID_SPARSE_MODE (co
->sparse_mode
));
2541 assert (VALID_REFLINK_MODE (co
->reflink_mode
));
2542 assert (!(co
->hard_link
&& co
->symbolic_link
));
2544 (co
->reflink_mode
== REFLINK_ALWAYS
2545 && co
->sparse_mode
!= SPARSE_AUTO
));
2549 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
2550 any type. NONEXISTENT_DST should be true if the file DST_NAME
2551 is known not to exist (e.g., because its parent directory was just
2552 created); NONEXISTENT_DST should be false if DST_NAME might already
2553 exist. OPTIONS is ... FIXME-describe
2554 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
2555 same as) DST_NAME; otherwise, set clear it.
2556 Return true if successful. */
2559 copy (char const *src_name
, char const *dst_name
,
2560 bool nonexistent_dst
, const struct cp_options
*options
,
2561 bool *copy_into_self
, bool *rename_succeeded
)
2563 assert (valid_options (options
));
2565 /* Record the file names: they're used in case of error, when copying
2566 a directory into itself. I don't like to make these tools do *any*
2567 extra work in the common case when that work is solely to handle
2568 exceptional cases, but in this case, I don't see a way to derive the
2569 top level source and destination directory names where they're used.
2570 An alternative is to use COPY_INTO_SELF and print the diagnostic
2571 from every caller -- but I don't want to do that. */
2572 top_level_src_name
= src_name
;
2573 top_level_dst_name
= dst_name
;
2575 bool first_dir_created_per_command_line_arg
= false;
2576 return copy_internal (src_name
, dst_name
, nonexistent_dst
, 0, NULL
,
2578 &first_dir_created_per_command_line_arg
,
2579 copy_into_self
, rename_succeeded
);
2582 /* Set *X to the default options for a value of type struct cp_options. */
2585 cp_options_default (struct cp_options
*x
)
2587 memset (x
, 0, sizeof *x
);
2588 #ifdef PRIV_FILE_CHOWN
2590 priv_set_t
*pset
= priv_allocset ();
2593 if (getppriv (PRIV_EFFECTIVE
, pset
) == 0)
2595 x
->chown_privileges
= priv_ismember (pset
, PRIV_FILE_CHOWN
);
2596 x
->owner_privileges
= priv_ismember (pset
, PRIV_FILE_OWNER
);
2598 priv_freeset (pset
);
2601 x
->chown_privileges
= x
->owner_privileges
= (geteuid () == 0);
2605 /* Return true if it's OK for chown to fail, where errno is
2606 the error number that chown failed with and X is the copying
2610 chown_failure_ok (struct cp_options
const *x
)
2612 /* If non-root uses -p, it's ok if we can't preserve ownership.
2613 But root probably wants to know, e.g. if NFS disallows it,
2614 or if the target system doesn't support file ownership. */
2616 return ((errno
== EPERM
|| errno
== EINVAL
) && !x
->chown_privileges
);
2619 /* Similarly, return true if it's OK for chmod and similar operations
2620 to fail, where errno is the error number that chmod failed with and
2621 X is the copying option set. */
2624 owner_failure_ok (struct cp_options
const *x
)
2626 return ((errno
== EPERM
|| errno
== EINVAL
) && !x
->owner_privileges
);
2629 /* Return the user's umask, caching the result. */
2634 static mode_t mask
= (mode_t
) -1;
2635 if (mask
== (mode_t
) -1)