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"
50 #include "ioblksize.h"
54 #include "stat-size.h"
55 #include "stat-time.h"
58 #include "write-any-file.h"
59 #include "areadlink.h"
63 # include <attr/error_context.h>
64 # include <attr/libattr.h>
70 # define HAVE_FCHOWN false
71 # define fchown(fd, uid, gid) (-1)
75 # define HAVE_LCHOWN false
76 # define lchown(name, uid, gid) chown (name, uid, gid)
81 rpl_mkfifo (char const *file
, mode_t mode
)
86 # define mkfifo rpl_mkfifo
93 #define SAME_OWNER(A, B) ((A).st_uid == (B).st_uid)
94 #define SAME_GROUP(A, B) ((A).st_gid == (B).st_gid)
95 #define SAME_OWNER_AND_GROUP(A, B) (SAME_OWNER (A, B) && SAME_GROUP (A, B))
99 struct dir_list
*parent
;
104 /* Initial size of the cp.dest_info hash table. */
105 #define DEST_INFO_INITIAL_CAPACITY 61
107 static bool copy_internal (char const *src_name
, char const *dst_name
,
108 bool new_dst
, dev_t device
,
109 struct dir_list
*ancestors
,
110 const struct cp_options
*x
,
111 bool command_line_arg
,
112 bool *first_dir_created_per_command_line_arg
,
113 bool *copy_into_self
,
114 bool *rename_succeeded
);
115 static bool owner_failure_ok (struct cp_options
const *x
);
117 /* Pointers to the file names: they're used in the diagnostic that is issued
118 when we detect the user is trying to copy a directory into itself. */
119 static char const *top_level_src_name
;
120 static char const *top_level_dst_name
;
122 /* Set the timestamp of symlink, FILE, to TIMESPEC.
123 If this system lacks support for that, simply return 0. */
125 utimens_symlink (char const *file
, struct timespec
const *timespec
)
127 int err
= lutimens (file
, timespec
);
128 /* When configuring on a system with new headers and libraries, and
129 running on one with a kernel that is old enough to lack the syscall,
130 utimensat fails with ENOSYS. Ignore that. */
131 if (err
&& errno
== ENOSYS
)
136 /* Copy the regular file open on SRC_FD/SRC_NAME to DST_FD/DST_NAME,
137 honoring the MAKE_HOLES setting and using the BUF_SIZE-byte buffer
138 BUF for temporary storage. Copy no more than MAX_N_READ bytes.
139 Return true upon successful completion;
140 print a diagnostic and return false upon error.
141 Note that for best results, BUF should be "well"-aligned.
142 BUF must have sizeof(uintptr_t)-1 bytes of additional space
143 beyond BUF[BUF_SIZE-1].
144 Set *LAST_WRITE_MADE_HOLE to true if the final operation on
145 DEST_FD introduced a hole. Set *TOTAL_N_READ to the number of
148 sparse_copy (int src_fd
, int dest_fd
, char *buf
, size_t buf_size
,
150 char const *src_name
, char const *dst_name
,
151 uintmax_t max_n_read
, off_t
*total_n_read
,
152 bool *last_write_made_hole
)
154 typedef uintptr_t word
;
155 *last_write_made_hole
= false;
162 ssize_t n_read
= read (src_fd
, buf
, MIN (max_n_read
, buf_size
));
167 error (0, errno
, _("reading %s"), quote (src_name
));
172 max_n_read
-= n_read
;
173 *total_n_read
+= n_read
;
179 /* Sentinel to stop loop. */
182 /* Usually, buf[n_read] is not the byte just before a "word"
183 (aka uintptr_t) boundary. In that case, the word-oriented
184 test below (*wp++ == 0) would read some uninitialized bytes
185 after the sentinel. To avoid false-positive reports about
186 this condition (e.g., from a tool like valgrind), set the
187 remaining bytes -- to any value. */
188 memset (buf
+ n_read
+ 1, 0, sizeof (word
) - 1);
191 /* Find first nonzero *word*, or the word with the sentinel. */
197 /* Find the first nonzero *byte*, or the sentinel. */
199 cp
= (char *) (wp
- 1);
203 if (cp
<= buf
+ n_read
)
204 /* Clear to indicate that a normal write is needed. */
208 /* We found the sentinel, so the whole input block was zero.
210 if (lseek (dest_fd
, n_read
, SEEK_CUR
) < 0)
212 error (0, errno
, _("cannot lseek %s"), quote (dst_name
));
215 *last_write_made_hole
= true;
222 if (full_write (dest_fd
, buf
, n
) != n
)
224 error (0, errno
, _("writing %s"), quote (dst_name
));
227 *last_write_made_hole
= false;
229 /* It is tempting to return early here upon a short read from a
230 regular file. That would save the final read syscall for each
231 file. Unfortunately that doesn't work for certain files in
232 /proc with linux kernels from at least 2.6.9 .. 2.6.29. */
239 /* Perform the O(1) btrfs clone operation, if possible.
240 Upon success, return 0. Otherwise, return -1 and set errno. */
242 clone_file (int dest_fd
, int src_fd
)
245 # undef BTRFS_IOCTL_MAGIC
246 # define BTRFS_IOCTL_MAGIC 0x94
247 # undef BTRFS_IOC_CLONE
248 # define BTRFS_IOC_CLONE _IOW (BTRFS_IOCTL_MAGIC, 9, int)
249 return ioctl (dest_fd
, BTRFS_IOC_CLONE
, src_fd
);
258 /* Write N_BYTES zero bytes to file descriptor FD. Return true if successful.
259 Upon write failure, set errno and return false. */
261 write_zeros (int fd
, uint64_t n_bytes
)
264 static size_t nz
= IO_BUFSIZE
;
266 /* Attempt to use a relatively large calloc'd source buffer for
267 efficiency, but if that allocation fails, resort to a smaller
268 statically allocated one. */
271 static char fallback
[1024];
272 zeros
= calloc (nz
, 1);
276 nz
= sizeof fallback
;
282 uint64_t n
= MIN (nz
, n_bytes
);
283 if ((full_write (fd
, zeros
, n
)) != n
)
291 /* Perform an efficient extent copy, if possible. This avoids
292 the overhead of detecting holes in hole-introducing/preserving
293 copy, and thus makes copying sparse files much more efficient.
294 Upon a successful copy, return true. If the initial extent scan
295 fails, set *NORMAL_COPY_REQUIRED to true and return false.
296 Upon any other failure, set *NORMAL_COPY_REQUIRED to false and
299 extent_copy (int src_fd
, int dest_fd
, char *buf
, size_t buf_size
,
300 off_t src_total_size
, enum Sparse_type sparse_mode
,
301 char const *src_name
, char const *dst_name
,
302 bool *require_normal_copy
)
304 struct extent_scan scan
;
305 off_t last_ext_start
= 0;
306 uint64_t last_ext_len
= 0;
308 /* Keep track of the output position.
309 We may need this at the end, for a final ftruncate. */
312 extent_scan_init (src_fd
, &scan
);
314 *require_normal_copy
= false;
315 bool wrote_hole_at_eof
= true;
318 bool ok
= extent_scan_read (&scan
);
321 if (scan
.hit_final_extent
)
324 if (scan
.initial_scan_failed
)
326 *require_normal_copy
= true;
330 error (0, errno
, _("%s: failed to get extents info"),
336 bool empty_extent
= false;
337 for (i
= 0; i
< scan
.ei_count
|| empty_extent
; i
++)
343 if (i
< scan
.ei_count
)
345 ext_start
= scan
.ext_info
[i
].ext_logical
;
346 ext_len
= scan
.ext_info
[i
].ext_length
;
348 else /* empty extent at EOF. */
351 ext_start
= last_ext_start
+ scan
.ext_info
[i
].ext_length
;
355 hole_size
= ext_start
- last_ext_start
- last_ext_len
;
357 wrote_hole_at_eof
= false;
361 if (lseek (src_fd
, ext_start
, SEEK_SET
) < 0)
363 error (0, errno
, _("cannot lseek %s"), quote (src_name
));
365 extent_scan_free (&scan
);
369 if ((empty_extent
&& sparse_mode
== SPARSE_ALWAYS
)
370 || (!empty_extent
&& sparse_mode
!= SPARSE_NEVER
))
372 if (lseek (dest_fd
, ext_start
, SEEK_SET
) < 0)
374 error (0, errno
, _("cannot lseek %s"), quote (dst_name
));
377 wrote_hole_at_eof
= true;
381 /* When not inducing holes and when there is a hole between
382 the end of the previous extent and the beginning of the
383 current one, write zeros to the destination file. */
384 off_t nzeros
= hole_size
;
386 nzeros
= MIN (src_total_size
- dest_pos
, hole_size
);
388 if (! write_zeros (dest_fd
, nzeros
))
390 error (0, errno
, _("%s: write failed"), quote (dst_name
));
394 dest_pos
= MIN (src_total_size
, ext_start
);
398 last_ext_start
= ext_start
;
400 /* Treat an unwritten but allocated extent much like a hole.
401 I.E. don't read, but don't convert to a hole in the destination,
402 unless SPARSE_ALWAYS. */
403 /* For now, do not treat FIEMAP_EXTENT_UNWRITTEN specially,
404 because that (in combination with no sync) would lead to data
405 loss at least on XFS and ext4 when using 2.6.39-rc3 kernels. */
406 if (0 && (scan
.ext_info
[i
].ext_flags
& FIEMAP_EXTENT_UNWRITTEN
))
410 if (ext_len
== 0) /* The last extent is empty and processed. */
411 empty_extent
= false;
416 empty_extent
= false;
417 last_ext_len
= ext_len
;
419 if ( ! sparse_copy (src_fd
, dest_fd
, buf
, buf_size
,
420 sparse_mode
== SPARSE_ALWAYS
,
421 src_name
, dst_name
, ext_len
, &n_read
,
425 dest_pos
= ext_start
+ n_read
;
428 /* If the file ends with unwritten extents not accounted for in the
429 size, then skip processing them, and the associated redundant
430 read() calls which will always return 0. We will need to
431 remove this when we add fallocate() so that we can maintain
432 extents beyond the apparent size. */
433 if (dest_pos
== src_total_size
)
435 scan
.hit_final_extent
= true;
440 /* Release the space allocated to scan->ext_info. */
441 extent_scan_free (&scan
);
444 while (! scan
.hit_final_extent
);
446 /* When the source file ends with a hole, we have to do a little more work,
447 since the above copied only up to and including the final extent.
448 In order to complete the copy, we may have to insert a hole or write
449 zeros in the destination corresponding to the source file's hole-at-EOF.
451 In addition, if the final extent was a block of zeros at EOF and we've
452 just converted them to a hole in the destination, we must call ftruncate
453 here in order to record the proper length in the destination. */
454 if ((dest_pos
< src_total_size
|| wrote_hole_at_eof
)
455 && (sparse_mode
!= SPARSE_NEVER
456 ? ftruncate (dest_fd
, src_total_size
)
457 : ! write_zeros (dest_fd
, src_total_size
- dest_pos
)))
459 error (0, errno
, _("failed to extend %s"), quote (dst_name
));
466 /* FIXME: describe */
467 /* FIXME: rewrite this to use a hash table so we avoid the quadratic
468 performance hit that's probably noticeable only on trees deeper
469 than a few hundred levels. See use of active_dir_map in remove.c */
471 static bool _GL_ATTRIBUTE_PURE
472 is_ancestor (const struct stat
*sb
, const struct dir_list
*ancestors
)
474 while (ancestors
!= 0)
476 if (ancestors
->ino
== sb
->st_ino
&& ancestors
->dev
== sb
->st_dev
)
478 ancestors
= ancestors
->parent
;
484 errno_unsupported (int err
)
486 return err
== ENOTSUP
|| err
== ENODATA
;
491 copy_attr_error (struct error_context
*ctx ATTRIBUTE_UNUSED
,
492 char const *fmt
, ...)
494 if (!errno_unsupported (errno
))
499 /* use verror module to print error message */
501 verror (0, err
, fmt
, ap
);
507 copy_attr_allerror (struct error_context
*ctx ATTRIBUTE_UNUSED
,
508 char const *fmt
, ...)
513 /* use verror module to print error message */
515 verror (0, err
, fmt
, ap
);
520 copy_attr_quote (struct error_context
*ctx ATTRIBUTE_UNUSED
, char const *str
)
526 copy_attr_free (struct error_context
*ctx ATTRIBUTE_UNUSED
,
527 char const *str ATTRIBUTE_UNUSED
)
531 /* If positive SRC_FD and DST_FD descriptors are passed,
532 then copy by fd, otherwise copy by name. */
535 copy_attr (char const *src_path
, int src_fd
,
536 char const *dst_path
, int dst_fd
, struct cp_options
const *x
)
539 bool all_errors
= (!x
->data_copy_required
|| x
->require_preserve_xattr
);
540 bool some_errors
= (!all_errors
&& !x
->reduce_diagnostics
);
541 struct error_context ctx
=
543 .error
= all_errors
? copy_attr_allerror
: copy_attr_error
,
544 .quote
= copy_attr_quote
,
545 .quote_free
= copy_attr_free
547 if (0 <= src_fd
&& 0 <= dst_fd
)
548 ret
= attr_copy_fd (src_path
, src_fd
, dst_path
, dst_fd
, 0,
549 (all_errors
|| some_errors
? &ctx
: NULL
));
551 ret
= attr_copy_file (src_path
, dst_path
, 0,
552 (all_errors
|| some_errors
? &ctx
: NULL
));
556 #else /* USE_XATTR */
559 copy_attr (char const *src_path ATTRIBUTE_UNUSED
,
560 int src_fd ATTRIBUTE_UNUSED
,
561 char const *dst_path ATTRIBUTE_UNUSED
,
562 int dst_fd ATTRIBUTE_UNUSED
,
563 struct cp_options
const *x ATTRIBUTE_UNUSED
)
567 #endif /* USE_XATTR */
569 /* Read the contents of the directory SRC_NAME_IN, and recursively
570 copy the contents to DST_NAME_IN. NEW_DST is true if
571 DST_NAME_IN is a directory that was created previously in the
572 recursion. SRC_SB and ANCESTORS describe SRC_NAME_IN.
573 Set *COPY_INTO_SELF if SRC_NAME_IN is a parent of
574 (or the same as) DST_NAME_IN; otherwise, clear it.
575 Propagate *FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG from
576 caller to each invocation of copy_internal. Be careful to
577 pass the address of a temporary, and to update
578 *FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG only upon completion.
579 Return true if successful. */
582 copy_dir (char const *src_name_in
, char const *dst_name_in
, bool new_dst
,
583 const struct stat
*src_sb
, struct dir_list
*ancestors
,
584 const struct cp_options
*x
,
585 bool *first_dir_created_per_command_line_arg
,
586 bool *copy_into_self
)
590 struct cp_options non_command_line_options
= *x
;
593 name_space
= savedir (src_name_in
);
594 if (name_space
== NULL
)
596 /* This diagnostic is a bit vague because savedir can fail in
597 several different ways. */
598 error (0, errno
, _("cannot access %s"), quote (src_name_in
));
602 /* For cp's -H option, dereference command line arguments, but do not
603 dereference symlinks that are found via recursive traversal. */
604 if (x
->dereference
== DEREF_COMMAND_LINE_ARGUMENTS
)
605 non_command_line_options
.dereference
= DEREF_NEVER
;
607 bool new_first_dir_created
= false;
609 while (*namep
!= '\0')
611 bool local_copy_into_self
;
612 char *src_name
= file_name_concat (src_name_in
, namep
, NULL
);
613 char *dst_name
= file_name_concat (dst_name_in
, namep
, NULL
);
614 bool first_dir_created
= *first_dir_created_per_command_line_arg
;
616 ok
&= copy_internal (src_name
, dst_name
, new_dst
, src_sb
->st_dev
,
617 ancestors
, &non_command_line_options
, false,
619 &local_copy_into_self
, NULL
);
620 *copy_into_self
|= local_copy_into_self
;
625 /* If we're copying into self, there's no point in continuing,
626 and in fact, that would even infloop, now that we record only
627 the first created directory per command line argument. */
628 if (local_copy_into_self
)
631 new_first_dir_created
|= first_dir_created
;
632 namep
+= strlen (namep
) + 1;
635 *first_dir_created_per_command_line_arg
= new_first_dir_created
;
640 /* Set the owner and owning group of DEST_DESC to the st_uid and
641 st_gid fields of SRC_SB. If DEST_DESC is undefined (-1), set
642 the owner and owning group of DST_NAME instead; for
643 safety prefer lchown if the system supports it since no
644 symbolic links should be involved. DEST_DESC must
645 refer to the same file as DEST_NAME if defined.
646 Upon failure to set both UID and GID, try to set only the GID.
647 NEW_DST is true if the file was newly created; otherwise,
648 DST_SB is the status of the destination.
649 Return 1 if the initial syscall succeeds, 0 if it fails but it's OK
650 not to preserve ownership, -1 otherwise. */
653 set_owner (const struct cp_options
*x
, char const *dst_name
, int dest_desc
,
654 struct stat
const *src_sb
, bool new_dst
,
655 struct stat
const *dst_sb
)
657 uid_t uid
= src_sb
->st_uid
;
658 gid_t gid
= src_sb
->st_gid
;
660 /* Naively changing the ownership of an already-existing file before
661 changing its permissions would create a window of vulnerability if
662 the file's old permissions are too generous for the new owner and
663 group. Avoid the window by first changing to a restrictive
664 temporary mode if necessary. */
666 if (!new_dst
&& (x
->preserve_mode
|| x
->move_mode
|| x
->set_mode
))
668 mode_t old_mode
= dst_sb
->st_mode
;
670 (x
->preserve_mode
|| x
->move_mode
? src_sb
->st_mode
: x
->mode
);
671 mode_t restrictive_temp_mode
= old_mode
& new_mode
& S_IRWXU
;
674 || (old_mode
& CHMOD_MODE_BITS
675 & (~new_mode
| S_ISUID
| S_ISGID
| S_ISVTX
)))
676 && qset_acl (dst_name
, dest_desc
, restrictive_temp_mode
) != 0)
678 if (! owner_failure_ok (x
))
679 error (0, errno
, _("clearing permissions for %s"),
681 return -x
->require_preserve
;
685 if (HAVE_FCHOWN
&& dest_desc
!= -1)
687 if (fchown (dest_desc
, uid
, gid
) == 0)
689 if (errno
== EPERM
|| errno
== EINVAL
)
691 /* We've failed to set *both*. Now, try to set just the group
692 ID, but ignore any failure here, and don't change errno. */
693 int saved_errno
= errno
;
694 ignore_value (fchown (dest_desc
, -1, gid
));
700 if (lchown (dst_name
, uid
, gid
) == 0)
702 if (errno
== EPERM
|| errno
== EINVAL
)
704 /* We've failed to set *both*. Now, try to set just the group
705 ID, but ignore any failure here, and don't change errno. */
706 int saved_errno
= errno
;
707 ignore_value (lchown (dst_name
, -1, gid
));
712 if (! chown_failure_ok (x
))
714 error (0, errno
, _("failed to preserve ownership for %s"),
716 if (x
->require_preserve
)
723 /* Set the st_author field of DEST_DESC to the st_author field of
724 SRC_SB. If DEST_DESC is undefined (-1), set the st_author field
725 of DST_NAME instead. DEST_DESC must refer to the same file as
726 DEST_NAME if defined. */
729 set_author (const char *dst_name
, int dest_desc
, const struct stat
*src_sb
)
731 #if HAVE_STRUCT_STAT_ST_AUTHOR
732 /* FIXME: Modify the following code so that it does not
733 follow symbolic links. */
735 /* Preserve the st_author field. */
736 file_t file
= (dest_desc
< 0
737 ? file_name_lookup (dst_name
, 0, 0)
738 : getdport (dest_desc
));
739 if (file
== MACH_PORT_NULL
)
740 error (0, errno
, _("failed to lookup file %s"), quote (dst_name
));
743 error_t err
= file_chauthor (file
, src_sb
->st_author
);
745 error (0, err
, _("failed to preserve authorship for %s"),
747 mach_port_deallocate (mach_task_self (), file
);
756 /* Change the file mode bits of the file identified by DESC or NAME to MODE.
757 Use DESC if DESC is valid and fchmod is available, NAME otherwise. */
760 fchmod_or_lchmod (int desc
, char const *name
, mode_t mode
)
764 return fchmod (desc
, mode
);
766 return lchmod (name
, mode
);
769 #ifndef HAVE_STRUCT_STAT_ST_BLOCKS
770 # define HAVE_STRUCT_STAT_ST_BLOCKS 0
773 /* Use a heuristic to determine whether stat buffer SB comes from a file
774 with sparse blocks. If the file has fewer blocks than would normally
775 be needed for a file of its size, then at least one of the blocks in
776 the file is a hole. In that case, return true. */
778 is_probably_sparse (struct stat
const *sb
)
780 return (HAVE_STRUCT_STAT_ST_BLOCKS
781 && S_ISREG (sb
->st_mode
)
782 && ST_NBLOCKS (*sb
) < sb
->st_size
/ ST_NBLOCKSIZE
);
786 /* Copy a regular file from SRC_NAME to DST_NAME.
787 If the source file contains holes, copies holes and blocks of zeros
788 in the source file as holes in the destination file.
789 (Holes are read as zeroes by the `read' system call.)
790 When creating the destination, use DST_MODE & ~OMITTED_PERMISSIONS
791 as the third argument in the call to open, adding
792 OMITTED_PERMISSIONS after copying as needed.
793 X provides many option settings.
794 Return true if successful.
795 *NEW_DST is as in copy_internal.
796 SRC_SB is the result of calling XSTAT (aka stat) on SRC_NAME. */
799 copy_reg (char const *src_name
, char const *dst_name
,
800 const struct cp_options
*x
,
801 mode_t dst_mode
, mode_t omitted_permissions
, bool *new_dst
,
802 struct stat
const *src_sb
)
805 char *buf_alloc
= NULL
;
806 char *name_alloc
= NULL
;
810 mode_t src_mode
= src_sb
->st_mode
;
812 struct stat src_open_sb
;
813 bool return_val
= true;
814 bool data_copy_required
= x
->data_copy_required
;
816 source_desc
= open (src_name
,
818 | (x
->dereference
== DEREF_NEVER
? O_NOFOLLOW
: 0)));
821 error (0, errno
, _("cannot open %s for reading"), quote (src_name
));
825 if (fstat (source_desc
, &src_open_sb
) != 0)
827 error (0, errno
, _("cannot fstat %s"), quote (src_name
));
832 /* Compare the source dev/ino from the open file to the incoming,
833 saved ones obtained via a previous call to stat. */
834 if (! SAME_INODE (*src_sb
, src_open_sb
))
837 _("skipping file %s, as it was replaced while being copied"),
843 /* The semantics of the following open calls are mandated
844 by the specs for both cp and mv. */
847 dest_desc
= open (dst_name
, O_WRONLY
| O_TRUNC
| O_BINARY
);
850 /* When using cp --preserve=context to copy to an existing destination,
851 use the default context rather than that of the source. Why?
852 1) the src context may prohibit writing, and
853 2) because it's more consistent to use the same context
854 that is used when the destination file doesn't already exist. */
855 if (x
->preserve_security_context
&& 0 <= dest_desc
)
857 bool all_errors
= (!x
->data_copy_required
858 || x
->require_preserve_context
);
859 bool some_errors
= !all_errors
&& !x
->reduce_diagnostics
;
860 security_context_t con
= NULL
;
862 if (getfscreatecon (&con
) < 0)
864 if (all_errors
|| (some_errors
&& !errno_unsupported (errno
)))
865 error (0, errno
, _("failed to get file system create context"));
866 if (x
->require_preserve_context
)
869 goto close_src_and_dst_desc
;
875 if (fsetfilecon (dest_desc
, con
) < 0)
877 if (all_errors
|| (some_errors
&& !errno_unsupported (errno
)))
879 _("failed to set the security context of %s to %s"),
880 quote_n (0, dst_name
), quote_n (1, con
));
881 if (x
->require_preserve_context
)
885 goto close_src_and_dst_desc
;
892 if (dest_desc
< 0 && x
->unlink_dest_after_failed_open
)
894 if (unlink (dst_name
) != 0)
896 error (0, errno
, _("cannot remove %s"), quote (dst_name
));
901 printf (_("removed %s\n"), quote (dst_name
));
903 /* Tell caller that the destination file was unlinked. */
910 int open_flags
= O_WRONLY
| O_CREAT
| O_BINARY
;
911 dest_desc
= open (dst_name
, open_flags
| O_EXCL
,
912 dst_mode
& ~omitted_permissions
);
915 /* When trying to copy through a dangling destination symlink,
916 the above open fails with EEXIST. If that happens, and
917 lstat'ing the DST_NAME shows that it is a symlink, then we
918 have a problem: trying to resolve this dangling symlink to
919 a directory/destination-entry pair is fundamentally racy,
920 so punt. If x->open_dangling_dest_symlink is set (cp sets
921 that when POSIXLY_CORRECT is set in the environment), simply
922 call open again, but without O_EXCL (potentially dangerous).
923 If not, fail with a diagnostic. These shenanigans are necessary
924 only when copying, i.e., not in move_mode. */
925 if (dest_desc
< 0 && dest_errno
== EEXIST
&& ! x
->move_mode
)
927 struct stat dangling_link_sb
;
928 if (lstat (dst_name
, &dangling_link_sb
) == 0
929 && S_ISLNK (dangling_link_sb
.st_mode
))
931 if (x
->open_dangling_dest_symlink
)
933 dest_desc
= open (dst_name
, open_flags
,
934 dst_mode
& ~omitted_permissions
);
939 error (0, 0, _("not writing through dangling symlink %s"),
947 /* Improve quality of diagnostic when a nonexistent dst_name
948 ends in a slash and open fails with errno == EISDIR. */
949 if (dest_desc
< 0 && dest_errno
== EISDIR
950 && *dst_name
&& dst_name
[strlen (dst_name
) - 1] == '/')
951 dest_errno
= ENOTDIR
;
955 omitted_permissions
= 0;
960 error (0, dest_errno
, _("cannot create regular file %s"),
966 if (fstat (dest_desc
, &sb
) != 0)
968 error (0, errno
, _("cannot fstat %s"), quote (dst_name
));
970 goto close_src_and_dst_desc
;
973 /* --attributes-only overrides --reflink. */
974 if (data_copy_required
&& x
->reflink_mode
)
976 bool clone_ok
= clone_file (dest_desc
, source_desc
) == 0;
977 if (clone_ok
|| x
->reflink_mode
== REFLINK_ALWAYS
)
981 error (0, errno
, _("failed to clone %s from %s"),
982 quote_n (0, dst_name
), quote_n (1, src_name
));
984 goto close_src_and_dst_desc
;
986 data_copy_required
= false;
990 if (data_copy_required
)
992 typedef uintptr_t word
;
994 /* Choose a suitable buffer size; it may be adjusted later. */
995 size_t buf_alignment
= lcm (getpagesize (), sizeof (word
));
996 size_t buf_alignment_slop
= sizeof (word
) + buf_alignment
- 1;
997 size_t buf_size
= io_blksize (sb
);
999 /* Deal with sparse files. */
1000 bool make_holes
= false;
1001 bool sparse_src
= false;
1003 if (S_ISREG (sb
.st_mode
))
1005 /* Even with --sparse=always, try to create holes only
1006 if the destination is a regular file. */
1007 if (x
->sparse_mode
== SPARSE_ALWAYS
)
1010 /* Use a heuristic to determine whether SRC_NAME contains any sparse
1011 blocks. If the file has fewer blocks than would normally be
1012 needed for a file of its size, then at least one of the blocks in
1013 the file is a hole. */
1014 sparse_src
= is_probably_sparse (&src_open_sb
);
1015 if (x
->sparse_mode
== SPARSE_AUTO
&& sparse_src
)
1019 /* If not making a sparse file, try to use a more-efficient
1023 /* Compute the least common multiple of the input and output
1024 buffer sizes, adjusting for outlandish values. */
1025 size_t blcm_max
= MIN (SIZE_MAX
, SSIZE_MAX
) - buf_alignment_slop
;
1026 size_t blcm
= buffer_lcm (io_blksize (src_open_sb
), buf_size
,
1029 /* Do not bother with a buffer larger than the input file, plus one
1030 byte to make sure the file has not grown while reading it. */
1031 if (S_ISREG (src_open_sb
.st_mode
) && src_open_sb
.st_size
< buf_size
)
1032 buf_size
= src_open_sb
.st_size
+ 1;
1034 /* However, stick with a block size that is a positive multiple of
1035 blcm, overriding the above adjustments. Watch out for
1037 buf_size
+= blcm
- 1;
1038 buf_size
-= buf_size
% blcm
;
1039 if (buf_size
== 0 || blcm_max
< buf_size
)
1043 /* Make a buffer with space for a sentinel at the end. */
1044 buf_alloc
= xmalloc (buf_size
+ buf_alignment_slop
);
1045 buf
= ptr_align (buf_alloc
, buf_alignment
);
1049 bool normal_copy_required
;
1051 /* Perform an efficient extent-based copy, falling back to the
1052 standard copy only if the initial extent scan fails. If the
1053 '--sparse=never' option is specified, write all data but use
1054 any extents to read more efficiently. */
1055 if (extent_copy (source_desc
, dest_desc
, buf
, buf_size
,
1056 src_open_sb
.st_size
,
1057 S_ISREG (sb
.st_mode
) ? x
->sparse_mode
: SPARSE_NEVER
,
1058 src_name
, dst_name
, &normal_copy_required
))
1059 goto preserve_metadata
;
1061 if (! normal_copy_required
)
1064 goto close_src_and_dst_desc
;
1069 bool wrote_hole_at_eof
;
1070 if ( ! sparse_copy (source_desc
, dest_desc
, buf
, buf_size
,
1071 make_holes
, src_name
, dst_name
,
1072 UINTMAX_MAX
, &n_read
,
1074 || (wrote_hole_at_eof
&&
1075 ftruncate (dest_desc
, n_read
) < 0))
1077 error (0, errno
, _("failed to extend %s"), quote (dst_name
));
1079 goto close_src_and_dst_desc
;
1084 if (x
->preserve_timestamps
)
1086 struct timespec timespec
[2];
1087 timespec
[0] = get_stat_atime (src_sb
);
1088 timespec
[1] = get_stat_mtime (src_sb
);
1090 if (fdutimens (dest_desc
, dst_name
, timespec
) != 0)
1092 error (0, errno
, _("preserving times for %s"), quote (dst_name
));
1093 if (x
->require_preserve
)
1096 goto close_src_and_dst_desc
;
1101 /* Set ownership before xattrs as changing owners will
1102 clear capabilities. */
1103 if (x
->preserve_ownership
&& ! SAME_OWNER_AND_GROUP (*src_sb
, sb
))
1105 switch (set_owner (x
, dst_name
, dest_desc
, src_sb
, *new_dst
, &sb
))
1109 goto close_src_and_dst_desc
;
1112 src_mode
&= ~ (S_ISUID
| S_ISGID
| S_ISVTX
);
1117 /* To allow copying xattrs on read-only files, temporarily chmod u+rw.
1118 This workaround is required as an inode permission check is done
1119 by xattr_permission() in fs/xattr.c of the GNU/Linux kernel tree. */
1120 if (x
->preserve_xattr
)
1122 bool access_changed
= false;
1124 if (!(sb
.st_mode
& S_IWUSR
) && geteuid () != 0)
1125 access_changed
= fchmod_or_lchmod (dest_desc
, dst_name
, 0600) == 0;
1127 if (!copy_attr (src_name
, source_desc
, dst_name
, dest_desc
, x
)
1128 && x
->require_preserve_xattr
)
1132 fchmod_or_lchmod (dest_desc
, dst_name
, dst_mode
& ~omitted_permissions
);
1135 set_author (dst_name
, dest_desc
, src_sb
);
1137 if (x
->preserve_mode
|| x
->move_mode
)
1139 if (copy_acl (src_name
, source_desc
, dst_name
, dest_desc
, src_mode
) != 0
1140 && x
->require_preserve
)
1143 else if (x
->set_mode
)
1145 if (set_acl (dst_name
, dest_desc
, x
->mode
) != 0)
1148 else if (omitted_permissions
)
1150 omitted_permissions
&= ~ cached_umask ();
1151 if (omitted_permissions
1152 && fchmod_or_lchmod (dest_desc
, dst_name
, dst_mode
) != 0)
1154 error (0, errno
, _("preserving permissions for %s"),
1156 if (x
->require_preserve
)
1161 close_src_and_dst_desc
:
1162 if (close (dest_desc
) < 0)
1164 error (0, errno
, _("closing %s"), quote (dst_name
));
1168 if (close (source_desc
) < 0)
1170 error (0, errno
, _("closing %s"), quote (src_name
));
1179 /* Return true if it's ok that the source and destination
1180 files are the `same' by some measure. The goal is to avoid
1181 making the `copy' operation remove both copies of the file
1182 in that case, while still allowing the user to e.g., move or
1183 copy a regular file onto a symlink that points to it.
1184 Try to minimize the cost of this function in the common case.
1185 Set *RETURN_NOW if we've determined that the caller has no more
1186 work to do and should return successfully, right away.
1188 Set *UNLINK_SRC if we've determined that the caller wants to do
1189 `rename (a, b)' where `a' and `b' are distinct hard links to the same
1190 file. In that case, the caller should try to unlink `a' and then return
1191 successfully. Ideally, we wouldn't have to do that, and we'd be
1192 able to rely on rename to remove the source file. However, POSIX
1193 mistakenly requires that such a rename call do *nothing* and return
1197 same_file_ok (char const *src_name
, struct stat
const *src_sb
,
1198 char const *dst_name
, struct stat
const *dst_sb
,
1199 const struct cp_options
*x
, bool *return_now
, bool *unlink_src
)
1201 const struct stat
*src_sb_link
;
1202 const struct stat
*dst_sb_link
;
1203 struct stat tmp_dst_sb
;
1204 struct stat tmp_src_sb
;
1207 bool same
= SAME_INODE (*src_sb
, *dst_sb
);
1209 *return_now
= false;
1210 *unlink_src
= false;
1212 /* FIXME: this should (at the very least) be moved into the following
1213 if-block. More likely, it should be removed, because it inhibits
1214 making backups. But removing it will result in a change in behavior
1215 that will probably have to be documented -- and tests will have to
1217 if (same
&& x
->hard_link
)
1223 if (x
->dereference
== DEREF_NEVER
)
1227 /* If both the source and destination files are symlinks (and we'll
1228 know this here IFF preserving symlinks), then it's ok -- as long
1229 as they are distinct. */
1230 if (S_ISLNK (src_sb
->st_mode
) && S_ISLNK (dst_sb
->st_mode
))
1231 return ! same_name (src_name
, dst_name
);
1233 src_sb_link
= src_sb
;
1234 dst_sb_link
= dst_sb
;
1241 if (lstat (dst_name
, &tmp_dst_sb
) != 0
1242 || lstat (src_name
, &tmp_src_sb
) != 0)
1245 src_sb_link
= &tmp_src_sb
;
1246 dst_sb_link
= &tmp_dst_sb
;
1248 same_link
= SAME_INODE (*src_sb_link
, *dst_sb_link
);
1250 /* If both are symlinks, then it's ok, but only if the destination
1251 will be unlinked before being opened. This is like the test
1252 above, but with the addition of the unlink_dest_before_opening
1253 conjunct because otherwise, with two symlinks to the same target,
1254 we'd end up truncating the source file. */
1255 if (S_ISLNK (src_sb_link
->st_mode
) && S_ISLNK (dst_sb_link
->st_mode
)
1256 && x
->unlink_dest_before_opening
)
1260 /* The backup code ensures there's a copy, so it's usually ok to
1261 remove any destination file. One exception is when both
1262 source and destination are the same directory entry. In that
1263 case, moving the destination file aside (in making the backup)
1264 would also rename the source file and result in an error. */
1265 if (x
->backup_type
!= no_backups
)
1269 /* In copy mode when dereferencing symlinks, if the source is a
1270 symlink and the dest is not, then backing up the destination
1271 (moving it aside) would make it a dangling symlink, and the
1272 subsequent attempt to open it in copy_reg would fail with
1273 a misleading diagnostic. Avoid that by returning zero in
1274 that case so the caller can make cp (or mv when it has to
1275 resort to reading the source file) fail now. */
1277 /* FIXME-note: even with the following kludge, we can still provoke
1278 the offending diagnostic. It's just a little harder to do :-)
1279 $ rm -f a b c; touch c; ln -s c b; ln -s b a; cp -b a b
1280 cp: cannot open `a' for reading: No such file or directory
1281 That's misleading, since a subsequent `ls' shows that `a'
1283 One solution would be to open the source file *before* moving
1284 aside the destination, but that'd involve a big rewrite. */
1286 && x
->dereference
!= DEREF_NEVER
1287 && S_ISLNK (src_sb_link
->st_mode
)
1288 && ! S_ISLNK (dst_sb_link
->st_mode
))
1294 return ! same_name (src_name
, dst_name
);
1298 /* FIXME: use or remove */
1300 /* If we're making a backup, we'll detect the problem case in
1301 copy_reg because SRC_NAME will no longer exist. Allowing
1302 the test to be deferred lets cp do some useful things.
1303 But when creating hardlinks and SRC_NAME is a symlink
1304 but DST_NAME is not we must test anyway. */
1306 || !S_ISLNK (src_sb_link
->st_mode
)
1307 || S_ISLNK (dst_sb_link
->st_mode
))
1310 if (x
->dereference
!= DEREF_NEVER
)
1314 /* They may refer to the same file if we're in move mode and the
1315 target is a symlink. That is ok, since we remove any existing
1316 destination file before opening it -- via `rename' if they're on
1317 the same file system, via `unlink (DST_NAME)' otherwise.
1318 It's also ok if they're distinct hard links to the same file. */
1319 if (x
->move_mode
|| x
->unlink_dest_before_opening
)
1321 if (S_ISLNK (dst_sb_link
->st_mode
))
1325 && 1 < dst_sb_link
->st_nlink
1326 && ! same_name (src_name
, dst_name
))
1337 /* If neither is a symlink, then it's ok as long as they aren't
1338 hard links to the same file. */
1339 if (!S_ISLNK (src_sb_link
->st_mode
) && !S_ISLNK (dst_sb_link
->st_mode
))
1341 if (!SAME_INODE (*src_sb_link
, *dst_sb_link
))
1344 /* If they are the same file, it's ok if we're making hard links. */
1352 /* It's ok to remove a destination symlink. But that works only when we
1353 unlink before opening the destination and when the source and destination
1354 files are on the same partition. */
1355 if (x
->unlink_dest_before_opening
1356 && S_ISLNK (dst_sb_link
->st_mode
))
1357 return dst_sb_link
->st_dev
== src_sb_link
->st_dev
;
1359 if (x
->dereference
== DEREF_NEVER
)
1361 if ( ! S_ISLNK (src_sb_link
->st_mode
))
1362 tmp_src_sb
= *src_sb_link
;
1363 else if (stat (src_name
, &tmp_src_sb
) != 0)
1366 if ( ! S_ISLNK (dst_sb_link
->st_mode
))
1367 tmp_dst_sb
= *dst_sb_link
;
1368 else if (stat (dst_name
, &tmp_dst_sb
) != 0)
1371 if ( ! SAME_INODE (tmp_src_sb
, tmp_dst_sb
))
1374 /* FIXME: shouldn't this be testing whether we're making symlinks? */
1385 /* Return true if FILE, with mode MODE, is writable in the sense of 'mv'.
1386 Always consider a symbolic link to be writable. */
1388 writable_destination (char const *file
, mode_t mode
)
1390 return (S_ISLNK (mode
)
1391 || can_write_any_file ()
1392 || euidaccess (file
, W_OK
) == 0);
1396 overwrite_prompt (char const *dst_name
, struct stat
const *dst_sb
)
1398 if (! writable_destination (dst_name
, dst_sb
->st_mode
))
1400 char perms
[12]; /* "-rwxrwxrwx " ls-style modes. */
1401 strmode (dst_sb
->st_mode
, perms
);
1404 _("%s: try to overwrite %s, overriding mode %04lo (%s)? "),
1405 program_name
, quote (dst_name
),
1406 (unsigned long int) (dst_sb
->st_mode
& CHMOD_MODE_BITS
),
1411 fprintf (stderr
, _("%s: overwrite %s? "),
1412 program_name
, quote (dst_name
));
1416 /* Initialize the hash table implementing a set of F_triple entries
1417 corresponding to destination files. */
1419 dest_info_init (struct cp_options
*x
)
1422 = hash_initialize (DEST_INFO_INITIAL_CAPACITY
,
1429 /* Initialize the hash table implementing a set of F_triple entries
1430 corresponding to source files listed on the command line. */
1432 src_info_init (struct cp_options
*x
)
1435 /* Note that we use triple_hash_no_name here.
1436 Contrast with the use of triple_hash above.
1437 That is necessary because a source file may be specified
1438 in many different ways. We want to warn about this
1444 = hash_initialize (DEST_INFO_INITIAL_CAPACITY
,
1446 triple_hash_no_name
,
1451 /* When effecting a move (e.g., for mv(1)), and given the name DST_NAME
1452 of the destination and a corresponding stat buffer, DST_SB, return
1453 true if the logical `move' operation should _not_ proceed.
1454 Otherwise, return false.
1455 Depending on options specified in X, this code may issue an
1456 interactive prompt asking whether it's ok to overwrite DST_NAME. */
1458 abandon_move (const struct cp_options
*x
,
1459 char const *dst_name
,
1460 struct stat
const *dst_sb
)
1462 assert (x
->move_mode
);
1463 return (x
->interactive
== I_ALWAYS_NO
1464 || ((x
->interactive
== I_ASK_USER
1465 || (x
->interactive
== I_UNSPECIFIED
1467 && ! writable_destination (dst_name
, dst_sb
->st_mode
)))
1468 && (overwrite_prompt (dst_name
, dst_sb
), 1)
1472 /* Print --verbose output on standard output, e.g. `new' -> `old'.
1473 If BACKUP_DST_NAME is non-NULL, then also indicate that it is
1474 the name of a backup file. */
1476 emit_verbose (char const *src
, char const *dst
, char const *backup_dst_name
)
1478 printf ("%s -> %s", quote_n (0, src
), quote_n (1, dst
));
1479 if (backup_dst_name
)
1480 printf (_(" (backup: %s)"), quote (backup_dst_name
));
1484 /* A wrapper around "setfscreatecon (NULL)" that exits upon failure. */
1486 restore_default_fscreatecon_or_die (void)
1488 if (setfscreatecon (NULL
) != 0)
1489 error (EXIT_FAILURE
, errno
,
1490 _("failed to restore the default file creation context"));
1493 /* Create a hard link DST_NAME to SRC_NAME, honoring the REPLACE and
1494 VERBOSE settings. Return true upon success. Otherwise, diagnose
1495 the failure and return false.
1496 If SRC_NAME is a symbolic link it will not be followed. If the system
1497 doesn't support hard links to symbolic links, then DST_NAME will
1498 be created as a symbolic link to SRC_NAME. */
1500 create_hard_link (char const *src_name
, char const *dst_name
,
1501 bool replace
, bool verbose
)
1503 /* We want to guarantee that symlinks are not followed. */
1504 bool link_failed
= (linkat (AT_FDCWD
, src_name
, AT_FDCWD
, dst_name
, 0) != 0);
1506 /* If the link failed because of an existing destination,
1507 remove that file and then call link again. */
1508 if (link_failed
&& replace
&& errno
== EEXIST
)
1510 if (unlink (dst_name
) != 0)
1512 error (0, errno
, _("cannot remove %s"), quote (dst_name
));
1516 printf (_("removed %s\n"), quote (dst_name
));
1517 link_failed
= (linkat (AT_FDCWD
, src_name
, AT_FDCWD
, dst_name
, 0) != 0);
1522 error (0, errno
, _("cannot create hard link %s to %s"),
1523 quote_n (0, dst_name
), quote_n (1, src_name
));
1530 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
1531 any type. NEW_DST should be true if the file DST_NAME cannot
1532 exist because its parent directory was just created; NEW_DST should
1533 be false if DST_NAME might already exist. DEVICE is the device
1534 number of the parent directory, or 0 if the parent of this file is
1535 not known. ANCESTORS points to a linked, null terminated list of
1536 devices and inodes of parent directories of SRC_NAME. COMMAND_LINE_ARG
1537 is true iff SRC_NAME was specified on the command line.
1538 FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG is both input and output.
1539 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
1540 same as) DST_NAME; otherwise, clear it.
1541 Return true if successful. */
1543 copy_internal (char const *src_name
, char const *dst_name
,
1546 struct dir_list
*ancestors
,
1547 const struct cp_options
*x
,
1548 bool command_line_arg
,
1549 bool *first_dir_created_per_command_line_arg
,
1550 bool *copy_into_self
,
1551 bool *rename_succeeded
)
1556 mode_t dst_mode
IF_LINT ( = 0);
1557 mode_t dst_mode_bits
;
1558 mode_t omitted_permissions
;
1559 bool restore_dst_mode
= false;
1560 char *earlier_file
= NULL
;
1561 char *dst_backup
= NULL
;
1562 bool backup_succeeded
= false;
1564 bool copied_as_regular
= false;
1565 bool dest_is_symlink
= false;
1566 bool have_dst_lstat
= false;
1568 if (x
->move_mode
&& rename_succeeded
)
1569 *rename_succeeded
= false;
1571 *copy_into_self
= false;
1573 if (XSTAT (x
, src_name
, &src_sb
) != 0)
1575 error (0, errno
, _("cannot stat %s"), quote (src_name
));
1579 src_mode
= src_sb
.st_mode
;
1581 if (S_ISDIR (src_mode
) && !x
->recursive
)
1583 error (0, 0, _("omitting directory %s"), quote (src_name
));
1587 /* Detect the case in which the same source file appears more than
1588 once on the command line and no backup option has been selected.
1589 If so, simply warn and don't copy it the second time.
1590 This check is enabled only if x->src_info is non-NULL. */
1591 if (command_line_arg
)
1593 if ( ! S_ISDIR (src_sb
.st_mode
)
1594 && x
->backup_type
== no_backups
1595 && seen_file (x
->src_info
, src_name
, &src_sb
))
1597 error (0, 0, _("warning: source file %s specified more than once"),
1602 record_file (x
->src_info
, src_name
, &src_sb
);
1607 /* Regular files can be created by writing through symbolic
1608 links, but other files cannot. So use stat on the
1609 destination when copying a regular file, and lstat otherwise.
1610 However, if we intend to unlink or remove the destination
1611 first, use lstat, since a copy won't actually be made to the
1612 destination in that case. */
1614 ((S_ISREG (src_mode
)
1615 || (x
->copy_as_regular
1616 && ! (S_ISDIR (src_mode
) || S_ISLNK (src_mode
))))
1617 && ! (x
->move_mode
|| x
->symbolic_link
|| x
->hard_link
1618 || x
->backup_type
!= no_backups
1619 || x
->unlink_dest_before_opening
));
1621 ? stat (dst_name
, &dst_sb
)
1622 : lstat (dst_name
, &dst_sb
))
1625 if (errno
!= ENOENT
)
1627 error (0, errno
, _("cannot stat %s"), quote (dst_name
));
1636 { /* Here, we know that dst_name exists, at least to the point
1637 that it is stat'able or lstat'able. */
1641 have_dst_lstat
= !use_stat
;
1642 if (! same_file_ok (src_name
, &src_sb
, dst_name
, &dst_sb
,
1643 x
, &return_now
, &unlink_src
))
1645 error (0, 0, _("%s and %s are the same file"),
1646 quote_n (0, src_name
), quote_n (1, dst_name
));
1650 if (!S_ISDIR (src_mode
) && x
->update
)
1652 /* When preserving time stamps (but not moving within a file
1653 system), don't worry if the destination time stamp is
1654 less than the source merely because of time stamp
1656 int options
= ((x
->preserve_timestamps
1658 && dst_sb
.st_dev
== src_sb
.st_dev
))
1659 ? UTIMECMP_TRUNCATE_SOURCE
1662 if (0 <= utimecmp (dst_name
, &dst_sb
, &src_sb
, options
))
1664 /* We're using --update and the destination is not older
1665 than the source, so do not copy or move. Pretend the
1666 rename succeeded, so the caller (if it's mv) doesn't
1667 end up removing the source file. */
1668 if (rename_succeeded
)
1669 *rename_succeeded
= true;
1671 /* However, we still must record that we've processed
1672 this src/dest pair, in case this source file is
1673 hard-linked to another one. In that case, we'll use
1674 the mapping information to link the corresponding
1675 destination names. */
1676 earlier_file
= remember_copied (dst_name
, src_sb
.st_ino
,
1680 /* Note we currently replace DST_NAME unconditionally,
1681 even if it was a newer separate file. */
1682 if (! create_hard_link (earlier_file
, dst_name
, true,
1693 /* When there is an existing destination file, we may end up
1694 returning early, and hence not copying/moving the file.
1695 This may be due to an interactive `negative' reply to the
1696 prompt about the existing file. It may also be due to the
1697 use of the --reply=no option.
1699 cp and mv treat -i and -f differently. */
1702 if (abandon_move (x
, dst_name
, &dst_sb
)
1703 || (unlink_src
&& unlink (src_name
) == 0))
1705 /* Pretend the rename succeeded, so the caller (mv)
1706 doesn't end up removing the source file. */
1707 if (rename_succeeded
)
1708 *rename_succeeded
= true;
1709 if (unlink_src
&& x
->verbose
)
1710 printf (_("removed %s\n"), quote (src_name
));
1715 error (0, errno
, _("cannot remove %s"), quote (src_name
));
1721 if (! S_ISDIR (src_mode
)
1722 && (x
->interactive
== I_ALWAYS_NO
1723 || (x
->interactive
== I_ASK_USER
1724 && (overwrite_prompt (dst_name
, &dst_sb
), 1)
1732 if (!S_ISDIR (dst_sb
.st_mode
))
1734 if (S_ISDIR (src_mode
))
1736 if (x
->move_mode
&& x
->backup_type
!= no_backups
)
1738 /* Moving a directory onto an existing
1739 non-directory is ok only with --backup. */
1744 _("cannot overwrite non-directory %s with directory %s"),
1745 quote_n (0, dst_name
), quote_n (1, src_name
));
1750 /* Don't let the user destroy their data, even if they try hard:
1751 This mv command must fail (likewise for cp):
1752 rm -rf a b c; mkdir a b c; touch a/f b/f; mv a/f b/f c
1753 Otherwise, the contents of b/f would be lost.
1754 In the case of `cp', b/f would be lost if the user simulated
1755 a move using cp and rm.
1756 Note that it works fine if you use --backup=numbered. */
1757 if (command_line_arg
1758 && x
->backup_type
!= numbered_backups
1759 && seen_file (x
->dest_info
, dst_name
, &dst_sb
))
1762 _("will not overwrite just-created %s with %s"),
1763 quote_n (0, dst_name
), quote_n (1, src_name
));
1768 if (!S_ISDIR (src_mode
))
1770 if (S_ISDIR (dst_sb
.st_mode
))
1772 if (x
->move_mode
&& x
->backup_type
!= no_backups
)
1774 /* Moving a non-directory onto an existing
1775 directory is ok only with --backup. */
1780 _("cannot overwrite directory %s with non-directory"),
1789 /* Don't allow user to move a directory onto a non-directory. */
1790 if (S_ISDIR (src_sb
.st_mode
) && !S_ISDIR (dst_sb
.st_mode
)
1791 && x
->backup_type
== no_backups
)
1794 _("cannot move directory onto non-directory: %s -> %s"),
1795 quote_n (0, src_name
), quote_n (0, dst_name
));
1800 if (x
->backup_type
!= no_backups
1801 /* Don't try to back up a destination if the last
1802 component of src_name is "." or "..". */
1803 && ! dot_or_dotdot (last_component (src_name
))
1804 /* Create a backup of each destination directory in move mode,
1805 but not in copy mode. FIXME: it might make sense to add an
1806 option to suppress backup creation also for move mode.
1807 That would let one use mv to merge new content into an
1808 existing hierarchy. */
1809 && (x
->move_mode
|| ! S_ISDIR (dst_sb
.st_mode
)))
1811 char *tmp_backup
= find_backup_file_name (dst_name
,
1814 /* Detect (and fail) when creating the backup file would
1815 destroy the source file. Before, running the commands
1816 cd /tmp; rm -f a a~; : > a; echo A > a~; cp --b=simple a~ a
1817 would leave two zero-length files: a and a~. */
1818 /* FIXME: but simply change e.g., the final a~ to `./a~'
1819 and the source will still be destroyed. */
1820 if (STREQ (tmp_backup
, src_name
))
1824 ? _("backing up %s would destroy source; %s not moved")
1825 : _("backing up %s would destroy source; %s not copied"));
1827 quote_n (0, dst_name
),
1828 quote_n (1, src_name
));
1834 Using alloca for a file name that may be arbitrarily
1835 long is not recommended. In fact, even forming such a name
1836 should be discouraged. Eventually, this code will be rewritten
1837 to use fts, so using alloca here will be less of a problem. */
1838 ASSIGN_STRDUPA (dst_backup
, tmp_backup
);
1840 if (rename (dst_name
, dst_backup
) != 0)
1842 if (errno
!= ENOENT
)
1844 error (0, errno
, _("cannot backup %s"), quote (dst_name
));
1854 backup_succeeded
= true;
1858 else if (! S_ISDIR (dst_sb
.st_mode
)
1859 /* Never unlink dst_name when in move mode. */
1861 && (x
->unlink_dest_before_opening
1862 || (x
->preserve_links
&& 1 < dst_sb
.st_nlink
)
1863 || (x
->dereference
== DEREF_NEVER
1864 && ! S_ISREG (src_sb
.st_mode
))
1867 if (unlink (dst_name
) != 0 && errno
!= ENOENT
)
1869 error (0, errno
, _("cannot remove %s"), quote (dst_name
));
1874 printf (_("removed %s\n"), quote (dst_name
));
1879 /* Ensure we don't try to copy through a symlink that was
1880 created by a prior call to this function. */
1881 if (command_line_arg
1884 && x
->backup_type
== no_backups
)
1886 bool lstat_ok
= true;
1887 struct stat tmp_buf
;
1888 struct stat
*dst_lstat_sb
;
1890 /* If we called lstat above, good: use that data.
1891 Otherwise, call lstat here, in case dst_name is a symlink. */
1893 dst_lstat_sb
= &dst_sb
;
1896 if (lstat (dst_name
, &tmp_buf
) == 0)
1897 dst_lstat_sb
= &tmp_buf
;
1902 /* Never copy through a symlink we've just created. */
1904 && S_ISLNK (dst_lstat_sb
->st_mode
)
1905 && seen_file (x
->dest_info
, dst_name
, dst_lstat_sb
))
1908 _("will not copy %s through just-created symlink %s"),
1909 quote_n (0, src_name
), quote_n (1, dst_name
));
1914 /* If the source is a directory, we don't always create the destination
1915 directory. So --verbose should not announce anything until we're
1916 sure we'll create a directory. */
1917 if (x
->verbose
&& !S_ISDIR (src_mode
))
1918 emit_verbose (src_name
, dst_name
, backup_succeeded
? dst_backup
: NULL
);
1920 /* Associate the destination file name with the source device and inode
1921 so that if we encounter a matching dev/ino pair in the source tree
1922 we can arrange to create a hard link between the corresponding names
1923 in the destination tree.
1925 When using the --link (-l) option, there is no need to take special
1926 measures, because (barring race conditions) files that are hard-linked
1927 in the source tree will also be hard-linked in the destination tree.
1929 Sometimes, when preserving links, we have to record dev/ino even
1930 though st_nlink == 1:
1931 - when in move_mode, since we may be moving a group of N hard-linked
1932 files (via two or more command line arguments) to a different
1933 partition; the links may be distributed among the command line
1934 arguments (possibly hierarchies) so that the link count of
1935 the final, once-linked source file is reduced to 1 when it is
1936 considered below. But in this case (for mv) we don't need to
1937 incur the expense of recording the dev/ino => name mapping; all we
1938 really need is a lookup, to see if the dev/ino pair has already
1940 - when using -H and processing a command line argument;
1941 that command line argument could be a symlink pointing to another
1942 command line argument. With `cp -H --preserve=link', we hard-link
1943 those two destination files.
1944 - likewise for -L except that it applies to all files, not just
1945 command line arguments.
1947 Also, with --recursive, record dev/ino of each command-line directory.
1948 We'll use that info to detect this problem: cp -R dir dir. */
1950 if (x
->move_mode
&& src_sb
.st_nlink
== 1)
1952 earlier_file
= src_to_dest_lookup (src_sb
.st_ino
, src_sb
.st_dev
);
1954 else if (x
->preserve_links
1956 && (1 < src_sb
.st_nlink
1957 || (command_line_arg
1958 && x
->dereference
== DEREF_COMMAND_LINE_ARGUMENTS
)
1959 || x
->dereference
== DEREF_ALWAYS
))
1961 earlier_file
= remember_copied (dst_name
, src_sb
.st_ino
, src_sb
.st_dev
);
1963 else if (x
->recursive
&& S_ISDIR (src_mode
))
1965 if (command_line_arg
)
1966 earlier_file
= remember_copied (dst_name
, src_sb
.st_ino
, src_sb
.st_dev
);
1968 earlier_file
= src_to_dest_lookup (src_sb
.st_ino
, src_sb
.st_dev
);
1971 /* Did we copy this inode somewhere else (in this command line argument)
1972 and therefore this is a second hard link to the inode? */
1976 /* Avoid damaging the destination file system by refusing to preserve
1977 hard-linked directories (which are found at least in Netapp snapshot
1979 if (S_ISDIR (src_mode
))
1981 /* If src_name and earlier_file refer to the same directory entry,
1982 then warn about copying a directory into itself. */
1983 if (same_name (src_name
, earlier_file
))
1985 error (0, 0, _("cannot copy a directory, %s, into itself, %s"),
1986 quote_n (0, top_level_src_name
),
1987 quote_n (1, top_level_dst_name
));
1988 *copy_into_self
= true;
1991 else if (x
->dereference
== DEREF_ALWAYS
)
1993 /* This happens when e.g., encountering a directory for the
1994 second or subsequent time via symlinks when cp is invoked
1995 with -R and -L. E.g.,
1996 rm -rf a b c d; mkdir a b c d; ln -s ../c a; ln -s ../c b;
2002 error (0, 0, _("will not create hard link %s to directory %s"),
2003 quote_n (0, dst_name
), quote_n (1, earlier_file
));
2009 if (! create_hard_link (earlier_file
, dst_name
, true, x
->verbose
))
2018 if (rename (src_name
, dst_name
) == 0)
2020 if (x
->verbose
&& S_ISDIR (src_mode
))
2021 emit_verbose (src_name
, dst_name
,
2022 backup_succeeded
? dst_backup
: NULL
);
2024 if (rename_succeeded
)
2025 *rename_succeeded
= true;
2027 if (command_line_arg
)
2029 /* Record destination dev/ino/name, so that if we are asked
2030 to overwrite that file again, we can detect it and fail. */
2031 /* It's fine to use the _source_ stat buffer (src_sb) to get the
2032 _destination_ dev/ino, since the rename above can't have
2033 changed those, and `mv' always uses lstat.
2034 We could limit it further by operating
2035 only on non-directories. */
2036 record_file (x
->dest_info
, dst_name
, &src_sb
);
2042 /* FIXME: someday, consider what to do when moving a directory into
2043 itself but when source and destination are on different devices. */
2045 /* This happens when attempting to rename a directory to a
2046 subdirectory of itself. */
2047 if (errno
== EINVAL
)
2049 /* FIXME: this is a little fragile in that it relies on rename(2)
2050 failing with a specific errno value. Expect problems on
2051 non-POSIX systems. */
2052 error (0, 0, _("cannot move %s to a subdirectory of itself, %s"),
2053 quote_n (0, top_level_src_name
),
2054 quote_n (1, top_level_dst_name
));
2056 /* Note that there is no need to call forget_created here,
2057 (compare with the other calls in this file) since the
2058 destination directory didn't exist before. */
2060 *copy_into_self
= true;
2061 /* FIXME-cleanup: Don't return true here; adjust mv.c accordingly.
2062 The only caller that uses this code (mv.c) ends up setting its
2063 exit status to nonzero when copy_into_self is nonzero. */
2067 /* WARNING: there probably exist systems for which an inter-device
2068 rename fails with a value of errno not handled here.
2069 If/as those are reported, add them to the condition below.
2070 If this happens to you, please do the following and send the output
2071 to the bug-reporting address (e.g., in the output of cp --help):
2072 touch k; perl -e 'rename "k","/tmp/k" or print "$!(",$!+0,")\n"'
2073 where your current directory is on one partion and /tmp is the other.
2074 Also, please try to find the E* errno macro name corresponding to
2075 the diagnostic and parenthesized integer, and include that in your
2076 e-mail. One way to do that is to run a command like this
2077 find /usr/include/. -type f \
2078 | xargs grep 'define.*\<E[A-Z]*\>.*\<18\>' /dev/null
2079 where you'd replace `18' with the integer in parentheses that
2080 was output from the perl one-liner above.
2081 If necessary, of course, change `/tmp' to some other directory. */
2084 /* There are many ways this can happen due to a race condition.
2085 When something happens between the initial XSTAT and the
2086 subsequent rename, we can get many different types of errors.
2087 For example, if the destination is initially a non-directory
2088 or non-existent, but it is created as a directory, the rename
2089 fails. If two `mv' commands try to rename the same file at
2090 about the same time, one will succeed and the other will fail.
2091 If the permissions on the directory containing the source or
2092 destination file are made too restrictive, the rename will
2095 _("cannot move %s to %s"),
2096 quote_n (0, src_name
), quote_n (1, dst_name
));
2097 forget_created (src_sb
.st_ino
, src_sb
.st_dev
);
2101 /* The rename attempt has failed. Remove any existing destination
2102 file so that a cross-device `mv' acts as if it were really using
2103 the rename syscall. */
2104 if (unlink (dst_name
) != 0 && errno
!= ENOENT
)
2107 _("inter-device move failed: %s to %s; unable to remove target"),
2108 quote_n (0, src_name
), quote_n (1, dst_name
));
2109 forget_created (src_sb
.st_ino
, src_sb
.st_dev
);
2116 /* If the ownership might change, or if it is a directory (whose
2117 special mode bits may change after the directory is created),
2118 omit some permissions at first, so unauthorized users cannot nip
2119 in before the file is ready. */
2120 dst_mode_bits
= (x
->set_mode
? x
->mode
: src_mode
) & CHMOD_MODE_BITS
;
2121 omitted_permissions
=
2123 & (x
->preserve_ownership
? S_IRWXG
| S_IRWXO
2124 : S_ISDIR (src_mode
) ? S_IWGRP
| S_IWOTH
2129 if (x
->preserve_security_context
)
2131 bool all_errors
= !x
->data_copy_required
|| x
->require_preserve_context
;
2132 bool some_errors
= !all_errors
&& !x
->reduce_diagnostics
;
2133 security_context_t con
;
2135 if (0 <= lgetfilecon (src_name
, &con
))
2137 if (setfscreatecon (con
) < 0)
2139 if (all_errors
|| (some_errors
&& !errno_unsupported (errno
)))
2141 _("failed to set default file creation context to %s"),
2143 if (x
->require_preserve_context
)
2153 if (all_errors
|| (some_errors
&& !errno_unsupported (errno
)))
2156 _("failed to get security context of %s"),
2159 if (x
->require_preserve_context
)
2164 if (S_ISDIR (src_mode
))
2166 struct dir_list
*dir
;
2168 /* If this directory has been copied before during the
2169 recursion, there is a symbolic link to an ancestor
2170 directory of the symbolic link. It is impossible to
2171 continue to copy this, unless we've got an infinite disk. */
2173 if (is_ancestor (&src_sb
, ancestors
))
2175 error (0, 0, _("cannot copy cyclic symbolic link %s"),
2180 /* Insert the current directory in the list of parents. */
2182 dir
= alloca (sizeof *dir
);
2183 dir
->parent
= ancestors
;
2184 dir
->ino
= src_sb
.st_ino
;
2185 dir
->dev
= src_sb
.st_dev
;
2187 if (new_dst
|| !S_ISDIR (dst_sb
.st_mode
))
2189 /* POSIX says mkdir's behavior is implementation-defined when
2190 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
2191 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
2192 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
2193 if (mkdir (dst_name
, dst_mode_bits
& ~omitted_permissions
) != 0)
2195 error (0, errno
, _("cannot create directory %s"),
2200 /* We need search and write permissions to the new directory
2201 for writing the directory's contents. Check if these
2202 permissions are there. */
2204 if (lstat (dst_name
, &dst_sb
) != 0)
2206 error (0, errno
, _("cannot stat %s"), quote (dst_name
));
2209 else if ((dst_sb
.st_mode
& S_IRWXU
) != S_IRWXU
)
2211 /* Make the new directory searchable and writable. */
2213 dst_mode
= dst_sb
.st_mode
;
2214 restore_dst_mode
= true;
2216 if (lchmod (dst_name
, dst_mode
| S_IRWXU
) != 0)
2218 error (0, errno
, _("setting permissions for %s"),
2224 /* Record the created directory's inode and device numbers into
2225 the search structure, so that we can avoid copying it again.
2226 Do this only for the first directory that is created for each
2227 source command line argument. */
2228 if (!*first_dir_created_per_command_line_arg
)
2230 remember_copied (dst_name
, dst_sb
.st_ino
, dst_sb
.st_dev
);
2231 *first_dir_created_per_command_line_arg
= true;
2235 emit_verbose (src_name
, dst_name
, NULL
);
2239 omitted_permissions
= 0;
2242 /* Decide whether to copy the contents of the directory. */
2243 if (x
->one_file_system
&& device
!= 0 && device
!= src_sb
.st_dev
)
2245 /* Here, we are crossing a file system boundary and cp's -x option
2246 is in effect: so don't copy the contents of this directory. */
2250 /* Copy the contents of the directory. Don't just return if
2251 this fails -- otherwise, the failure to read a single file
2252 in a source directory would cause the containing destination
2253 directory not to have owner/perms set properly. */
2254 delayed_ok
= copy_dir (src_name
, dst_name
, new_dst
, &src_sb
, dir
, x
,
2255 first_dir_created_per_command_line_arg
,
2259 else if (x
->symbolic_link
)
2261 dest_is_symlink
= true;
2262 if (*src_name
!= '/')
2264 /* Check that DST_NAME denotes a file in the current directory. */
2266 struct stat dst_parent_sb
;
2268 bool in_current_dir
;
2270 dst_parent
= dir_name (dst_name
);
2272 in_current_dir
= (STREQ (".", dst_parent
)
2273 /* If either stat call fails, it's ok not to report
2274 the failure and say dst_name is in the current
2275 directory. Other things will fail later. */
2276 || stat (".", &dot_sb
) != 0
2277 || stat (dst_parent
, &dst_parent_sb
) != 0
2278 || SAME_INODE (dot_sb
, dst_parent_sb
));
2281 if (! in_current_dir
)
2284 _("%s: can make relative symbolic links only in current directory"),
2289 if (symlink (src_name
, dst_name
) != 0)
2291 error (0, errno
, _("cannot create symbolic link %s to %s"),
2292 quote_n (0, dst_name
), quote_n (1, src_name
));
2297 /* POSIX 2008 states that it is implementation-defined whether
2298 link() on a symlink creates a hard-link to the symlink, or only
2299 to the referent (effectively dereferencing the symlink) (POSIX
2300 2001 required the latter behavior, although many systems provided
2301 the former). Yet cp, invoked with `--link --no-dereference',
2302 should not follow the link. We can approximate the desired
2303 behavior by skipping this hard-link creating block and instead
2304 copying the symlink, via the `S_ISLNK'- copying code below.
2305 LINK_FOLLOWS_SYMLINKS is tri-state; if it is -1, we don't know
2306 how link() behaves, so we use the fallback case for safety.
2308 Note gnulib's linkat module, guarantees that the symlink is not
2309 dereferenced. However its emulation currently doesn't maintain
2310 timestamps or ownership so we only call it when we know the
2311 emulation will not be needed. */
2312 else if (x
->hard_link
2313 && !(LINK_FOLLOWS_SYMLINKS
&& S_ISLNK (src_mode
)
2314 && x
->dereference
== DEREF_NEVER
))
2316 if (! create_hard_link (src_name
, dst_name
, false, false))
2319 else if (S_ISREG (src_mode
)
2320 || (x
->copy_as_regular
&& !S_ISLNK (src_mode
)))
2322 copied_as_regular
= true;
2323 /* POSIX says the permission bits of the source file must be
2324 used as the 3rd argument in the open call. Historical
2325 practice passed all the source mode bits to 'open', but the extra
2326 bits were ignored, so it should be the same either way. */
2327 if (! copy_reg (src_name
, dst_name
, x
, src_mode
& S_IRWXUGO
,
2328 omitted_permissions
, &new_dst
, &src_sb
))
2331 else if (S_ISFIFO (src_mode
))
2333 /* Use mknod, rather than mkfifo, because the former preserves
2334 the special mode bits of a fifo on Solaris 10, while mkfifo
2335 does not. But fall back on mkfifo, because on some BSD systems,
2336 mknod always fails when asked to create a FIFO. */
2337 if (mknod (dst_name
, src_mode
& ~omitted_permissions
, 0) != 0)
2338 if (mkfifo (dst_name
, src_mode
& ~S_IFIFO
& ~omitted_permissions
) != 0)
2340 error (0, errno
, _("cannot create fifo %s"), quote (dst_name
));
2344 else if (S_ISBLK (src_mode
) || S_ISCHR (src_mode
) || S_ISSOCK (src_mode
))
2346 if (mknod (dst_name
, src_mode
& ~omitted_permissions
, src_sb
.st_rdev
)
2349 error (0, errno
, _("cannot create special file %s"),
2354 else if (S_ISLNK (src_mode
))
2356 char *src_link_val
= areadlink_with_size (src_name
, src_sb
.st_size
);
2357 dest_is_symlink
= true;
2358 if (src_link_val
== NULL
)
2360 error (0, errno
, _("cannot read symbolic link %s"), quote (src_name
));
2364 if (symlink (src_link_val
, dst_name
) == 0)
2365 free (src_link_val
);
2368 int saved_errno
= errno
;
2369 bool same_link
= false;
2370 if (x
->update
&& !new_dst
&& S_ISLNK (dst_sb
.st_mode
)
2371 && dst_sb
.st_size
== strlen (src_link_val
))
2373 /* See if the destination is already the desired symlink.
2374 FIXME: This behavior isn't documented, and seems wrong
2375 in some cases, e.g., if the destination symlink has the
2376 wrong ownership, permissions, or time stamps. */
2377 char *dest_link_val
=
2378 areadlink_with_size (dst_name
, dst_sb
.st_size
);
2379 if (dest_link_val
&& STREQ (dest_link_val
, src_link_val
))
2381 free (dest_link_val
);
2383 free (src_link_val
);
2387 error (0, saved_errno
, _("cannot create symbolic link %s"),
2393 if (x
->preserve_security_context
)
2394 restore_default_fscreatecon_or_die ();
2396 if (x
->preserve_ownership
)
2398 /* Preserve the owner and group of the just-`copied'
2399 symbolic link, if possible. */
2401 && lchown (dst_name
, src_sb
.st_uid
, src_sb
.st_gid
) != 0
2402 && ! chown_failure_ok (x
))
2404 error (0, errno
, _("failed to preserve ownership for %s"),
2410 /* Can't preserve ownership of symlinks.
2411 FIXME: maybe give a warning or even error for symlinks
2412 in directories with the sticky bit set -- there, not
2413 preserving owner/group is a potential security problem. */
2419 error (0, 0, _("%s has unknown file type"), quote (src_name
));
2423 if (command_line_arg
&& x
->dest_info
)
2425 /* Now that the destination file is very likely to exist,
2426 add its info to the set. */
2428 if (lstat (dst_name
, &sb
) == 0)
2429 record_file (x
->dest_info
, dst_name
, &sb
);
2432 /* If we've just created a hard-link due to cp's --link option,
2434 if (x
->hard_link
&& ! S_ISDIR (src_mode
)
2435 && !(LINK_FOLLOWS_SYMLINKS
&& S_ISLNK (src_mode
)
2436 && x
->dereference
== DEREF_NEVER
))
2439 if (copied_as_regular
)
2442 /* POSIX says that `cp -p' must restore the following:
2444 - setuid, setgid bits
2446 If it fails to restore any of those, we may give a warning but
2447 the destination must not be removed.
2448 FIXME: implement the above. */
2450 /* Adjust the times (and if possible, ownership) for the copy.
2451 chown turns off set[ug]id bits for non-root,
2452 so do the chmod last. */
2454 if (x
->preserve_timestamps
)
2456 struct timespec timespec
[2];
2457 timespec
[0] = get_stat_atime (&src_sb
);
2458 timespec
[1] = get_stat_mtime (&src_sb
);
2460 if ((dest_is_symlink
2461 ? utimens_symlink (dst_name
, timespec
)
2462 : utimens (dst_name
, timespec
))
2465 error (0, errno
, _("preserving times for %s"), quote (dst_name
));
2466 if (x
->require_preserve
)
2471 /* The operations beyond this point may dereference a symlink. */
2472 if (dest_is_symlink
)
2475 /* Avoid calling chown if we know it's not necessary. */
2476 if (x
->preserve_ownership
2477 && (new_dst
|| !SAME_OWNER_AND_GROUP (src_sb
, dst_sb
)))
2479 switch (set_owner (x
, dst_name
, -1, &src_sb
, new_dst
, &dst_sb
))
2485 src_mode
&= ~ (S_ISUID
| S_ISGID
| S_ISVTX
);
2490 set_author (dst_name
, -1, &src_sb
);
2492 if (x
->preserve_xattr
&& ! copy_attr (src_name
, -1, dst_name
, -1, x
)
2493 && x
->require_preserve_xattr
)
2496 if (x
->preserve_mode
|| x
->move_mode
)
2498 if (copy_acl (src_name
, -1, dst_name
, -1, src_mode
) != 0
2499 && x
->require_preserve
)
2502 else if (x
->set_mode
)
2504 if (set_acl (dst_name
, -1, x
->mode
) != 0)
2509 if (omitted_permissions
)
2511 omitted_permissions
&= ~ cached_umask ();
2513 if (omitted_permissions
&& !restore_dst_mode
)
2515 /* Permissions were deliberately omitted when the file
2516 was created due to security concerns. See whether
2517 they need to be re-added now. It'd be faster to omit
2518 the lstat, but deducing the current destination mode
2519 is tricky in the presence of implementation-defined
2520 rules for special mode bits. */
2521 if (new_dst
&& lstat (dst_name
, &dst_sb
) != 0)
2523 error (0, errno
, _("cannot stat %s"), quote (dst_name
));
2526 dst_mode
= dst_sb
.st_mode
;
2527 if (omitted_permissions
& ~dst_mode
)
2528 restore_dst_mode
= true;
2532 if (restore_dst_mode
)
2534 if (lchmod (dst_name
, dst_mode
| omitted_permissions
) != 0)
2536 error (0, errno
, _("preserving permissions for %s"),
2538 if (x
->require_preserve
)
2548 if (x
->preserve_security_context
)
2549 restore_default_fscreatecon_or_die ();
2551 /* We have failed to create the destination file.
2552 If we've just added a dev/ino entry via the remember_copied
2553 call above (i.e., unless we've just failed to create a hard link),
2554 remove the entry associating the source dev/ino with the
2555 destination file name, so we don't try to `preserve' a link
2556 to a file we didn't create. */
2557 if (earlier_file
== NULL
)
2558 forget_created (src_sb
.st_ino
, src_sb
.st_dev
);
2562 if (rename (dst_backup
, dst_name
) != 0)
2563 error (0, errno
, _("cannot un-backup %s"), quote (dst_name
));
2567 printf (_("%s -> %s (unbackup)\n"),
2568 quote_n (0, dst_backup
), quote_n (1, dst_name
));
2574 static bool _GL_ATTRIBUTE_PURE
2575 valid_options (const struct cp_options
*co
)
2577 assert (co
!= NULL
);
2578 assert (VALID_BACKUP_TYPE (co
->backup_type
));
2579 assert (VALID_SPARSE_MODE (co
->sparse_mode
));
2580 assert (VALID_REFLINK_MODE (co
->reflink_mode
));
2581 assert (!(co
->hard_link
&& co
->symbolic_link
));
2583 (co
->reflink_mode
== REFLINK_ALWAYS
2584 && co
->sparse_mode
!= SPARSE_AUTO
));
2588 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
2589 any type. NONEXISTENT_DST should be true if the file DST_NAME
2590 is known not to exist (e.g., because its parent directory was just
2591 created); NONEXISTENT_DST should be false if DST_NAME might already
2592 exist. OPTIONS is ... FIXME-describe
2593 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
2594 same as) DST_NAME; otherwise, set clear it.
2595 Return true if successful. */
2598 copy (char const *src_name
, char const *dst_name
,
2599 bool nonexistent_dst
, const struct cp_options
*options
,
2600 bool *copy_into_self
, bool *rename_succeeded
)
2602 assert (valid_options (options
));
2604 /* Record the file names: they're used in case of error, when copying
2605 a directory into itself. I don't like to make these tools do *any*
2606 extra work in the common case when that work is solely to handle
2607 exceptional cases, but in this case, I don't see a way to derive the
2608 top level source and destination directory names where they're used.
2609 An alternative is to use COPY_INTO_SELF and print the diagnostic
2610 from every caller -- but I don't want to do that. */
2611 top_level_src_name
= src_name
;
2612 top_level_dst_name
= dst_name
;
2614 bool first_dir_created_per_command_line_arg
= false;
2615 return copy_internal (src_name
, dst_name
, nonexistent_dst
, 0, NULL
,
2617 &first_dir_created_per_command_line_arg
,
2618 copy_into_self
, rename_succeeded
);
2621 /* Set *X to the default options for a value of type struct cp_options. */
2624 cp_options_default (struct cp_options
*x
)
2626 memset (x
, 0, sizeof *x
);
2627 #ifdef PRIV_FILE_CHOWN
2629 priv_set_t
*pset
= priv_allocset ();
2632 if (getppriv (PRIV_EFFECTIVE
, pset
) == 0)
2634 x
->chown_privileges
= priv_ismember (pset
, PRIV_FILE_CHOWN
);
2635 x
->owner_privileges
= priv_ismember (pset
, PRIV_FILE_OWNER
);
2637 priv_freeset (pset
);
2640 x
->chown_privileges
= x
->owner_privileges
= (geteuid () == 0);
2644 /* Return true if it's OK for chown to fail, where errno is
2645 the error number that chown failed with and X is the copying
2649 chown_failure_ok (struct cp_options
const *x
)
2651 /* If non-root uses -p, it's ok if we can't preserve ownership.
2652 But root probably wants to know, e.g. if NFS disallows it,
2653 or if the target system doesn't support file ownership. */
2655 return ((errno
== EPERM
|| errno
== EINVAL
) && !x
->chown_privileges
);
2658 /* Similarly, return true if it's OK for chmod and similar operations
2659 to fail, where errno is the error number that chmod failed with and
2660 X is the copying option set. */
2663 owner_failure_ok (struct cp_options
const *x
)
2665 return ((errno
== EPERM
|| errno
== EINVAL
) && !x
->owner_privileges
);
2668 /* Return the user's umask, caching the result. */
2673 static mode_t mask
= (mode_t
) -1;
2674 if (mask
== (mode_t
) -1)