1 /* copy.c -- core functions for copying files and directories
2 Copyright (C) 1989-2013 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"
66 # include <attr/error_context.h>
67 # include <attr/libattr.h>
73 # define HAVE_FCHOWN false
74 # define fchown(fd, uid, gid) (-1)
78 # define HAVE_LCHOWN false
79 # define lchown(name, uid, gid) chown (name, uid, gid)
84 rpl_mkfifo (char const *file
, mode_t mode
)
89 # define mkfifo rpl_mkfifo
96 #define SAME_OWNER(A, B) ((A).st_uid == (B).st_uid)
97 #define SAME_GROUP(A, B) ((A).st_gid == (B).st_gid)
98 #define SAME_OWNER_AND_GROUP(A, B) (SAME_OWNER (A, B) && SAME_GROUP (A, B))
102 struct dir_list
*parent
;
107 /* Initial size of the cp.dest_info hash table. */
108 #define DEST_INFO_INITIAL_CAPACITY 61
110 static bool copy_internal (char const *src_name
, char const *dst_name
,
111 bool new_dst
, dev_t device
,
112 struct dir_list
*ancestors
,
113 const struct cp_options
*x
,
114 bool command_line_arg
,
115 bool *first_dir_created_per_command_line_arg
,
116 bool *copy_into_self
,
117 bool *rename_succeeded
);
118 static bool owner_failure_ok (struct cp_options
const *x
);
120 /* Pointers to the file names: they're used in the diagnostic that is issued
121 when we detect the user is trying to copy a directory into itself. */
122 static char const *top_level_src_name
;
123 static char const *top_level_dst_name
;
125 /* Set the timestamp of symlink, FILE, to TIMESPEC.
126 If this system lacks support for that, simply return 0. */
128 utimens_symlink (char const *file
, struct timespec
const *timespec
)
130 int err
= lutimens (file
, timespec
);
131 /* When configuring on a system with new headers and libraries, and
132 running on one with a kernel that is old enough to lack the syscall,
133 utimensat fails with ENOSYS. Ignore that. */
134 if (err
&& errno
== ENOSYS
)
139 /* Copy the regular file open on SRC_FD/SRC_NAME to DST_FD/DST_NAME,
140 honoring the MAKE_HOLES setting and using the BUF_SIZE-byte buffer
141 BUF for temporary storage. Copy no more than MAX_N_READ bytes.
142 Return true upon successful completion;
143 print a diagnostic and return false upon error.
144 Note that for best results, BUF should be "well"-aligned.
145 BUF must have sizeof(uintptr_t)-1 bytes of additional space
146 beyond BUF[BUF_SIZE-1].
147 Set *LAST_WRITE_MADE_HOLE to true if the final operation on
148 DEST_FD introduced a hole. Set *TOTAL_N_READ to the number of
151 sparse_copy (int src_fd
, int dest_fd
, char *buf
, size_t buf_size
,
153 char const *src_name
, char const *dst_name
,
154 uintmax_t max_n_read
, off_t
*total_n_read
,
155 bool *last_write_made_hole
)
157 *last_write_made_hole
= false;
162 bool make_hole
= false;
164 ssize_t n_read
= read (src_fd
, buf
, MIN (max_n_read
, buf_size
));
169 error (0, errno
, _("error reading %s"), quote (src_name
));
174 max_n_read
-= n_read
;
175 *total_n_read
+= n_read
;
179 /* Sentinel required by is_nul(). */
182 typedef uintptr_t word
;
183 /* Usually, buf[n_read] is not the byte just before a "word"
184 (aka uintptr_t) boundary. In that case, the word-oriented
185 test below (*wp++ == 0) would read some uninitialized bytes
186 after the sentinel. To avoid false-positive reports about
187 this condition (e.g., from a tool like valgrind), set the
188 remaining bytes -- to any value. */
189 memset (buf
+ n_read
+ 1, 0, sizeof (word
) - 1);
192 if ((make_hole
= is_nul (buf
, n_read
)))
194 if (lseek (dest_fd
, n_read
, SEEK_CUR
) < 0)
196 error (0, errno
, _("cannot lseek %s"), quote (dst_name
));
205 if (full_write (dest_fd
, buf
, n
) != n
)
207 error (0, errno
, _("error writing %s"), quote (dst_name
));
211 /* It is tempting to return early here upon a short read from a
212 regular file. That would save the final read syscall for each
213 file. Unfortunately that doesn't work for certain files in
214 /proc with linux kernels from at least 2.6.9 .. 2.6.29. */
217 *last_write_made_hole
= make_hole
;
223 /* Perform the O(1) btrfs clone operation, if possible.
224 Upon success, return 0. Otherwise, return -1 and set errno. */
226 clone_file (int dest_fd
, int src_fd
)
229 # undef BTRFS_IOCTL_MAGIC
230 # define BTRFS_IOCTL_MAGIC 0x94
231 # undef BTRFS_IOC_CLONE
232 # define BTRFS_IOC_CLONE _IOW (BTRFS_IOCTL_MAGIC, 9, int)
233 return ioctl (dest_fd
, BTRFS_IOC_CLONE
, src_fd
);
242 /* Write N_BYTES zero bytes to file descriptor FD. Return true if successful.
243 Upon write failure, set errno and return false. */
245 write_zeros (int fd
, uint64_t n_bytes
)
248 static size_t nz
= IO_BUFSIZE
;
250 /* Attempt to use a relatively large calloc'd source buffer for
251 efficiency, but if that allocation fails, resort to a smaller
252 statically allocated one. */
255 static char fallback
[1024];
256 zeros
= calloc (nz
, 1);
260 nz
= sizeof fallback
;
266 uint64_t n
= MIN (nz
, n_bytes
);
267 if ((full_write (fd
, zeros
, n
)) != n
)
275 /* Perform an efficient extent copy, if possible. This avoids
276 the overhead of detecting holes in hole-introducing/preserving
277 copy, and thus makes copying sparse files much more efficient.
278 Upon a successful copy, return true. If the initial extent scan
279 fails, set *NORMAL_COPY_REQUIRED to true and return false.
280 Upon any other failure, set *NORMAL_COPY_REQUIRED to false and
283 extent_copy (int src_fd
, int dest_fd
, char *buf
, size_t buf_size
,
284 off_t src_total_size
, enum Sparse_type sparse_mode
,
285 char const *src_name
, char const *dst_name
,
286 bool *require_normal_copy
)
288 struct extent_scan scan
;
289 off_t last_ext_start
= 0;
290 uint64_t last_ext_len
= 0;
292 /* Keep track of the output position.
293 We may need this at the end, for a final ftruncate. */
296 extent_scan_init (src_fd
, &scan
);
298 *require_normal_copy
= false;
299 bool wrote_hole_at_eof
= true;
302 bool ok
= extent_scan_read (&scan
);
305 if (scan
.hit_final_extent
)
308 if (scan
.initial_scan_failed
)
310 *require_normal_copy
= true;
314 error (0, errno
, _("%s: failed to get extents info"),
320 bool empty_extent
= false;
321 for (i
= 0; i
< scan
.ei_count
|| empty_extent
; i
++)
327 if (i
< scan
.ei_count
)
329 ext_start
= scan
.ext_info
[i
].ext_logical
;
330 ext_len
= scan
.ext_info
[i
].ext_length
;
332 else /* empty extent at EOF. */
335 ext_start
= last_ext_start
+ scan
.ext_info
[i
].ext_length
;
339 hole_size
= ext_start
- last_ext_start
- last_ext_len
;
341 wrote_hole_at_eof
= false;
345 if (lseek (src_fd
, ext_start
, SEEK_SET
) < 0)
347 error (0, errno
, _("cannot lseek %s"), quote (src_name
));
349 extent_scan_free (&scan
);
353 if ((empty_extent
&& sparse_mode
== SPARSE_ALWAYS
)
354 || (!empty_extent
&& sparse_mode
!= SPARSE_NEVER
))
356 if (lseek (dest_fd
, ext_start
, SEEK_SET
) < 0)
358 error (0, errno
, _("cannot lseek %s"), quote (dst_name
));
361 wrote_hole_at_eof
= true;
365 /* When not inducing holes and when there is a hole between
366 the end of the previous extent and the beginning of the
367 current one, write zeros to the destination file. */
368 off_t nzeros
= hole_size
;
370 nzeros
= MIN (src_total_size
- dest_pos
, hole_size
);
372 if (! write_zeros (dest_fd
, nzeros
))
374 error (0, errno
, _("%s: write failed"), quote (dst_name
));
378 dest_pos
= MIN (src_total_size
, ext_start
);
382 last_ext_start
= ext_start
;
384 /* Treat an unwritten but allocated extent much like a hole.
385 I.E. don't read, but don't convert to a hole in the destination,
386 unless SPARSE_ALWAYS. */
387 /* For now, do not treat FIEMAP_EXTENT_UNWRITTEN specially,
388 because that (in combination with no sync) would lead to data
389 loss at least on XFS and ext4 when using 2.6.39-rc3 kernels. */
390 if (0 && (scan
.ext_info
[i
].ext_flags
& FIEMAP_EXTENT_UNWRITTEN
))
394 if (ext_len
== 0) /* The last extent is empty and processed. */
395 empty_extent
= false;
400 empty_extent
= false;
401 last_ext_len
= ext_len
;
403 if ( ! sparse_copy (src_fd
, dest_fd
, buf
, buf_size
,
404 sparse_mode
== SPARSE_ALWAYS
,
405 src_name
, dst_name
, ext_len
, &n_read
,
409 dest_pos
= ext_start
+ n_read
;
412 /* If the file ends with unwritten extents not accounted for in the
413 size, then skip processing them, and the associated redundant
414 read() calls which will always return 0. We will need to
415 remove this when we add fallocate() so that we can maintain
416 extents beyond the apparent size. */
417 if (dest_pos
== src_total_size
)
419 scan
.hit_final_extent
= true;
424 /* Release the space allocated to scan->ext_info. */
425 extent_scan_free (&scan
);
428 while (! scan
.hit_final_extent
);
430 /* When the source file ends with a hole, we have to do a little more work,
431 since the above copied only up to and including the final extent.
432 In order to complete the copy, we may have to insert a hole or write
433 zeros in the destination corresponding to the source file's hole-at-EOF.
435 In addition, if the final extent was a block of zeros at EOF and we've
436 just converted them to a hole in the destination, we must call ftruncate
437 here in order to record the proper length in the destination. */
438 if ((dest_pos
< src_total_size
|| wrote_hole_at_eof
)
439 && (sparse_mode
!= SPARSE_NEVER
440 ? ftruncate (dest_fd
, src_total_size
)
441 : ! write_zeros (dest_fd
, src_total_size
- dest_pos
)))
443 error (0, errno
, _("failed to extend %s"), quote (dst_name
));
450 /* FIXME: describe */
451 /* FIXME: rewrite this to use a hash table so we avoid the quadratic
452 performance hit that's probably noticeable only on trees deeper
453 than a few hundred levels. See use of active_dir_map in remove.c */
455 static bool _GL_ATTRIBUTE_PURE
456 is_ancestor (const struct stat
*sb
, const struct dir_list
*ancestors
)
458 while (ancestors
!= 0)
460 if (ancestors
->ino
== sb
->st_ino
&& ancestors
->dev
== sb
->st_dev
)
462 ancestors
= ancestors
->parent
;
468 errno_unsupported (int err
)
470 return err
== ENOTSUP
|| err
== ENODATA
;
475 copy_attr_error (struct error_context
*ctx _GL_UNUSED
,
476 char const *fmt
, ...)
478 if (!errno_unsupported (errno
))
483 /* use verror module to print error message */
485 verror (0, err
, fmt
, ap
);
491 copy_attr_allerror (struct error_context
*ctx _GL_UNUSED
,
492 char const *fmt
, ...)
497 /* use verror module to print error message */
499 verror (0, err
, fmt
, ap
);
504 copy_attr_quote (struct error_context
*ctx _GL_UNUSED
, char const *str
)
510 copy_attr_free (struct error_context
*ctx _GL_UNUSED
,
511 char const *str _GL_UNUSED
)
515 /* If positive SRC_FD and DST_FD descriptors are passed,
516 then copy by fd, otherwise copy by name. */
519 copy_attr (char const *src_path
, int src_fd
,
520 char const *dst_path
, int dst_fd
, struct cp_options
const *x
)
523 bool all_errors
= (!x
->data_copy_required
|| x
->require_preserve_xattr
);
524 bool some_errors
= (!all_errors
&& !x
->reduce_diagnostics
);
525 struct error_context ctx
=
527 .error
= all_errors
? copy_attr_allerror
: copy_attr_error
,
528 .quote
= copy_attr_quote
,
529 .quote_free
= copy_attr_free
531 if (0 <= src_fd
&& 0 <= dst_fd
)
532 ret
= attr_copy_fd (src_path
, src_fd
, dst_path
, dst_fd
, 0,
533 (all_errors
|| some_errors
? &ctx
: NULL
));
535 ret
= attr_copy_file (src_path
, dst_path
, 0,
536 (all_errors
|| some_errors
? &ctx
: NULL
));
540 #else /* USE_XATTR */
543 copy_attr (char const *src_path _GL_UNUSED
,
544 int src_fd _GL_UNUSED
,
545 char const *dst_path _GL_UNUSED
,
546 int dst_fd _GL_UNUSED
,
547 struct cp_options
const *x _GL_UNUSED
)
551 #endif /* USE_XATTR */
553 /* Read the contents of the directory SRC_NAME_IN, and recursively
554 copy the contents to DST_NAME_IN. NEW_DST is true if
555 DST_NAME_IN is a directory that was created previously in the
556 recursion. SRC_SB and ANCESTORS describe SRC_NAME_IN.
557 Set *COPY_INTO_SELF if SRC_NAME_IN is a parent of
558 (or the same as) DST_NAME_IN; otherwise, clear it.
559 Propagate *FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG from
560 caller to each invocation of copy_internal. Be careful to
561 pass the address of a temporary, and to update
562 *FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG only upon completion.
563 Return true if successful. */
566 copy_dir (char const *src_name_in
, char const *dst_name_in
, bool new_dst
,
567 const struct stat
*src_sb
, struct dir_list
*ancestors
,
568 const struct cp_options
*x
,
569 bool *first_dir_created_per_command_line_arg
,
570 bool *copy_into_self
)
574 struct cp_options non_command_line_options
= *x
;
577 name_space
= savedir (src_name_in
);
578 if (name_space
== NULL
)
580 /* This diagnostic is a bit vague because savedir can fail in
581 several different ways. */
582 error (0, errno
, _("cannot access %s"), quote (src_name_in
));
586 /* For cp's -H option, dereference command line arguments, but do not
587 dereference symlinks that are found via recursive traversal. */
588 if (x
->dereference
== DEREF_COMMAND_LINE_ARGUMENTS
)
589 non_command_line_options
.dereference
= DEREF_NEVER
;
591 bool new_first_dir_created
= false;
593 while (*namep
!= '\0')
595 bool local_copy_into_self
;
596 char *src_name
= file_name_concat (src_name_in
, namep
, NULL
);
597 char *dst_name
= file_name_concat (dst_name_in
, namep
, NULL
);
598 bool first_dir_created
= *first_dir_created_per_command_line_arg
;
600 ok
&= copy_internal (src_name
, dst_name
, new_dst
, src_sb
->st_dev
,
601 ancestors
, &non_command_line_options
, false,
603 &local_copy_into_self
, NULL
);
604 *copy_into_self
|= local_copy_into_self
;
609 /* If we're copying into self, there's no point in continuing,
610 and in fact, that would even infloop, now that we record only
611 the first created directory per command line argument. */
612 if (local_copy_into_self
)
615 new_first_dir_created
|= first_dir_created
;
616 namep
+= strlen (namep
) + 1;
619 *first_dir_created_per_command_line_arg
= new_first_dir_created
;
624 /* Set the owner and owning group of DEST_DESC to the st_uid and
625 st_gid fields of SRC_SB. If DEST_DESC is undefined (-1), set
626 the owner and owning group of DST_NAME instead; for
627 safety prefer lchown if the system supports it since no
628 symbolic links should be involved. DEST_DESC must
629 refer to the same file as DEST_NAME if defined.
630 Upon failure to set both UID and GID, try to set only the GID.
631 NEW_DST is true if the file was newly created; otherwise,
632 DST_SB is the status of the destination.
633 Return 1 if the initial syscall succeeds, 0 if it fails but it's OK
634 not to preserve ownership, -1 otherwise. */
637 set_owner (const struct cp_options
*x
, char const *dst_name
, int dest_desc
,
638 struct stat
const *src_sb
, bool new_dst
,
639 struct stat
const *dst_sb
)
641 uid_t uid
= src_sb
->st_uid
;
642 gid_t gid
= src_sb
->st_gid
;
644 /* Naively changing the ownership of an already-existing file before
645 changing its permissions would create a window of vulnerability if
646 the file's old permissions are too generous for the new owner and
647 group. Avoid the window by first changing to a restrictive
648 temporary mode if necessary. */
650 if (!new_dst
&& (x
->preserve_mode
|| x
->move_mode
|| x
->set_mode
))
652 mode_t old_mode
= dst_sb
->st_mode
;
654 (x
->preserve_mode
|| x
->move_mode
? src_sb
->st_mode
: x
->mode
);
655 mode_t restrictive_temp_mode
= old_mode
& new_mode
& S_IRWXU
;
658 || (old_mode
& CHMOD_MODE_BITS
659 & (~new_mode
| S_ISUID
| S_ISGID
| S_ISVTX
)))
660 && qset_acl (dst_name
, dest_desc
, restrictive_temp_mode
) != 0)
662 if (! owner_failure_ok (x
))
663 error (0, errno
, _("clearing permissions for %s"),
665 return -x
->require_preserve
;
669 if (HAVE_FCHOWN
&& dest_desc
!= -1)
671 if (fchown (dest_desc
, uid
, gid
) == 0)
673 if (errno
== EPERM
|| errno
== EINVAL
)
675 /* We've failed to set *both*. Now, try to set just the group
676 ID, but ignore any failure here, and don't change errno. */
677 int saved_errno
= errno
;
678 ignore_value (fchown (dest_desc
, -1, gid
));
684 if (lchown (dst_name
, uid
, gid
) == 0)
686 if (errno
== EPERM
|| errno
== EINVAL
)
688 /* We've failed to set *both*. Now, try to set just the group
689 ID, but ignore any failure here, and don't change errno. */
690 int saved_errno
= errno
;
691 ignore_value (lchown (dst_name
, -1, gid
));
696 if (! chown_failure_ok (x
))
698 error (0, errno
, _("failed to preserve ownership for %s"),
700 if (x
->require_preserve
)
707 /* Set the st_author field of DEST_DESC to the st_author field of
708 SRC_SB. If DEST_DESC is undefined (-1), set the st_author field
709 of DST_NAME instead. DEST_DESC must refer to the same file as
710 DEST_NAME if defined. */
713 set_author (const char *dst_name
, int dest_desc
, const struct stat
*src_sb
)
715 #if HAVE_STRUCT_STAT_ST_AUTHOR
716 /* FIXME: Modify the following code so that it does not
717 follow symbolic links. */
719 /* Preserve the st_author field. */
720 file_t file
= (dest_desc
< 0
721 ? file_name_lookup (dst_name
, 0, 0)
722 : getdport (dest_desc
));
723 if (file
== MACH_PORT_NULL
)
724 error (0, errno
, _("failed to lookup file %s"), quote (dst_name
));
727 error_t err
= file_chauthor (file
, src_sb
->st_author
);
729 error (0, err
, _("failed to preserve authorship for %s"),
731 mach_port_deallocate (mach_task_self (), file
);
740 /* Change the file mode bits of the file identified by DESC or NAME to MODE.
741 Use DESC if DESC is valid and fchmod is available, NAME otherwise. */
744 fchmod_or_lchmod (int desc
, char const *name
, mode_t mode
)
748 return fchmod (desc
, mode
);
750 return lchmod (name
, mode
);
753 #ifndef HAVE_STRUCT_STAT_ST_BLOCKS
754 # define HAVE_STRUCT_STAT_ST_BLOCKS 0
757 /* Use a heuristic to determine whether stat buffer SB comes from a file
758 with sparse blocks. If the file has fewer blocks than would normally
759 be needed for a file of its size, then at least one of the blocks in
760 the file is a hole. In that case, return true. */
762 is_probably_sparse (struct stat
const *sb
)
764 return (HAVE_STRUCT_STAT_ST_BLOCKS
765 && S_ISREG (sb
->st_mode
)
766 && ST_NBLOCKS (*sb
) < sb
->st_size
/ ST_NBLOCKSIZE
);
770 /* Copy a regular file from SRC_NAME to DST_NAME.
771 If the source file contains holes, copies holes and blocks of zeros
772 in the source file as holes in the destination file.
773 (Holes are read as zeroes by the 'read' system call.)
774 When creating the destination, use DST_MODE & ~OMITTED_PERMISSIONS
775 as the third argument in the call to open, adding
776 OMITTED_PERMISSIONS after copying as needed.
777 X provides many option settings.
778 Return true if successful.
779 *NEW_DST is as in copy_internal.
780 SRC_SB is the result of calling XSTAT (aka stat) on SRC_NAME. */
783 copy_reg (char const *src_name
, char const *dst_name
,
784 const struct cp_options
*x
,
785 mode_t dst_mode
, mode_t omitted_permissions
, bool *new_dst
,
786 struct stat
const *src_sb
)
789 char *buf_alloc
= NULL
;
790 char *name_alloc
= NULL
;
794 mode_t src_mode
= src_sb
->st_mode
;
796 struct stat src_open_sb
;
797 bool return_val
= true;
798 bool data_copy_required
= x
->data_copy_required
;
800 source_desc
= open (src_name
,
802 | (x
->dereference
== DEREF_NEVER
? O_NOFOLLOW
: 0)));
805 error (0, errno
, _("cannot open %s for reading"), quote (src_name
));
809 if (fstat (source_desc
, &src_open_sb
) != 0)
811 error (0, errno
, _("cannot fstat %s"), quote (src_name
));
816 /* Compare the source dev/ino from the open file to the incoming,
817 saved ones obtained via a previous call to stat. */
818 if (! SAME_INODE (*src_sb
, src_open_sb
))
821 _("skipping file %s, as it was replaced while being copied"),
827 /* The semantics of the following open calls are mandated
828 by the specs for both cp and mv. */
832 O_WRONLY
| O_BINARY
| (x
->data_copy_required
? O_TRUNC
: 0);
833 dest_desc
= open (dst_name
, open_flags
);
836 /* When using cp --preserve=context to copy to an existing destination,
837 use the default context rather than that of the source. Why?
838 1) the src context may prohibit writing, and
839 2) because it's more consistent to use the same context
840 that is used when the destination file doesn't already exist. */
841 if (x
->preserve_security_context
&& 0 <= dest_desc
)
843 bool all_errors
= (!x
->data_copy_required
844 || x
->require_preserve_context
);
845 bool some_errors
= !all_errors
&& !x
->reduce_diagnostics
;
846 security_context_t con
= NULL
;
848 if (getfscreatecon (&con
) < 0)
850 if (all_errors
|| (some_errors
&& !errno_unsupported (errno
)))
851 error (0, errno
, _("failed to get file system create context"));
852 if (x
->require_preserve_context
)
855 goto close_src_and_dst_desc
;
861 if (fsetfilecon (dest_desc
, con
) < 0)
863 if (all_errors
|| (some_errors
&& !errno_unsupported (errno
)))
865 _("failed to set the security context of %s to %s"),
866 quote_n (0, dst_name
), quote_n (1, con
));
867 if (x
->require_preserve_context
)
871 goto close_src_and_dst_desc
;
878 if (dest_desc
< 0 && x
->unlink_dest_after_failed_open
)
880 if (unlink (dst_name
) != 0)
882 error (0, errno
, _("cannot remove %s"), quote (dst_name
));
887 printf (_("removed %s\n"), quote (dst_name
));
889 /* Tell caller that the destination file was unlinked. */
898 int open_flags
= O_WRONLY
| O_CREAT
| O_BINARY
;
899 dest_desc
= open (dst_name
, open_flags
| O_EXCL
,
900 dst_mode
& ~omitted_permissions
);
903 /* When trying to copy through a dangling destination symlink,
904 the above open fails with EEXIST. If that happens, and
905 lstat'ing the DST_NAME shows that it is a symlink, then we
906 have a problem: trying to resolve this dangling symlink to
907 a directory/destination-entry pair is fundamentally racy,
908 so punt. If x->open_dangling_dest_symlink is set (cp sets
909 that when POSIXLY_CORRECT is set in the environment), simply
910 call open again, but without O_EXCL (potentially dangerous).
911 If not, fail with a diagnostic. These shenanigans are necessary
912 only when copying, i.e., not in move_mode. */
913 if (dest_desc
< 0 && dest_errno
== EEXIST
&& ! x
->move_mode
)
915 struct stat dangling_link_sb
;
916 if (lstat (dst_name
, &dangling_link_sb
) == 0
917 && S_ISLNK (dangling_link_sb
.st_mode
))
919 if (x
->open_dangling_dest_symlink
)
921 dest_desc
= open (dst_name
, open_flags
,
922 dst_mode
& ~omitted_permissions
);
927 error (0, 0, _("not writing through dangling symlink %s"),
935 /* Improve quality of diagnostic when a nonexistent dst_name
936 ends in a slash and open fails with errno == EISDIR. */
937 if (dest_desc
< 0 && dest_errno
== EISDIR
938 && *dst_name
&& dst_name
[strlen (dst_name
) - 1] == '/')
939 dest_errno
= ENOTDIR
;
943 omitted_permissions
= 0;
948 /* If we've just failed due to ENOENT for an ostensibly preexisting
949 destination (*new_dst was 0), that's a bit of a contradiction/race:
950 the prior stat/lstat said the file existed (*new_dst was 0), yet
951 the subsequent open-existing-file failed with ENOENT. With NFS,
952 the race window is wider still, since its meta-data caching tends
953 to make the stat succeed for a just-removed remote file, while the
954 more-definitive initial open call will fail with ENOENT. When this
955 situation arises, we attempt to open again, but this time with
956 O_CREAT. Do this only when not in move-mode, since when handling
957 a cross-device move, we must never open an existing destination. */
958 if (dest_errno
== ENOENT
&& ! *new_dst
&& ! x
->move_mode
)
961 goto open_with_O_CREAT
;
964 /* Otherwise, it's an error. */
965 error (0, dest_errno
, _("cannot create regular file %s"),
971 if (fstat (dest_desc
, &sb
) != 0)
973 error (0, errno
, _("cannot fstat %s"), quote (dst_name
));
975 goto close_src_and_dst_desc
;
978 /* --attributes-only overrides --reflink. */
979 if (data_copy_required
&& x
->reflink_mode
)
981 bool clone_ok
= clone_file (dest_desc
, source_desc
) == 0;
982 if (clone_ok
|| x
->reflink_mode
== REFLINK_ALWAYS
)
986 error (0, errno
, _("failed to clone %s from %s"),
987 quote_n (0, dst_name
), quote_n (1, src_name
));
989 goto close_src_and_dst_desc
;
991 data_copy_required
= false;
995 if (data_copy_required
)
997 typedef uintptr_t word
;
999 /* Choose a suitable buffer size; it may be adjusted later. */
1000 size_t buf_alignment
= lcm (getpagesize (), sizeof (word
));
1001 size_t buf_alignment_slop
= sizeof (word
) + buf_alignment
- 1;
1002 size_t buf_size
= io_blksize (sb
);
1004 fdadvise (source_desc
, 0, 0, FADVISE_SEQUENTIAL
);
1006 /* Deal with sparse files. */
1007 bool make_holes
= false;
1008 bool sparse_src
= false;
1010 if (S_ISREG (sb
.st_mode
))
1012 /* Even with --sparse=always, try to create holes only
1013 if the destination is a regular file. */
1014 if (x
->sparse_mode
== SPARSE_ALWAYS
)
1017 /* Use a heuristic to determine whether SRC_NAME contains any sparse
1018 blocks. If the file has fewer blocks than would normally be
1019 needed for a file of its size, then at least one of the blocks in
1020 the file is a hole. */
1021 sparse_src
= is_probably_sparse (&src_open_sb
);
1022 if (x
->sparse_mode
== SPARSE_AUTO
&& sparse_src
)
1026 /* If not making a sparse file, try to use a more-efficient
1030 /* Compute the least common multiple of the input and output
1031 buffer sizes, adjusting for outlandish values. */
1032 size_t blcm_max
= MIN (SIZE_MAX
, SSIZE_MAX
) - buf_alignment_slop
;
1033 size_t blcm
= buffer_lcm (io_blksize (src_open_sb
), buf_size
,
1036 /* Do not bother with a buffer larger than the input file, plus one
1037 byte to make sure the file has not grown while reading it. */
1038 if (S_ISREG (src_open_sb
.st_mode
) && src_open_sb
.st_size
< buf_size
)
1039 buf_size
= src_open_sb
.st_size
+ 1;
1041 /* However, stick with a block size that is a positive multiple of
1042 blcm, overriding the above adjustments. Watch out for
1044 buf_size
+= blcm
- 1;
1045 buf_size
-= buf_size
% blcm
;
1046 if (buf_size
== 0 || blcm_max
< buf_size
)
1050 /* Make a buffer with space for a sentinel at the end. */
1051 buf_alloc
= xmalloc (buf_size
+ buf_alignment_slop
);
1052 buf
= ptr_align (buf_alloc
, buf_alignment
);
1056 bool normal_copy_required
;
1058 /* Perform an efficient extent-based copy, falling back to the
1059 standard copy only if the initial extent scan fails. If the
1060 '--sparse=never' option is specified, write all data but use
1061 any extents to read more efficiently. */
1062 if (extent_copy (source_desc
, dest_desc
, buf
, buf_size
,
1063 src_open_sb
.st_size
,
1064 S_ISREG (sb
.st_mode
) ? x
->sparse_mode
: SPARSE_NEVER
,
1065 src_name
, dst_name
, &normal_copy_required
))
1066 goto preserve_metadata
;
1068 if (! normal_copy_required
)
1071 goto close_src_and_dst_desc
;
1076 bool wrote_hole_at_eof
;
1077 if ( ! sparse_copy (source_desc
, dest_desc
, buf
, buf_size
,
1078 make_holes
, src_name
, dst_name
,
1079 UINTMAX_MAX
, &n_read
,
1081 || (wrote_hole_at_eof
1082 && ftruncate (dest_desc
, n_read
) < 0))
1084 error (0, errno
, _("failed to extend %s"), quote (dst_name
));
1086 goto close_src_and_dst_desc
;
1091 if (x
->preserve_timestamps
)
1093 struct timespec timespec
[2];
1094 timespec
[0] = get_stat_atime (src_sb
);
1095 timespec
[1] = get_stat_mtime (src_sb
);
1097 if (fdutimens (dest_desc
, dst_name
, timespec
) != 0)
1099 error (0, errno
, _("preserving times for %s"), quote (dst_name
));
1100 if (x
->require_preserve
)
1103 goto close_src_and_dst_desc
;
1108 /* Set ownership before xattrs as changing owners will
1109 clear capabilities. */
1110 if (x
->preserve_ownership
&& ! SAME_OWNER_AND_GROUP (*src_sb
, sb
))
1112 switch (set_owner (x
, dst_name
, dest_desc
, src_sb
, *new_dst
, &sb
))
1116 goto close_src_and_dst_desc
;
1119 src_mode
&= ~ (S_ISUID
| S_ISGID
| S_ISVTX
);
1124 /* To allow copying xattrs on read-only files, temporarily chmod u+rw.
1125 This workaround is required as an inode permission check is done
1126 by xattr_permission() in fs/xattr.c of the GNU/Linux kernel tree. */
1127 if (x
->preserve_xattr
)
1129 bool access_changed
= false;
1131 if (!(sb
.st_mode
& S_IWUSR
) && geteuid () != ROOT_UID
)
1132 access_changed
= fchmod_or_lchmod (dest_desc
, dst_name
, 0600) == 0;
1134 if (!copy_attr (src_name
, source_desc
, dst_name
, dest_desc
, x
)
1135 && x
->require_preserve_xattr
)
1139 fchmod_or_lchmod (dest_desc
, dst_name
, dst_mode
& ~omitted_permissions
);
1142 set_author (dst_name
, dest_desc
, src_sb
);
1144 if (x
->preserve_mode
|| x
->move_mode
)
1146 if (copy_acl (src_name
, source_desc
, dst_name
, dest_desc
, src_mode
) != 0
1147 && x
->require_preserve
)
1150 else if (x
->set_mode
)
1152 if (set_acl (dst_name
, dest_desc
, x
->mode
) != 0)
1155 else if (x
->explicit_no_preserve_mode
)
1157 if (set_acl (dst_name
, dest_desc
, 0666 & ~cached_umask ()) != 0)
1160 else if (omitted_permissions
)
1162 omitted_permissions
&= ~ cached_umask ();
1163 if (omitted_permissions
1164 && fchmod_or_lchmod (dest_desc
, dst_name
, dst_mode
) != 0)
1166 error (0, errno
, _("preserving permissions for %s"),
1168 if (x
->require_preserve
)
1173 close_src_and_dst_desc
:
1174 if (close (dest_desc
) < 0)
1176 error (0, errno
, _("failed to close %s"), quote (dst_name
));
1180 if (close (source_desc
) < 0)
1182 error (0, errno
, _("failed to close %s"), quote (src_name
));
1191 /* Return true if it's ok that the source and destination
1192 files are the 'same' by some measure. The goal is to avoid
1193 making the 'copy' operation remove both copies of the file
1194 in that case, while still allowing the user to e.g., move or
1195 copy a regular file onto a symlink that points to it.
1196 Try to minimize the cost of this function in the common case.
1197 Set *RETURN_NOW if we've determined that the caller has no more
1198 work to do and should return successfully, right away.
1200 Set *UNLINK_SRC if we've determined that the caller wants to do
1201 'rename (a, b)' where 'a' and 'b' are distinct hard links to the same
1202 file. In that case, the caller should try to unlink 'a' and then return
1203 successfully. Ideally, we wouldn't have to do that, and we'd be
1204 able to rely on rename to remove the source file. However, POSIX
1205 mistakenly requires that such a rename call do *nothing* and return
1209 same_file_ok (char const *src_name
, struct stat
const *src_sb
,
1210 char const *dst_name
, struct stat
const *dst_sb
,
1211 const struct cp_options
*x
, bool *return_now
, bool *unlink_src
)
1213 const struct stat
*src_sb_link
;
1214 const struct stat
*dst_sb_link
;
1215 struct stat tmp_dst_sb
;
1216 struct stat tmp_src_sb
;
1219 bool same
= SAME_INODE (*src_sb
, *dst_sb
);
1221 *return_now
= false;
1222 *unlink_src
= false;
1224 /* FIXME: this should (at the very least) be moved into the following
1225 if-block. More likely, it should be removed, because it inhibits
1226 making backups. But removing it will result in a change in behavior
1227 that will probably have to be documented -- and tests will have to
1229 if (same
&& x
->hard_link
)
1235 if (x
->dereference
== DEREF_NEVER
)
1239 /* If both the source and destination files are symlinks (and we'll
1240 know this here IFF preserving symlinks), then it's usually ok
1241 when they are distinct. */
1242 if (S_ISLNK (src_sb
->st_mode
) && S_ISLNK (dst_sb
->st_mode
))
1244 bool sn
= same_name (src_name
, dst_name
);
1247 /* It's fine when we're making any type of backup. */
1248 if (x
->backup_type
!= no_backups
)
1251 /* Here we have two symlinks that are hard-linked together,
1252 and we're not making backups. In this unusual case, simply
1253 returning true would lead to mv calling "rename(A,B)",
1254 which would do nothing and return 0. I.e., A would
1255 not be removed. Hence, the solution is to tell the
1256 caller that all it must do is unlink A and return. */
1268 src_sb_link
= src_sb
;
1269 dst_sb_link
= dst_sb
;
1276 if (lstat (dst_name
, &tmp_dst_sb
) != 0
1277 || lstat (src_name
, &tmp_src_sb
) != 0)
1280 src_sb_link
= &tmp_src_sb
;
1281 dst_sb_link
= &tmp_dst_sb
;
1283 same_link
= SAME_INODE (*src_sb_link
, *dst_sb_link
);
1285 /* If both are symlinks, then it's ok, but only if the destination
1286 will be unlinked before being opened. This is like the test
1287 above, but with the addition of the unlink_dest_before_opening
1288 conjunct because otherwise, with two symlinks to the same target,
1289 we'd end up truncating the source file. */
1290 if (S_ISLNK (src_sb_link
->st_mode
) && S_ISLNK (dst_sb_link
->st_mode
)
1291 && x
->unlink_dest_before_opening
)
1295 /* The backup code ensures there's a copy, so it's usually ok to
1296 remove any destination file. One exception is when both
1297 source and destination are the same directory entry. In that
1298 case, moving the destination file aside (in making the backup)
1299 would also rename the source file and result in an error. */
1300 if (x
->backup_type
!= no_backups
)
1304 /* In copy mode when dereferencing symlinks, if the source is a
1305 symlink and the dest is not, then backing up the destination
1306 (moving it aside) would make it a dangling symlink, and the
1307 subsequent attempt to open it in copy_reg would fail with
1308 a misleading diagnostic. Avoid that by returning zero in
1309 that case so the caller can make cp (or mv when it has to
1310 resort to reading the source file) fail now. */
1312 /* FIXME-note: even with the following kludge, we can still provoke
1313 the offending diagnostic. It's just a little harder to do :-)
1314 $ rm -f a b c; touch c; ln -s c b; ln -s b a; cp -b a b
1315 cp: cannot open 'a' for reading: No such file or directory
1316 That's misleading, since a subsequent 'ls' shows that 'a'
1318 One solution would be to open the source file *before* moving
1319 aside the destination, but that'd involve a big rewrite. */
1321 && x
->dereference
!= DEREF_NEVER
1322 && S_ISLNK (src_sb_link
->st_mode
)
1323 && ! S_ISLNK (dst_sb_link
->st_mode
))
1329 return ! same_name (src_name
, dst_name
);
1333 /* FIXME: use or remove */
1335 /* If we're making a backup, we'll detect the problem case in
1336 copy_reg because SRC_NAME will no longer exist. Allowing
1337 the test to be deferred lets cp do some useful things.
1338 But when creating hardlinks and SRC_NAME is a symlink
1339 but DST_NAME is not we must test anyway. */
1341 || !S_ISLNK (src_sb_link
->st_mode
)
1342 || S_ISLNK (dst_sb_link
->st_mode
))
1345 if (x
->dereference
!= DEREF_NEVER
)
1349 /* They may refer to the same file if we're in move mode and the
1350 target is a symlink. That is ok, since we remove any existing
1351 destination file before opening it -- via 'rename' if they're on
1352 the same file system, via 'unlink (DST_NAME)' otherwise.
1353 It's also ok if they're distinct hard links to the same file. */
1354 if (x
->move_mode
|| x
->unlink_dest_before_opening
)
1356 if (S_ISLNK (dst_sb_link
->st_mode
))
1360 && 1 < dst_sb_link
->st_nlink
1361 && ! same_name (src_name
, dst_name
))
1372 /* If neither is a symlink, then it's ok as long as they aren't
1373 hard links to the same file. */
1374 if (!S_ISLNK (src_sb_link
->st_mode
) && !S_ISLNK (dst_sb_link
->st_mode
))
1376 if (!SAME_INODE (*src_sb_link
, *dst_sb_link
))
1379 /* If they are the same file, it's ok if we're making hard links. */
1387 /* At this point, it is normally an error (data loss) to move a symlink
1388 onto its referent, but in at least one narrow case, it is not:
1390 1) src is a symlink,
1391 2) dest has a link count of 2 or more and
1392 3) dest and the referent of src are not the same directory entry,
1393 then it's ok, since while we'll lose one of those hard links,
1394 src will still point to a remaining link.
1395 Note that technically, condition #3 obviates condition #2, but we
1396 retain the 1 < st_nlink condition because that means fewer invocations
1397 of the more expensive #3.
1400 $ touch f && ln f l && ln -s f s
1402 -rw-------. 2 0 Jan 4 22:46 f
1403 -rw-------. 2 0 Jan 4 22:46 l
1404 lrwxrwxrwx. 1 1 Jan 4 22:46 s -> f
1405 this must fail: mv s f
1406 this must succeed: mv s l */
1408 && S_ISLNK (src_sb
->st_mode
)
1409 && 1 < dst_sb_link
->st_nlink
)
1411 char *abs_src
= canonicalize_file_name (src_name
);
1414 bool result
= ! same_name (abs_src
, dst_name
);
1420 /* It's ok to remove a destination symlink. But that works only when we
1421 unlink before opening the destination and when the source and destination
1422 files are on the same partition. */
1423 if (x
->unlink_dest_before_opening
1424 && S_ISLNK (dst_sb_link
->st_mode
))
1425 return dst_sb_link
->st_dev
== src_sb_link
->st_dev
;
1427 if (x
->dereference
== DEREF_NEVER
)
1429 if ( ! S_ISLNK (src_sb_link
->st_mode
))
1430 tmp_src_sb
= *src_sb_link
;
1431 else if (stat (src_name
, &tmp_src_sb
) != 0)
1434 if ( ! S_ISLNK (dst_sb_link
->st_mode
))
1435 tmp_dst_sb
= *dst_sb_link
;
1436 else if (stat (dst_name
, &tmp_dst_sb
) != 0)
1439 if ( ! SAME_INODE (tmp_src_sb
, tmp_dst_sb
))
1442 /* FIXME: shouldn't this be testing whether we're making symlinks? */
1453 /* Return true if FILE, with mode MODE, is writable in the sense of 'mv'.
1454 Always consider a symbolic link to be writable. */
1456 writable_destination (char const *file
, mode_t mode
)
1458 return (S_ISLNK (mode
)
1459 || can_write_any_file ()
1460 || euidaccess (file
, W_OK
) == 0);
1464 overwrite_prompt (char const *dst_name
, struct stat
const *dst_sb
)
1466 if (! writable_destination (dst_name
, dst_sb
->st_mode
))
1468 char perms
[12]; /* "-rwxrwxrwx " ls-style modes. */
1469 strmode (dst_sb
->st_mode
, perms
);
1472 _("%s: try to overwrite %s, overriding mode %04lo (%s)? "),
1473 program_name
, quote (dst_name
),
1474 (unsigned long int) (dst_sb
->st_mode
& CHMOD_MODE_BITS
),
1479 fprintf (stderr
, _("%s: overwrite %s? "),
1480 program_name
, quote (dst_name
));
1484 /* Initialize the hash table implementing a set of F_triple entries
1485 corresponding to destination files. */
1487 dest_info_init (struct cp_options
*x
)
1490 = hash_initialize (DEST_INFO_INITIAL_CAPACITY
,
1497 /* Initialize the hash table implementing a set of F_triple entries
1498 corresponding to source files listed on the command line. */
1500 src_info_init (struct cp_options
*x
)
1503 /* Note that we use triple_hash_no_name here.
1504 Contrast with the use of triple_hash above.
1505 That is necessary because a source file may be specified
1506 in many different ways. We want to warn about this
1512 = hash_initialize (DEST_INFO_INITIAL_CAPACITY
,
1514 triple_hash_no_name
,
1519 /* When effecting a move (e.g., for mv(1)), and given the name DST_NAME
1520 of the destination and a corresponding stat buffer, DST_SB, return
1521 true if the logical 'move' operation should _not_ proceed.
1522 Otherwise, return false.
1523 Depending on options specified in X, this code may issue an
1524 interactive prompt asking whether it's ok to overwrite DST_NAME. */
1526 abandon_move (const struct cp_options
*x
,
1527 char const *dst_name
,
1528 struct stat
const *dst_sb
)
1530 assert (x
->move_mode
);
1531 return (x
->interactive
== I_ALWAYS_NO
1532 || ((x
->interactive
== I_ASK_USER
1533 || (x
->interactive
== I_UNSPECIFIED
1535 && ! writable_destination (dst_name
, dst_sb
->st_mode
)))
1536 && (overwrite_prompt (dst_name
, dst_sb
), 1)
1540 /* Print --verbose output on standard output, e.g. 'new' -> 'old'.
1541 If BACKUP_DST_NAME is non-NULL, then also indicate that it is
1542 the name of a backup file. */
1544 emit_verbose (char const *src
, char const *dst
, char const *backup_dst_name
)
1546 printf ("%s -> %s", quote_n (0, src
), quote_n (1, dst
));
1547 if (backup_dst_name
)
1548 printf (_(" (backup: %s)"), quote (backup_dst_name
));
1552 /* A wrapper around "setfscreatecon (NULL)" that exits upon failure. */
1554 restore_default_fscreatecon_or_die (void)
1556 if (setfscreatecon (NULL
) != 0)
1557 error (EXIT_FAILURE
, errno
,
1558 _("failed to restore the default file creation context"));
1561 /* Create a hard link DST_NAME to SRC_NAME, honoring the REPLACE, VERBOSE and
1562 DEREFERENCE settings. Return true upon success. Otherwise, diagnose the
1563 failure and return false. If SRC_NAME is a symbolic link, then it will not
1564 be followed unless DEREFERENCE is true.
1565 If the system doesn't support hard links to symbolic links, then DST_NAME
1566 will be created as a symbolic link to SRC_NAME. */
1568 create_hard_link (char const *src_name
, char const *dst_name
,
1569 bool replace
, bool verbose
, bool dereference
)
1571 /* We want to guarantee that symlinks are not followed, unless requested. */
1574 flags
= AT_SYMLINK_FOLLOW
;
1576 bool link_failed
= (linkat (AT_FDCWD
, src_name
, AT_FDCWD
, dst_name
, flags
)
1579 /* If the link failed because of an existing destination,
1580 remove that file and then call link again. */
1581 if (link_failed
&& replace
&& errno
== EEXIST
)
1583 if (unlink (dst_name
) != 0)
1585 error (0, errno
, _("cannot remove %s"), quote (dst_name
));
1589 printf (_("removed %s\n"), quote (dst_name
));
1590 link_failed
= (linkat (AT_FDCWD
, src_name
, AT_FDCWD
, dst_name
, flags
)
1596 error (0, errno
, _("cannot create hard link %s to %s"),
1597 quote_n (0, dst_name
), quote_n (1, src_name
));
1604 /* Return true if the current file should be (tried to be) dereferenced:
1605 either for DEREF_ALWAYS or for DEREF_COMMAND_LINE_ARGUMENTS in the case
1606 where the current file is a COMMAND_LINE_ARG; otherwise return false. */
1607 static inline bool _GL_ATTRIBUTE_PURE
1608 should_dereference (const struct cp_options
*x
, bool command_line_arg
)
1610 return x
->dereference
== DEREF_ALWAYS
1611 || (x
->dereference
== DEREF_COMMAND_LINE_ARGUMENTS
1612 && command_line_arg
);
1615 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
1616 any type. NEW_DST should be true if the file DST_NAME cannot
1617 exist because its parent directory was just created; NEW_DST should
1618 be false if DST_NAME might already exist. DEVICE is the device
1619 number of the parent directory, or 0 if the parent of this file is
1620 not known. ANCESTORS points to a linked, null terminated list of
1621 devices and inodes of parent directories of SRC_NAME. COMMAND_LINE_ARG
1622 is true iff SRC_NAME was specified on the command line.
1623 FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG is both input and output.
1624 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
1625 same as) DST_NAME; otherwise, clear it.
1626 Return true if successful. */
1628 copy_internal (char const *src_name
, char const *dst_name
,
1631 struct dir_list
*ancestors
,
1632 const struct cp_options
*x
,
1633 bool command_line_arg
,
1634 bool *first_dir_created_per_command_line_arg
,
1635 bool *copy_into_self
,
1636 bool *rename_succeeded
)
1641 mode_t dst_mode
IF_LINT ( = 0);
1642 mode_t dst_mode_bits
;
1643 mode_t omitted_permissions
;
1644 bool restore_dst_mode
= false;
1645 char *earlier_file
= NULL
;
1646 char *dst_backup
= NULL
;
1647 bool backup_succeeded
= false;
1649 bool copied_as_regular
= false;
1650 bool dest_is_symlink
= false;
1651 bool have_dst_lstat
= false;
1653 if (x
->move_mode
&& rename_succeeded
)
1654 *rename_succeeded
= false;
1656 *copy_into_self
= false;
1658 if (XSTAT (x
, src_name
, &src_sb
) != 0)
1660 error (0, errno
, _("cannot stat %s"), quote (src_name
));
1664 src_mode
= src_sb
.st_mode
;
1666 if (S_ISDIR (src_mode
) && !x
->recursive
)
1668 error (0, 0, _("omitting directory %s"), quote (src_name
));
1672 /* Detect the case in which the same source file appears more than
1673 once on the command line and no backup option has been selected.
1674 If so, simply warn and don't copy it the second time.
1675 This check is enabled only if x->src_info is non-NULL. */
1676 if (command_line_arg
)
1678 if ( ! S_ISDIR (src_sb
.st_mode
)
1679 && x
->backup_type
== no_backups
1680 && seen_file (x
->src_info
, src_name
, &src_sb
))
1682 error (0, 0, _("warning: source file %s specified more than once"),
1687 record_file (x
->src_info
, src_name
, &src_sb
);
1690 bool dereference
= should_dereference (x
, command_line_arg
);
1694 /* Regular files can be created by writing through symbolic
1695 links, but other files cannot. So use stat on the
1696 destination when copying a regular file, and lstat otherwise.
1697 However, if we intend to unlink or remove the destination
1698 first, use lstat, since a copy won't actually be made to the
1699 destination in that case. */
1701 ((S_ISREG (src_mode
)
1702 || (x
->copy_as_regular
1703 && ! (S_ISDIR (src_mode
) || S_ISLNK (src_mode
))))
1704 && ! (x
->move_mode
|| x
->symbolic_link
|| x
->hard_link
1705 || x
->backup_type
!= no_backups
1706 || x
->unlink_dest_before_opening
));
1708 ? stat (dst_name
, &dst_sb
)
1709 : lstat (dst_name
, &dst_sb
))
1712 if (errno
!= ENOENT
)
1714 error (0, errno
, _("cannot stat %s"), quote (dst_name
));
1723 { /* Here, we know that dst_name exists, at least to the point
1724 that it is stat'able or lstat'able. */
1728 have_dst_lstat
= !use_stat
;
1729 if (! same_file_ok (src_name
, &src_sb
, dst_name
, &dst_sb
,
1730 x
, &return_now
, &unlink_src
))
1732 error (0, 0, _("%s and %s are the same file"),
1733 quote_n (0, src_name
), quote_n (1, dst_name
));
1737 if (!S_ISDIR (src_mode
) && x
->update
)
1739 /* When preserving time stamps (but not moving within a file
1740 system), don't worry if the destination time stamp is
1741 less than the source merely because of time stamp
1743 int options
= ((x
->preserve_timestamps
1745 && dst_sb
.st_dev
== src_sb
.st_dev
))
1746 ? UTIMECMP_TRUNCATE_SOURCE
1749 if (0 <= utimecmp (dst_name
, &dst_sb
, &src_sb
, options
))
1751 /* We're using --update and the destination is not older
1752 than the source, so do not copy or move. Pretend the
1753 rename succeeded, so the caller (if it's mv) doesn't
1754 end up removing the source file. */
1755 if (rename_succeeded
)
1756 *rename_succeeded
= true;
1758 /* However, we still must record that we've processed
1759 this src/dest pair, in case this source file is
1760 hard-linked to another one. In that case, we'll use
1761 the mapping information to link the corresponding
1762 destination names. */
1763 earlier_file
= remember_copied (dst_name
, src_sb
.st_ino
,
1767 /* Note we currently replace DST_NAME unconditionally,
1768 even if it was a newer separate file. */
1769 if (! create_hard_link (earlier_file
, dst_name
, true,
1770 x
->verbose
, dereference
))
1780 /* When there is an existing destination file, we may end up
1781 returning early, and hence not copying/moving the file.
1782 This may be due to an interactive 'negative' reply to the
1783 prompt about the existing file. It may also be due to the
1784 use of the --no-clobber option.
1786 cp and mv treat -i and -f differently. */
1789 if (abandon_move (x
, dst_name
, &dst_sb
)
1790 || (unlink_src
&& unlink (src_name
) == 0))
1792 /* Pretend the rename succeeded, so the caller (mv)
1793 doesn't end up removing the source file. */
1794 if (rename_succeeded
)
1795 *rename_succeeded
= true;
1796 if (unlink_src
&& x
->verbose
)
1797 printf (_("removed %s\n"), quote (src_name
));
1802 error (0, errno
, _("cannot remove %s"), quote (src_name
));
1808 if (! S_ISDIR (src_mode
)
1809 && (x
->interactive
== I_ALWAYS_NO
1810 || (x
->interactive
== I_ASK_USER
1811 && (overwrite_prompt (dst_name
, &dst_sb
), 1)
1819 if (!S_ISDIR (dst_sb
.st_mode
))
1821 if (S_ISDIR (src_mode
))
1823 if (x
->move_mode
&& x
->backup_type
!= no_backups
)
1825 /* Moving a directory onto an existing
1826 non-directory is ok only with --backup. */
1831 _("cannot overwrite non-directory %s with directory %s"),
1832 quote_n (0, dst_name
), quote_n (1, src_name
));
1837 /* Don't let the user destroy their data, even if they try hard:
1838 This mv command must fail (likewise for cp):
1839 rm -rf a b c; mkdir a b c; touch a/f b/f; mv a/f b/f c
1840 Otherwise, the contents of b/f would be lost.
1841 In the case of 'cp', b/f would be lost if the user simulated
1842 a move using cp and rm.
1843 Note that it works fine if you use --backup=numbered. */
1844 if (command_line_arg
1845 && x
->backup_type
!= numbered_backups
1846 && seen_file (x
->dest_info
, dst_name
, &dst_sb
))
1849 _("will not overwrite just-created %s with %s"),
1850 quote_n (0, dst_name
), quote_n (1, src_name
));
1855 if (!S_ISDIR (src_mode
))
1857 if (S_ISDIR (dst_sb
.st_mode
))
1859 if (x
->move_mode
&& x
->backup_type
!= no_backups
)
1861 /* Moving a non-directory onto an existing
1862 directory is ok only with --backup. */
1867 _("cannot overwrite directory %s with non-directory"),
1876 /* Don't allow user to move a directory onto a non-directory. */
1877 if (S_ISDIR (src_sb
.st_mode
) && !S_ISDIR (dst_sb
.st_mode
)
1878 && x
->backup_type
== no_backups
)
1881 _("cannot move directory onto non-directory: %s -> %s"),
1882 quote_n (0, src_name
), quote_n (0, dst_name
));
1887 if (x
->backup_type
!= no_backups
1888 /* Don't try to back up a destination if the last
1889 component of src_name is "." or "..". */
1890 && ! dot_or_dotdot (last_component (src_name
))
1891 /* Create a backup of each destination directory in move mode,
1892 but not in copy mode. FIXME: it might make sense to add an
1893 option to suppress backup creation also for move mode.
1894 That would let one use mv to merge new content into an
1895 existing hierarchy. */
1896 && (x
->move_mode
|| ! S_ISDIR (dst_sb
.st_mode
)))
1898 char *tmp_backup
= find_backup_file_name (dst_name
,
1901 /* Detect (and fail) when creating the backup file would
1902 destroy the source file. Before, running the commands
1903 cd /tmp; rm -f a a~; : > a; echo A > a~; cp --b=simple a~ a
1904 would leave two zero-length files: a and a~. */
1905 /* FIXME: but simply change e.g., the final a~ to './a~'
1906 and the source will still be destroyed. */
1907 if (STREQ (tmp_backup
, src_name
))
1911 ? _("backing up %s would destroy source; %s not moved")
1912 : _("backing up %s would destroy source; %s not copied"));
1914 quote_n (0, dst_name
),
1915 quote_n (1, src_name
));
1921 Using alloca for a file name that may be arbitrarily
1922 long is not recommended. In fact, even forming such a name
1923 should be discouraged. Eventually, this code will be rewritten
1924 to use fts, so using alloca here will be less of a problem. */
1925 ASSIGN_STRDUPA (dst_backup
, tmp_backup
);
1927 /* In move mode, when src_name and dst_name are on the
1928 same partition (FIXME, and when they are non-directories),
1929 make the operation atomic: link dest
1930 to backup, then rename src to dest. */
1931 if (rename (dst_name
, dst_backup
) != 0)
1933 if (errno
!= ENOENT
)
1935 error (0, errno
, _("cannot backup %s"), quote (dst_name
));
1945 backup_succeeded
= true;
1949 else if (! S_ISDIR (dst_sb
.st_mode
)
1950 /* Never unlink dst_name when in move mode. */
1952 && (x
->unlink_dest_before_opening
1953 || (x
->preserve_links
&& 1 < dst_sb
.st_nlink
)
1954 || (x
->dereference
== DEREF_NEVER
1955 && ! S_ISREG (src_sb
.st_mode
))
1958 if (unlink (dst_name
) != 0 && errno
!= ENOENT
)
1960 error (0, errno
, _("cannot remove %s"), quote (dst_name
));
1965 printf (_("removed %s\n"), quote (dst_name
));
1970 /* Ensure we don't try to copy through a symlink that was
1971 created by a prior call to this function. */
1972 if (command_line_arg
1975 && x
->backup_type
== no_backups
)
1977 bool lstat_ok
= true;
1978 struct stat tmp_buf
;
1979 struct stat
*dst_lstat_sb
;
1981 /* If we called lstat above, good: use that data.
1982 Otherwise, call lstat here, in case dst_name is a symlink. */
1984 dst_lstat_sb
= &dst_sb
;
1987 if (lstat (dst_name
, &tmp_buf
) == 0)
1988 dst_lstat_sb
= &tmp_buf
;
1993 /* Never copy through a symlink we've just created. */
1995 && S_ISLNK (dst_lstat_sb
->st_mode
)
1996 && seen_file (x
->dest_info
, dst_name
, dst_lstat_sb
))
1999 _("will not copy %s through just-created symlink %s"),
2000 quote_n (0, src_name
), quote_n (1, dst_name
));
2005 /* If the source is a directory, we don't always create the destination
2006 directory. So --verbose should not announce anything until we're
2007 sure we'll create a directory. */
2008 if (x
->verbose
&& !S_ISDIR (src_mode
))
2009 emit_verbose (src_name
, dst_name
, backup_succeeded
? dst_backup
: NULL
);
2011 /* Associate the destination file name with the source device and inode
2012 so that if we encounter a matching dev/ino pair in the source tree
2013 we can arrange to create a hard link between the corresponding names
2014 in the destination tree.
2016 When using the --link (-l) option, there is no need to take special
2017 measures, because (barring race conditions) files that are hard-linked
2018 in the source tree will also be hard-linked in the destination tree.
2020 Sometimes, when preserving links, we have to record dev/ino even
2021 though st_nlink == 1:
2022 - when in move_mode, since we may be moving a group of N hard-linked
2023 files (via two or more command line arguments) to a different
2024 partition; the links may be distributed among the command line
2025 arguments (possibly hierarchies) so that the link count of
2026 the final, once-linked source file is reduced to 1 when it is
2027 considered below. But in this case (for mv) we don't need to
2028 incur the expense of recording the dev/ino => name mapping; all we
2029 really need is a lookup, to see if the dev/ino pair has already
2031 - when using -H and processing a command line argument;
2032 that command line argument could be a symlink pointing to another
2033 command line argument. With 'cp -H --preserve=link', we hard-link
2034 those two destination files.
2035 - likewise for -L except that it applies to all files, not just
2036 command line arguments.
2038 Also, with --recursive, record dev/ino of each command-line directory.
2039 We'll use that info to detect this problem: cp -R dir dir. */
2041 if (x
->move_mode
&& src_sb
.st_nlink
== 1)
2043 earlier_file
= src_to_dest_lookup (src_sb
.st_ino
, src_sb
.st_dev
);
2045 else if (x
->preserve_links
2047 && (1 < src_sb
.st_nlink
2048 || (command_line_arg
2049 && x
->dereference
== DEREF_COMMAND_LINE_ARGUMENTS
)
2050 || x
->dereference
== DEREF_ALWAYS
))
2052 earlier_file
= remember_copied (dst_name
, src_sb
.st_ino
, src_sb
.st_dev
);
2054 else if (x
->recursive
&& S_ISDIR (src_mode
))
2056 if (command_line_arg
)
2057 earlier_file
= remember_copied (dst_name
, src_sb
.st_ino
, src_sb
.st_dev
);
2059 earlier_file
= src_to_dest_lookup (src_sb
.st_ino
, src_sb
.st_dev
);
2062 /* Did we copy this inode somewhere else (in this command line argument)
2063 and therefore this is a second hard link to the inode? */
2067 /* Avoid damaging the destination file system by refusing to preserve
2068 hard-linked directories (which are found at least in Netapp snapshot
2070 if (S_ISDIR (src_mode
))
2072 /* If src_name and earlier_file refer to the same directory entry,
2073 then warn about copying a directory into itself. */
2074 if (same_name (src_name
, earlier_file
))
2076 error (0, 0, _("cannot copy a directory, %s, into itself, %s"),
2077 quote_n (0, top_level_src_name
),
2078 quote_n (1, top_level_dst_name
));
2079 *copy_into_self
= true;
2082 else if (x
->dereference
== DEREF_ALWAYS
)
2084 /* This happens when e.g., encountering a directory for the
2085 second or subsequent time via symlinks when cp is invoked
2086 with -R and -L. E.g.,
2087 rm -rf a b c d; mkdir a b c d; ln -s ../c a; ln -s ../c b;
2093 error (0, 0, _("will not create hard link %s to directory %s"),
2094 quote_n (0, dst_name
), quote_n (1, earlier_file
));
2100 if (! create_hard_link (earlier_file
, dst_name
, true, x
->verbose
,
2110 if (rename (src_name
, dst_name
) == 0)
2112 if (x
->verbose
&& S_ISDIR (src_mode
))
2113 emit_verbose (src_name
, dst_name
,
2114 backup_succeeded
? dst_backup
: NULL
);
2116 if (rename_succeeded
)
2117 *rename_succeeded
= true;
2119 if (command_line_arg
)
2121 /* Record destination dev/ino/name, so that if we are asked
2122 to overwrite that file again, we can detect it and fail. */
2123 /* It's fine to use the _source_ stat buffer (src_sb) to get the
2124 _destination_ dev/ino, since the rename above can't have
2125 changed those, and 'mv' always uses lstat.
2126 We could limit it further by operating
2127 only on non-directories. */
2128 record_file (x
->dest_info
, dst_name
, &src_sb
);
2134 /* FIXME: someday, consider what to do when moving a directory into
2135 itself but when source and destination are on different devices. */
2137 /* This happens when attempting to rename a directory to a
2138 subdirectory of itself. */
2139 if (errno
== EINVAL
)
2141 /* FIXME: this is a little fragile in that it relies on rename(2)
2142 failing with a specific errno value. Expect problems on
2143 non-POSIX systems. */
2144 error (0, 0, _("cannot move %s to a subdirectory of itself, %s"),
2145 quote_n (0, top_level_src_name
),
2146 quote_n (1, top_level_dst_name
));
2148 /* Note that there is no need to call forget_created here,
2149 (compare with the other calls in this file) since the
2150 destination directory didn't exist before. */
2152 *copy_into_self
= true;
2153 /* FIXME-cleanup: Don't return true here; adjust mv.c accordingly.
2154 The only caller that uses this code (mv.c) ends up setting its
2155 exit status to nonzero when copy_into_self is nonzero. */
2159 /* WARNING: there probably exist systems for which an inter-device
2160 rename fails with a value of errno not handled here.
2161 If/as those are reported, add them to the condition below.
2162 If this happens to you, please do the following and send the output
2163 to the bug-reporting address (e.g., in the output of cp --help):
2164 touch k; perl -e 'rename "k","/tmp/k" or print "$!(",$!+0,")\n"'
2165 where your current directory is on one partion and /tmp is the other.
2166 Also, please try to find the E* errno macro name corresponding to
2167 the diagnostic and parenthesized integer, and include that in your
2168 e-mail. One way to do that is to run a command like this
2169 find /usr/include/. -type f \
2170 | xargs grep 'define.*\<E[A-Z]*\>.*\<18\>' /dev/null
2171 where you'd replace '18' with the integer in parentheses that
2172 was output from the perl one-liner above.
2173 If necessary, of course, change '/tmp' to some other directory. */
2176 /* There are many ways this can happen due to a race condition.
2177 When something happens between the initial XSTAT and the
2178 subsequent rename, we can get many different types of errors.
2179 For example, if the destination is initially a non-directory
2180 or non-existent, but it is created as a directory, the rename
2181 fails. If two 'mv' commands try to rename the same file at
2182 about the same time, one will succeed and the other will fail.
2183 If the permissions on the directory containing the source or
2184 destination file are made too restrictive, the rename will
2187 _("cannot move %s to %s"),
2188 quote_n (0, src_name
), quote_n (1, dst_name
));
2189 forget_created (src_sb
.st_ino
, src_sb
.st_dev
);
2193 /* The rename attempt has failed. Remove any existing destination
2194 file so that a cross-device 'mv' acts as if it were really using
2195 the rename syscall. Note both src and dst must both be directories
2196 or not, and this is enforced above. Therefore we check the src_mode
2197 and operate on dst_name here as a tighter constraint and also because
2198 src_mode is readily available here. */
2199 if ((S_ISDIR (src_mode
) ? rmdir (dst_name
) : unlink (dst_name
)) != 0
2203 _("inter-device move failed: %s to %s; unable to remove target"),
2204 quote_n (0, src_name
), quote_n (1, dst_name
));
2205 forget_created (src_sb
.st_ino
, src_sb
.st_dev
);
2212 /* If the ownership might change, or if it is a directory (whose
2213 special mode bits may change after the directory is created),
2214 omit some permissions at first, so unauthorized users cannot nip
2215 in before the file is ready. */
2216 dst_mode_bits
= (x
->set_mode
? x
->mode
: src_mode
) & CHMOD_MODE_BITS
;
2217 omitted_permissions
=
2219 & (x
->preserve_ownership
? S_IRWXG
| S_IRWXO
2220 : S_ISDIR (src_mode
) ? S_IWGRP
| S_IWOTH
2225 if (x
->preserve_security_context
)
2227 bool all_errors
= !x
->data_copy_required
|| x
->require_preserve_context
;
2228 bool some_errors
= !all_errors
&& !x
->reduce_diagnostics
;
2229 security_context_t con
;
2231 if (0 <= lgetfilecon (src_name
, &con
))
2233 if (setfscreatecon (con
) < 0)
2235 if (all_errors
|| (some_errors
&& !errno_unsupported (errno
)))
2237 _("failed to set default file creation context to %s"),
2239 if (x
->require_preserve_context
)
2249 if (all_errors
|| (some_errors
&& !errno_unsupported (errno
)))
2252 _("failed to get security context of %s"),
2255 if (x
->require_preserve_context
)
2260 if (S_ISDIR (src_mode
))
2262 struct dir_list
*dir
;
2264 /* If this directory has been copied before during the
2265 recursion, there is a symbolic link to an ancestor
2266 directory of the symbolic link. It is impossible to
2267 continue to copy this, unless we've got an infinite disk. */
2269 if (is_ancestor (&src_sb
, ancestors
))
2271 error (0, 0, _("cannot copy cyclic symbolic link %s"),
2276 /* Insert the current directory in the list of parents. */
2278 dir
= alloca (sizeof *dir
);
2279 dir
->parent
= ancestors
;
2280 dir
->ino
= src_sb
.st_ino
;
2281 dir
->dev
= src_sb
.st_dev
;
2283 if (new_dst
|| !S_ISDIR (dst_sb
.st_mode
))
2285 /* POSIX says mkdir's behavior is implementation-defined when
2286 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
2287 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
2288 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
2289 if (mkdir (dst_name
, dst_mode_bits
& ~omitted_permissions
) != 0)
2291 error (0, errno
, _("cannot create directory %s"),
2296 /* We need search and write permissions to the new directory
2297 for writing the directory's contents. Check if these
2298 permissions are there. */
2300 if (lstat (dst_name
, &dst_sb
) != 0)
2302 error (0, errno
, _("cannot stat %s"), quote (dst_name
));
2305 else if ((dst_sb
.st_mode
& S_IRWXU
) != S_IRWXU
)
2307 /* Make the new directory searchable and writable. */
2309 dst_mode
= dst_sb
.st_mode
;
2310 restore_dst_mode
= true;
2312 if (lchmod (dst_name
, dst_mode
| S_IRWXU
) != 0)
2314 error (0, errno
, _("setting permissions for %s"),
2320 /* Record the created directory's inode and device numbers into
2321 the search structure, so that we can avoid copying it again.
2322 Do this only for the first directory that is created for each
2323 source command line argument. */
2324 if (!*first_dir_created_per_command_line_arg
)
2326 remember_copied (dst_name
, dst_sb
.st_ino
, dst_sb
.st_dev
);
2327 *first_dir_created_per_command_line_arg
= true;
2331 emit_verbose (src_name
, dst_name
, NULL
);
2335 omitted_permissions
= 0;
2338 /* Decide whether to copy the contents of the directory. */
2339 if (x
->one_file_system
&& device
!= 0 && device
!= src_sb
.st_dev
)
2341 /* Here, we are crossing a file system boundary and cp's -x option
2342 is in effect: so don't copy the contents of this directory. */
2346 /* Copy the contents of the directory. Don't just return if
2347 this fails -- otherwise, the failure to read a single file
2348 in a source directory would cause the containing destination
2349 directory not to have owner/perms set properly. */
2350 delayed_ok
= copy_dir (src_name
, dst_name
, new_dst
, &src_sb
, dir
, x
,
2351 first_dir_created_per_command_line_arg
,
2355 else if (x
->symbolic_link
)
2357 dest_is_symlink
= true;
2358 if (*src_name
!= '/')
2360 /* Check that DST_NAME denotes a file in the current directory. */
2362 struct stat dst_parent_sb
;
2364 bool in_current_dir
;
2366 dst_parent
= dir_name (dst_name
);
2368 in_current_dir
= (STREQ (".", dst_parent
)
2369 /* If either stat call fails, it's ok not to report
2370 the failure and say dst_name is in the current
2371 directory. Other things will fail later. */
2372 || stat (".", &dot_sb
) != 0
2373 || stat (dst_parent
, &dst_parent_sb
) != 0
2374 || SAME_INODE (dot_sb
, dst_parent_sb
));
2377 if (! in_current_dir
)
2380 _("%s: can make relative symbolic links only in current directory"),
2385 if (symlink (src_name
, dst_name
) != 0)
2387 error (0, errno
, _("cannot create symbolic link %s to %s"),
2388 quote_n (0, dst_name
), quote_n (1, src_name
));
2393 /* POSIX 2008 states that it is implementation-defined whether
2394 link() on a symlink creates a hard-link to the symlink, or only
2395 to the referent (effectively dereferencing the symlink) (POSIX
2396 2001 required the latter behavior, although many systems provided
2397 the former). Yet cp, invoked with '--link --no-dereference',
2398 should not follow the link. We can approximate the desired
2399 behavior by skipping this hard-link creating block and instead
2400 copying the symlink, via the 'S_ISLNK'- copying code below.
2401 LINK_FOLLOWS_SYMLINKS is tri-state; if it is -1, we don't know
2402 how link() behaves, so we use the fallback case for safety.
2404 Note gnulib's linkat module, guarantees that the symlink is not
2405 dereferenced. However its emulation currently doesn't maintain
2406 timestamps or ownership so we only call it when we know the
2407 emulation will not be needed. */
2408 else if (x
->hard_link
2409 && !(LINK_FOLLOWS_SYMLINKS
&& S_ISLNK (src_mode
)
2410 && x
->dereference
== DEREF_NEVER
))
2412 if (! create_hard_link (src_name
, dst_name
, false, false, dereference
))
2415 else if (S_ISREG (src_mode
)
2416 || (x
->copy_as_regular
&& !S_ISLNK (src_mode
)))
2418 copied_as_regular
= true;
2419 /* POSIX says the permission bits of the source file must be
2420 used as the 3rd argument in the open call. Historical
2421 practice passed all the source mode bits to 'open', but the extra
2422 bits were ignored, so it should be the same either way.
2424 This call uses DST_MODE_BITS, not SRC_MODE. These are
2425 normally the same, and the exception (where x->set_mode) is
2426 used only by 'install', which POSIX does not specify and
2427 where DST_MODE_BITS is what's wanted. */
2428 if (! copy_reg (src_name
, dst_name
, x
, dst_mode_bits
& S_IRWXUGO
,
2429 omitted_permissions
, &new_dst
, &src_sb
))
2432 else if (S_ISFIFO (src_mode
))
2434 /* Use mknod, rather than mkfifo, because the former preserves
2435 the special mode bits of a fifo on Solaris 10, while mkfifo
2436 does not. But fall back on mkfifo, because on some BSD systems,
2437 mknod always fails when asked to create a FIFO. */
2438 if (mknod (dst_name
, src_mode
& ~omitted_permissions
, 0) != 0)
2439 if (mkfifo (dst_name
, src_mode
& ~S_IFIFO
& ~omitted_permissions
) != 0)
2441 error (0, errno
, _("cannot create fifo %s"), quote (dst_name
));
2445 else if (S_ISBLK (src_mode
) || S_ISCHR (src_mode
) || S_ISSOCK (src_mode
))
2447 if (mknod (dst_name
, src_mode
& ~omitted_permissions
, src_sb
.st_rdev
)
2450 error (0, errno
, _("cannot create special file %s"),
2455 else if (S_ISLNK (src_mode
))
2457 char *src_link_val
= areadlink_with_size (src_name
, src_sb
.st_size
);
2458 dest_is_symlink
= true;
2459 if (src_link_val
== NULL
)
2461 error (0, errno
, _("cannot read symbolic link %s"), quote (src_name
));
2465 if (symlink (src_link_val
, dst_name
) == 0)
2466 free (src_link_val
);
2469 int saved_errno
= errno
;
2470 bool same_link
= false;
2471 if (x
->update
&& !new_dst
&& S_ISLNK (dst_sb
.st_mode
)
2472 && dst_sb
.st_size
== strlen (src_link_val
))
2474 /* See if the destination is already the desired symlink.
2475 FIXME: This behavior isn't documented, and seems wrong
2476 in some cases, e.g., if the destination symlink has the
2477 wrong ownership, permissions, or time stamps. */
2478 char *dest_link_val
=
2479 areadlink_with_size (dst_name
, dst_sb
.st_size
);
2480 if (dest_link_val
&& STREQ (dest_link_val
, src_link_val
))
2482 free (dest_link_val
);
2484 free (src_link_val
);
2488 error (0, saved_errno
, _("cannot create symbolic link %s"),
2494 if (x
->preserve_security_context
)
2495 restore_default_fscreatecon_or_die ();
2497 if (x
->preserve_ownership
)
2499 /* Preserve the owner and group of the just-'copied'
2500 symbolic link, if possible. */
2502 && lchown (dst_name
, src_sb
.st_uid
, src_sb
.st_gid
) != 0
2503 && ! chown_failure_ok (x
))
2505 error (0, errno
, _("failed to preserve ownership for %s"),
2511 /* Can't preserve ownership of symlinks.
2512 FIXME: maybe give a warning or even error for symlinks
2513 in directories with the sticky bit set -- there, not
2514 preserving owner/group is a potential security problem. */
2520 error (0, 0, _("%s has unknown file type"), quote (src_name
));
2524 if (command_line_arg
&& x
->dest_info
)
2526 /* Now that the destination file is very likely to exist,
2527 add its info to the set. */
2529 if (lstat (dst_name
, &sb
) == 0)
2530 record_file (x
->dest_info
, dst_name
, &sb
);
2533 /* If we've just created a hard-link due to cp's --link option,
2535 if (x
->hard_link
&& ! S_ISDIR (src_mode
)
2536 && !(LINK_FOLLOWS_SYMLINKS
&& S_ISLNK (src_mode
)
2537 && x
->dereference
== DEREF_NEVER
))
2540 if (copied_as_regular
)
2543 /* POSIX says that 'cp -p' must restore the following:
2545 - setuid, setgid bits
2547 If it fails to restore any of those, we may give a warning but
2548 the destination must not be removed.
2549 FIXME: implement the above. */
2551 /* Adjust the times (and if possible, ownership) for the copy.
2552 chown turns off set[ug]id bits for non-root,
2553 so do the chmod last. */
2555 if (x
->preserve_timestamps
)
2557 struct timespec timespec
[2];
2558 timespec
[0] = get_stat_atime (&src_sb
);
2559 timespec
[1] = get_stat_mtime (&src_sb
);
2561 if ((dest_is_symlink
2562 ? utimens_symlink (dst_name
, timespec
)
2563 : utimens (dst_name
, timespec
))
2566 error (0, errno
, _("preserving times for %s"), quote (dst_name
));
2567 if (x
->require_preserve
)
2572 /* The operations beyond this point may dereference a symlink. */
2573 if (dest_is_symlink
)
2576 /* Avoid calling chown if we know it's not necessary. */
2577 if (x
->preserve_ownership
2578 && (new_dst
|| !SAME_OWNER_AND_GROUP (src_sb
, dst_sb
)))
2580 switch (set_owner (x
, dst_name
, -1, &src_sb
, new_dst
, &dst_sb
))
2586 src_mode
&= ~ (S_ISUID
| S_ISGID
| S_ISVTX
);
2591 set_author (dst_name
, -1, &src_sb
);
2593 if (x
->preserve_xattr
&& ! copy_attr (src_name
, -1, dst_name
, -1, x
)
2594 && x
->require_preserve_xattr
)
2597 if (x
->preserve_mode
|| x
->move_mode
)
2599 if (copy_acl (src_name
, -1, dst_name
, -1, src_mode
) != 0
2600 && x
->require_preserve
)
2603 else if (x
->set_mode
)
2605 if (set_acl (dst_name
, -1, x
->mode
) != 0)
2608 else if (x
->explicit_no_preserve_mode
)
2610 if (set_acl (dst_name
, -1, 0777 & ~cached_umask ()) != 0)
2615 if (omitted_permissions
)
2617 omitted_permissions
&= ~ cached_umask ();
2619 if (omitted_permissions
&& !restore_dst_mode
)
2621 /* Permissions were deliberately omitted when the file
2622 was created due to security concerns. See whether
2623 they need to be re-added now. It'd be faster to omit
2624 the lstat, but deducing the current destination mode
2625 is tricky in the presence of implementation-defined
2626 rules for special mode bits. */
2627 if (new_dst
&& lstat (dst_name
, &dst_sb
) != 0)
2629 error (0, errno
, _("cannot stat %s"), quote (dst_name
));
2632 dst_mode
= dst_sb
.st_mode
;
2633 if (omitted_permissions
& ~dst_mode
)
2634 restore_dst_mode
= true;
2638 if (restore_dst_mode
)
2640 if (lchmod (dst_name
, dst_mode
| omitted_permissions
) != 0)
2642 error (0, errno
, _("preserving permissions for %s"),
2644 if (x
->require_preserve
)
2654 if (x
->preserve_security_context
)
2655 restore_default_fscreatecon_or_die ();
2657 /* We have failed to create the destination file.
2658 If we've just added a dev/ino entry via the remember_copied
2659 call above (i.e., unless we've just failed to create a hard link),
2660 remove the entry associating the source dev/ino with the
2661 destination file name, so we don't try to 'preserve' a link
2662 to a file we didn't create. */
2663 if (earlier_file
== NULL
)
2664 forget_created (src_sb
.st_ino
, src_sb
.st_dev
);
2668 if (rename (dst_backup
, dst_name
) != 0)
2669 error (0, errno
, _("cannot un-backup %s"), quote (dst_name
));
2673 printf (_("%s -> %s (unbackup)\n"),
2674 quote_n (0, dst_backup
), quote_n (1, dst_name
));
2680 static bool _GL_ATTRIBUTE_PURE
2681 valid_options (const struct cp_options
*co
)
2683 assert (co
!= NULL
);
2684 assert (VALID_BACKUP_TYPE (co
->backup_type
));
2685 assert (VALID_SPARSE_MODE (co
->sparse_mode
));
2686 assert (VALID_REFLINK_MODE (co
->reflink_mode
));
2687 assert (!(co
->hard_link
&& co
->symbolic_link
));
2689 (co
->reflink_mode
== REFLINK_ALWAYS
2690 && co
->sparse_mode
!= SPARSE_AUTO
));
2694 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
2695 any type. NONEXISTENT_DST should be true if the file DST_NAME
2696 is known not to exist (e.g., because its parent directory was just
2697 created); NONEXISTENT_DST should be false if DST_NAME might already
2698 exist. OPTIONS is ... FIXME-describe
2699 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
2700 same as) DST_NAME; otherwise, set clear it.
2701 Return true if successful. */
2704 copy (char const *src_name
, char const *dst_name
,
2705 bool nonexistent_dst
, const struct cp_options
*options
,
2706 bool *copy_into_self
, bool *rename_succeeded
)
2708 assert (valid_options (options
));
2710 /* Record the file names: they're used in case of error, when copying
2711 a directory into itself. I don't like to make these tools do *any*
2712 extra work in the common case when that work is solely to handle
2713 exceptional cases, but in this case, I don't see a way to derive the
2714 top level source and destination directory names where they're used.
2715 An alternative is to use COPY_INTO_SELF and print the diagnostic
2716 from every caller -- but I don't want to do that. */
2717 top_level_src_name
= src_name
;
2718 top_level_dst_name
= dst_name
;
2720 bool first_dir_created_per_command_line_arg
= false;
2721 return copy_internal (src_name
, dst_name
, nonexistent_dst
, 0, NULL
,
2723 &first_dir_created_per_command_line_arg
,
2724 copy_into_self
, rename_succeeded
);
2727 /* Set *X to the default options for a value of type struct cp_options. */
2730 cp_options_default (struct cp_options
*x
)
2732 memset (x
, 0, sizeof *x
);
2733 #ifdef PRIV_FILE_CHOWN
2735 priv_set_t
*pset
= priv_allocset ();
2738 if (getppriv (PRIV_EFFECTIVE
, pset
) == 0)
2740 x
->chown_privileges
= priv_ismember (pset
, PRIV_FILE_CHOWN
);
2741 x
->owner_privileges
= priv_ismember (pset
, PRIV_FILE_OWNER
);
2743 priv_freeset (pset
);
2746 x
->chown_privileges
= x
->owner_privileges
= (geteuid () == ROOT_UID
);
2750 /* Return true if it's OK for chown to fail, where errno is
2751 the error number that chown failed with and X is the copying
2755 chown_failure_ok (struct cp_options
const *x
)
2757 /* If non-root uses -p, it's ok if we can't preserve ownership.
2758 But root probably wants to know, e.g. if NFS disallows it,
2759 or if the target system doesn't support file ownership. */
2761 return ((errno
== EPERM
|| errno
== EINVAL
) && !x
->chown_privileges
);
2764 /* Similarly, return true if it's OK for chmod and similar operations
2765 to fail, where errno is the error number that chmod failed with and
2766 X is the copying option set. */
2769 owner_failure_ok (struct cp_options
const *x
)
2771 return ((errno
== EPERM
|| errno
== EINVAL
) && !x
->owner_privileges
);
2774 /* Return the user's umask, caching the result.
2776 FIXME: If the destination's parent directory has has a default ACL,
2777 some operating systems (e.g., GNU/Linux's "POSIX" ACLs) use that
2778 ACL's mask rather than the process umask. Currently, the callers
2779 of cached_umask incorrectly assume that this situation cannot occur. */
2783 static mode_t mask
= (mode_t
) -1;
2784 if (mask
== (mode_t
) -1)