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