cp -pP (and e.g., -a): preserve time stamps on symlinks, too
[coreutils.git] / src / copy.c
blob24b5f6b46cc0edd88dacf1cde7c8eb1f14e5a320
1 /* copy.c -- core functions for copying files and directories
2 Copyright (C) 89, 90, 91, 1995-2009 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/types.h>
23 #include <selinux/selinux.h>
25 #if HAVE_HURD_H
26 # include <hurd.h>
27 #endif
28 #if HAVE_PRIV_H
29 # include <priv.h>
30 #endif
32 #include "system.h"
33 #include "acl.h"
34 #include "backupfile.h"
35 #include "buffer-lcm.h"
36 #include "copy.h"
37 #include "cp-hash.h"
38 #include "error.h"
39 #include "fcntl--.h"
40 #include "file-set.h"
41 #include "filemode.h"
42 #include "filenamecat.h"
43 #include "full-write.h"
44 #include "hash.h"
45 #include "hash-triple.h"
46 #include "ignore-value.h"
47 #include "quote.h"
48 #include "same.h"
49 #include "savedir.h"
50 #include "stat-time.h"
51 #include "utimecmp.h"
52 #include "utimens.h"
53 #include "write-any-file.h"
54 #include "areadlink.h"
55 #include "yesno.h"
57 #if USE_XATTR
58 # include <attr/error_context.h>
59 # include <attr/libattr.h>
60 # include <stdarg.h>
61 # include "verror.h"
62 #endif
64 #if HAVE_SYS_IOCTL_H
65 # include <sys/ioctl.h>
66 #endif
68 #ifndef HAVE_FCHOWN
69 # define HAVE_FCHOWN false
70 # define fchown(fd, uid, gid) (-1)
71 #endif
73 #ifndef HAVE_LCHOWN
74 # define HAVE_LCHOWN false
75 # define lchown(name, uid, gid) chown (name, uid, gid)
76 #endif
78 #ifndef HAVE_MKFIFO
79 static int
80 rpl_mkfifo (char const *file, mode_t mode)
82 errno = ENOTSUP;
83 return -1;
85 # define mkfifo rpl_mkfifo
86 #endif
88 #ifndef USE_ACL
89 # define USE_ACL 0
90 #endif
92 #define SAME_OWNER(A, B) ((A).st_uid == (B).st_uid)
93 #define SAME_GROUP(A, B) ((A).st_gid == (B).st_gid)
94 #define SAME_OWNER_AND_GROUP(A, B) (SAME_OWNER (A, B) && SAME_GROUP (A, B))
96 struct dir_list
98 struct dir_list *parent;
99 ino_t ino;
100 dev_t dev;
103 /* Initial size of the cp.dest_info hash table. */
104 #define DEST_INFO_INITIAL_CAPACITY 61
106 static bool copy_internal (char const *src_name, char const *dst_name,
107 bool new_dst, dev_t device,
108 struct dir_list *ancestors,
109 const struct cp_options *x,
110 bool command_line_arg,
111 bool *first_dir_created_per_command_line_arg,
112 bool *copy_into_self,
113 bool *rename_succeeded);
114 static bool owner_failure_ok (struct cp_options const *x);
116 /* Pointers to the file names: they're used in the diagnostic that is issued
117 when we detect the user is trying to copy a directory into itself. */
118 static char const *top_level_src_name;
119 static char const *top_level_dst_name;
121 /* Wrap utimensat-with-AT_FDCWD and utimens, to keep these
122 cpp directives out of the main code. */
123 static inline int
124 utimensat_if_possible (char const *file, struct timespec const *timespec)
126 return
127 #if HAVE_UTIMENSAT
128 utimensat (AT_FDCWD, file, timespec, AT_SYMLINK_NOFOLLOW)
129 #else
130 utimens (file, timespec)
131 #endif
135 /* Perform the O(1) btrfs clone operation, if possible.
136 Upon success, return 0. Otherwise, return -1 and set errno. */
137 static inline int
138 clone_file (int dest_fd, int src_fd)
140 #ifdef __linux__
141 # undef BTRFS_IOCTL_MAGIC
142 # define BTRFS_IOCTL_MAGIC 0x94
143 # undef BTRFS_IOC_CLONE
144 # define BTRFS_IOC_CLONE _IOW (BTRFS_IOCTL_MAGIC, 9, int)
145 return ioctl (dest_fd, BTRFS_IOC_CLONE, src_fd);
146 #else
147 errno = ENOTSUP;
148 return -1;
149 #endif
152 /* FIXME: describe */
153 /* FIXME: rewrite this to use a hash table so we avoid the quadratic
154 performance hit that's probably noticeable only on trees deeper
155 than a few hundred levels. See use of active_dir_map in remove.c */
157 static bool
158 is_ancestor (const struct stat *sb, const struct dir_list *ancestors)
160 while (ancestors != 0)
162 if (ancestors->ino == sb->st_ino && ancestors->dev == sb->st_dev)
163 return true;
164 ancestors = ancestors->parent;
166 return false;
169 static bool
170 errno_unsupported (int err)
172 return err == ENOTSUP || err == ENODATA;
175 #if USE_XATTR
176 static void
177 copy_attr_error (struct error_context *ctx ATTRIBUTE_UNUSED,
178 char const *fmt, ...)
180 int err = errno;
181 va_list ap;
183 if (!errno_unsupported (errno))
185 /* use verror module to print error message */
186 va_start (ap, fmt);
187 verror (0, err, fmt, ap);
188 va_end (ap);
192 static void
193 copy_attr_allerror (struct error_context *ctx ATTRIBUTE_UNUSED,
194 char const *fmt, ...)
196 int err = errno;
197 va_list ap;
199 /* use verror module to print error message */
200 va_start (ap, fmt);
201 verror (0, err, fmt, ap);
202 va_end (ap);
205 static char const *
206 copy_attr_quote (struct error_context *ctx ATTRIBUTE_UNUSED, char const *str)
208 return quote (str);
211 static void
212 copy_attr_free (struct error_context *ctx ATTRIBUTE_UNUSED,
213 char const *str ATTRIBUTE_UNUSED)
217 static bool
218 copy_attr_by_fd (char const *src_path, int src_fd,
219 char const *dst_path, int dst_fd, const struct cp_options *x)
221 struct error_context ctx =
223 .error = x->require_preserve_xattr ? copy_attr_allerror : copy_attr_error,
224 .quote = copy_attr_quote,
225 .quote_free = copy_attr_free
227 return 0 == attr_copy_fd (src_path, src_fd, dst_path, dst_fd, 0,
228 (x->reduce_diagnostics
229 && !x->require_preserve_xattr)? NULL : &ctx);
232 static bool
233 copy_attr_by_name (char const *src_path, char const *dst_path,
234 const struct cp_options *x)
236 struct error_context ctx =
238 .error = x->require_preserve_xattr ? copy_attr_allerror : copy_attr_error,
239 .quote = copy_attr_quote,
240 .quote_free = copy_attr_free
242 return 0 == attr_copy_file (src_path, dst_path, 0,
243 (x-> reduce_diagnostics
244 && !x->require_preserve_xattr) ? NULL : &ctx);
246 #else /* USE_XATTR */
248 static bool
249 copy_attr_by_fd (char const *src_path, int src_fd,
250 char const *dst_path, int dst_fd, const struct cp_options *x)
252 return true;
255 static bool
256 copy_attr_by_name (char const *src_path, char const *dst_path,
257 const struct cp_options *x)
259 return true;
261 #endif /* USE_XATTR */
263 /* Read the contents of the directory SRC_NAME_IN, and recursively
264 copy the contents to DST_NAME_IN. NEW_DST is true if
265 DST_NAME_IN is a directory that was created previously in the
266 recursion. SRC_SB and ANCESTORS describe SRC_NAME_IN.
267 Set *COPY_INTO_SELF if SRC_NAME_IN is a parent of
268 FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG FIXME
269 (or the same as) DST_NAME_IN; otherwise, clear it.
270 Return true if successful. */
272 static bool
273 copy_dir (char const *src_name_in, char const *dst_name_in, bool new_dst,
274 const struct stat *src_sb, struct dir_list *ancestors,
275 const struct cp_options *x,
276 bool *first_dir_created_per_command_line_arg,
277 bool *copy_into_self)
279 char *name_space;
280 char *namep;
281 struct cp_options non_command_line_options = *x;
282 bool ok = true;
284 name_space = savedir (src_name_in);
285 if (name_space == NULL)
287 /* This diagnostic is a bit vague because savedir can fail in
288 several different ways. */
289 error (0, errno, _("cannot access %s"), quote (src_name_in));
290 return false;
293 /* For cp's -H option, dereference command line arguments, but do not
294 dereference symlinks that are found via recursive traversal. */
295 if (x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
296 non_command_line_options.dereference = DEREF_NEVER;
298 namep = name_space;
299 while (*namep != '\0')
301 bool local_copy_into_self;
302 char *src_name = file_name_concat (src_name_in, namep, NULL);
303 char *dst_name = file_name_concat (dst_name_in, namep, NULL);
305 ok &= copy_internal (src_name, dst_name, new_dst, src_sb->st_dev,
306 ancestors, &non_command_line_options, false,
307 first_dir_created_per_command_line_arg,
308 &local_copy_into_self, NULL);
309 *copy_into_self |= local_copy_into_self;
311 free (dst_name);
312 free (src_name);
314 /* If we're copying into self, there's no point in continuing,
315 and in fact, that would even infloop, now that we record only
316 the first created directory per command line argument. */
317 if (local_copy_into_self)
318 break;
320 namep += strlen (namep) + 1;
322 free (name_space);
323 return ok;
326 /* Set the owner and owning group of DEST_DESC to the st_uid and
327 st_gid fields of SRC_SB. If DEST_DESC is undefined (-1), set
328 the owner and owning group of DST_NAME instead; for
329 safety prefer lchown if the system supports it since no
330 symbolic links should be involved. DEST_DESC must
331 refer to the same file as DEST_NAME if defined.
332 Upon failure to set both UID and GID, try to set only the GID.
333 NEW_DST is true if the file was newly created; otherwise,
334 DST_SB is the status of the destination.
335 Return 1 if the initial syscall succeeds, 0 if it fails but it's OK
336 not to preserve ownership, -1 otherwise. */
338 static int
339 set_owner (const struct cp_options *x, char const *dst_name, int dest_desc,
340 struct stat const *src_sb, bool new_dst,
341 struct stat const *dst_sb)
343 uid_t uid = src_sb->st_uid;
344 gid_t gid = src_sb->st_gid;
346 /* Naively changing the ownership of an already-existing file before
347 changing its permissions would create a window of vulnerability if
348 the file's old permissions are too generous for the new owner and
349 group. Avoid the window by first changing to a restrictive
350 temporary mode if necessary. */
352 if (!new_dst && (x->preserve_mode | x->move_mode | x->set_mode))
354 mode_t old_mode = dst_sb->st_mode;
355 mode_t new_mode =
356 (x->preserve_mode | x->move_mode ? src_sb->st_mode : x->mode);
357 mode_t restrictive_temp_mode = old_mode & new_mode & S_IRWXU;
359 if ((USE_ACL
360 || (old_mode & CHMOD_MODE_BITS
361 & (~new_mode | S_ISUID | S_ISGID | S_ISVTX)))
362 && qset_acl (dst_name, dest_desc, restrictive_temp_mode) != 0)
364 if (! owner_failure_ok (x))
365 error (0, errno, _("clearing permissions for %s"), quote (dst_name));
366 return -x->require_preserve;
370 if (HAVE_FCHOWN && dest_desc != -1)
372 if (fchown (dest_desc, uid, gid) == 0)
373 return 1;
374 if (errno == EPERM || errno == EINVAL)
376 /* We've failed to set *both*. Now, try to set just the group
377 ID, but ignore any failure here, and don't change errno. */
378 int saved_errno = errno;
379 ignore_value (fchown (dest_desc, -1, gid));
380 errno = saved_errno;
383 else
385 if (lchown (dst_name, uid, gid) == 0)
386 return 1;
387 if (errno == EPERM || errno == EINVAL)
389 /* We've failed to set *both*. Now, try to set just the group
390 ID, but ignore any failure here, and don't change errno. */
391 int saved_errno = errno;
392 ignore_value (lchown (dst_name, -1, gid));
393 errno = saved_errno;
397 if (! chown_failure_ok (x))
399 error (0, errno, _("failed to preserve ownership for %s"),
400 quote (dst_name));
401 if (x->require_preserve)
402 return -1;
405 return 0;
408 /* Set the st_author field of DEST_DESC to the st_author field of
409 SRC_SB. If DEST_DESC is undefined (-1), set the st_author field
410 of DST_NAME instead. DEST_DESC must refer to the same file as
411 DEST_NAME if defined. */
413 static void
414 set_author (const char *dst_name, int dest_desc, const struct stat *src_sb)
416 #if HAVE_STRUCT_STAT_ST_AUTHOR
417 /* FIXME: Modify the following code so that it does not
418 follow symbolic links. */
420 /* Preserve the st_author field. */
421 file_t file = (dest_desc < 0
422 ? file_name_lookup (dst_name, 0, 0)
423 : getdport (dest_desc));
424 if (file == MACH_PORT_NULL)
425 error (0, errno, _("failed to lookup file %s"), quote (dst_name));
426 else
428 error_t err = file_chauthor (file, src_sb->st_author);
429 if (err)
430 error (0, err, _("failed to preserve authorship for %s"),
431 quote (dst_name));
432 mach_port_deallocate (mach_task_self (), file);
434 #else
435 (void) dst_name;
436 (void) dest_desc;
437 (void) src_sb;
438 #endif
441 /* Change the file mode bits of the file identified by DESC or NAME to MODE.
442 Use DESC if DESC is valid and fchmod is available, NAME otherwise. */
444 static int
445 fchmod_or_lchmod (int desc, char const *name, mode_t mode)
447 #if HAVE_FCHMOD
448 if (0 <= desc)
449 return fchmod (desc, mode);
450 #endif
451 return lchmod (name, mode);
454 /* Copy a regular file from SRC_NAME to DST_NAME.
455 If the source file contains holes, copies holes and blocks of zeros
456 in the source file as holes in the destination file.
457 (Holes are read as zeroes by the `read' system call.)
458 When creating the destination, use DST_MODE & ~OMITTED_PERMISSIONS
459 as the third argument in the call to open, adding
460 OMITTED_PERMISSIONS after copying as needed.
461 X provides many option settings.
462 Return true if successful.
463 *NEW_DST is as in copy_internal.
464 SRC_SB is the result of calling XSTAT (aka stat) on SRC_NAME. */
466 static bool
467 copy_reg (char const *src_name, char const *dst_name,
468 const struct cp_options *x,
469 mode_t dst_mode, mode_t omitted_permissions, bool *new_dst,
470 struct stat const *src_sb)
472 char *buf;
473 char *buf_alloc = NULL;
474 char *name_alloc = NULL;
475 int dest_desc;
476 int dest_errno;
477 int source_desc;
478 mode_t src_mode = src_sb->st_mode;
479 struct stat sb;
480 struct stat src_open_sb;
481 bool return_val = true;
483 source_desc = open (src_name,
484 (O_RDONLY | O_BINARY
485 | (x->dereference == DEREF_NEVER ? O_NOFOLLOW : 0)));
486 if (source_desc < 0)
488 error (0, errno, _("cannot open %s for reading"), quote (src_name));
489 return false;
492 if (fstat (source_desc, &src_open_sb) != 0)
494 error (0, errno, _("cannot fstat %s"), quote (src_name));
495 return_val = false;
496 goto close_src_desc;
499 /* Compare the source dev/ino from the open file to the incoming,
500 saved ones obtained via a previous call to stat. */
501 if (! SAME_INODE (*src_sb, src_open_sb))
503 error (0, 0,
504 _("skipping file %s, as it was replaced while being copied"),
505 quote (src_name));
506 return_val = false;
507 goto close_src_desc;
510 /* The semantics of the following open calls are mandated
511 by the specs for both cp and mv. */
512 if (! *new_dst)
514 dest_desc = open (dst_name, O_WRONLY | O_TRUNC | O_BINARY);
515 dest_errno = errno;
517 /* When using cp --preserve=context to copy to an existing destination,
518 use the default context rather than that of the source. Why?
519 1) the src context may prohibit writing, and
520 2) because it's more consistent to use the same context
521 that is used when the destination file doesn't already exist. */
522 if (x->preserve_security_context && 0 <= dest_desc)
524 security_context_t con = NULL;
525 if (getfscreatecon (&con) < 0)
527 if (!x->reduce_diagnostics || x->require_preserve_context)
528 error (0, errno, _("failed to get file system create context"));
529 if (x->require_preserve_context)
531 return_val = false;
532 goto close_src_and_dst_desc;
536 if (con)
538 if (fsetfilecon (dest_desc, con) < 0)
540 if (!x->reduce_diagnostics || x->require_preserve_context)
541 error (0, errno,
542 _("failed to set the security context of %s to %s"),
543 quote_n (0, dst_name), quote_n (1, con));
544 if (x->require_preserve_context)
546 return_val = false;
547 freecon (con);
548 goto close_src_and_dst_desc;
551 freecon (con);
555 if (dest_desc < 0 && x->unlink_dest_after_failed_open)
557 if (unlink (dst_name) != 0)
559 error (0, errno, _("cannot remove %s"), quote (dst_name));
560 return_val = false;
561 goto close_src_desc;
563 if (x->verbose)
564 printf (_("removed %s\n"), quote (dst_name));
566 /* Tell caller that the destination file was unlinked. */
567 *new_dst = true;
571 if (*new_dst)
573 int open_flags = O_WRONLY | O_CREAT | O_BINARY;
574 dest_desc = open (dst_name, open_flags | O_EXCL,
575 dst_mode & ~omitted_permissions);
576 dest_errno = errno;
578 /* When trying to copy through a dangling destination symlink,
579 the above open fails with EEXIST. If that happens, and
580 lstat'ing the DST_NAME shows that it is a symlink, then we
581 have a problem: trying to resolve this dangling symlink to
582 a directory/destination-entry pair is fundamentally racy,
583 so punt. If POSIXLY_CORRECT is set, simply call open again,
584 but without O_EXCL (potentially dangerous). If not, fail
585 with a diagnostic. These shenanigans are necessary only
586 when copying, i.e., not in move_mode. */
587 if (dest_desc < 0 && dest_errno == EEXIST && ! x->move_mode)
589 struct stat dangling_link_sb;
590 if (lstat (dst_name, &dangling_link_sb) == 0
591 && S_ISLNK (dangling_link_sb.st_mode))
593 if (x->open_dangling_dest_symlink)
595 dest_desc = open (dst_name, open_flags,
596 dst_mode & ~omitted_permissions);
597 dest_errno = errno;
599 else
601 error (0, 0, _("not writing through dangling symlink %s"),
602 quote (dst_name));
603 return_val = false;
604 goto close_src_desc;
609 else
610 omitted_permissions = 0;
612 if (dest_desc < 0)
614 error (0, dest_errno, _("cannot create regular file %s"),
615 quote (dst_name));
616 return_val = false;
617 goto close_src_desc;
620 if (fstat (dest_desc, &sb) != 0)
622 error (0, errno, _("cannot fstat %s"), quote (dst_name));
623 return_val = false;
624 goto close_src_and_dst_desc;
627 /* If --sparse=auto is in effect, attempt a btrfs clone operation.
628 If the operation is not supported or it fails then copy the file
629 in the usual way. */
630 bool copied = (x->sparse_mode == SPARSE_AUTO
631 && clone_file (dest_desc, source_desc) == 0);
633 if (!copied)
635 typedef uintptr_t word;
636 off_t n_read_total = 0;
638 /* Choose a suitable buffer size; it may be adjusted later. */
639 size_t buf_alignment = lcm (getpagesize (), sizeof (word));
640 size_t buf_alignment_slop = sizeof (word) + buf_alignment - 1;
641 size_t buf_size = io_blksize (sb);
643 /* Deal with sparse files. */
644 bool last_write_made_hole = false;
645 bool make_holes = false;
647 if (S_ISREG (sb.st_mode))
649 /* Even with --sparse=always, try to create holes only
650 if the destination is a regular file. */
651 if (x->sparse_mode == SPARSE_ALWAYS)
652 make_holes = true;
654 #if HAVE_STRUCT_STAT_ST_BLOCKS
655 /* Use a heuristic to determine whether SRC_NAME contains any sparse
656 blocks. If the file has fewer blocks than would normally be
657 needed for a file of its size, then at least one of the blocks in
658 the file is a hole. */
659 if (x->sparse_mode == SPARSE_AUTO && S_ISREG (src_open_sb.st_mode)
660 && ST_NBLOCKS (src_open_sb) < src_open_sb.st_size / ST_NBLOCKSIZE)
661 make_holes = true;
662 #endif
665 /* If not making a sparse file, try to use a more-efficient
666 buffer size. */
667 if (! make_holes)
669 /* Compute the least common multiple of the input and output
670 buffer sizes, adjusting for outlandish values. */
671 size_t blcm_max = MIN (SIZE_MAX, SSIZE_MAX) - buf_alignment_slop;
672 size_t blcm = buffer_lcm (io_blksize (src_open_sb), buf_size,
673 blcm_max);
675 /* Do not bother with a buffer larger than the input file, plus one
676 byte to make sure the file has not grown while reading it. */
677 if (S_ISREG (src_open_sb.st_mode) && src_open_sb.st_size < buf_size)
678 buf_size = src_open_sb.st_size + 1;
680 /* However, stick with a block size that is a positive multiple of
681 blcm, overriding the above adjustments. Watch out for
682 overflow. */
683 buf_size += blcm - 1;
684 buf_size -= buf_size % blcm;
685 if (buf_size == 0 || blcm_max < buf_size)
686 buf_size = blcm;
689 /* Make a buffer with space for a sentinel at the end. */
690 buf_alloc = xmalloc (buf_size + buf_alignment_slop);
691 buf = ptr_align (buf_alloc, buf_alignment);
693 for (;;)
695 word *wp = NULL;
697 ssize_t n_read = read (source_desc, buf, buf_size);
698 if (n_read < 0)
700 #ifdef EINTR
701 if (errno == EINTR)
702 continue;
703 #endif
704 error (0, errno, _("reading %s"), quote (src_name));
705 return_val = false;
706 goto close_src_and_dst_desc;
708 if (n_read == 0)
709 break;
711 n_read_total += n_read;
713 if (make_holes)
715 char *cp;
717 /* Sentinel to stop loop. */
718 buf[n_read] = '\1';
719 #ifdef lint
720 /* Usually, buf[n_read] is not the byte just before a "word"
721 (aka uintptr_t) boundary. In that case, the word-oriented
722 test below (*wp++ == 0) would read some uninitialized bytes
723 after the sentinel. To avoid false-positive reports about
724 this condition (e.g., from a tool like valgrind), set the
725 remaining bytes -- to any value. */
726 memset (buf + n_read + 1, 0, sizeof (word) - 1);
727 #endif
729 /* Find first nonzero *word*, or the word with the sentinel. */
731 wp = (word *) buf;
732 while (*wp++ == 0)
733 continue;
735 /* Find the first nonzero *byte*, or the sentinel. */
737 cp = (char *) (wp - 1);
738 while (*cp++ == 0)
739 continue;
741 if (cp <= buf + n_read)
742 /* Clear to indicate that a normal write is needed. */
743 wp = NULL;
744 else
746 /* We found the sentinel, so the whole input block was zero.
747 Make a hole. */
748 if (lseek (dest_desc, n_read, SEEK_CUR) < 0)
750 error (0, errno, _("cannot lseek %s"), quote (dst_name));
751 return_val = false;
752 goto close_src_and_dst_desc;
754 last_write_made_hole = true;
758 if (!wp)
760 size_t n = n_read;
761 if (full_write (dest_desc, buf, n) != n)
763 error (0, errno, _("writing %s"), quote (dst_name));
764 return_val = false;
765 goto close_src_and_dst_desc;
767 last_write_made_hole = false;
769 /* It is tempting to return early here upon a short read from a
770 regular file. That would save the final read syscall for each
771 file. Unfortunately that doesn't work for certain files in
772 /proc with linux kernels from at least 2.6.9 .. 2.6.29. */
776 /* If the file ends with a `hole', we need to do something to record
777 the length of the file. On modern systems, calling ftruncate does
778 the job. On systems without native ftruncate support, we have to
779 write a byte at the ending position. Otherwise the kernel would
780 truncate the file at the end of the last write operation. */
782 if (last_write_made_hole)
784 if (HAVE_FTRUNCATE
785 ? /* ftruncate sets the file size,
786 so there is no need for a write. */
787 ftruncate (dest_desc, n_read_total) < 0
788 : /* Seek backwards one character and write a null. */
789 (lseek (dest_desc, (off_t) -1, SEEK_CUR) < 0L
790 || full_write (dest_desc, "", 1) != 1))
792 error (0, errno, _("writing %s"), quote (dst_name));
793 return_val = false;
794 goto close_src_and_dst_desc;
799 if (x->preserve_timestamps)
801 struct timespec timespec[2];
802 timespec[0] = get_stat_atime (src_sb);
803 timespec[1] = get_stat_mtime (src_sb);
805 if (gl_futimens (dest_desc, dst_name, timespec) != 0)
807 error (0, errno, _("preserving times for %s"), quote (dst_name));
808 if (x->require_preserve)
810 return_val = false;
811 goto close_src_and_dst_desc;
816 if (x->preserve_ownership && ! SAME_OWNER_AND_GROUP (*src_sb, sb))
818 switch (set_owner (x, dst_name, dest_desc, src_sb, *new_dst, &sb))
820 case -1:
821 return_val = false;
822 goto close_src_and_dst_desc;
824 case 0:
825 src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX);
826 break;
830 set_author (dst_name, dest_desc, src_sb);
832 if (x->preserve_xattr && ! copy_attr_by_fd (src_name, source_desc,
833 dst_name, dest_desc, x)
834 && x->require_preserve_xattr)
835 return false;
837 if (x->preserve_mode || x->move_mode)
839 if (copy_acl (src_name, source_desc, dst_name, dest_desc, src_mode) != 0
840 && x->require_preserve)
841 return_val = false;
843 else if (x->set_mode)
845 if (set_acl (dst_name, dest_desc, x->mode) != 0)
846 return_val = false;
848 else if (omitted_permissions)
850 omitted_permissions &= ~ cached_umask ();
851 if (omitted_permissions
852 && fchmod_or_lchmod (dest_desc, dst_name, dst_mode) != 0)
854 error (0, errno, _("preserving permissions for %s"),
855 quote (dst_name));
856 if (x->require_preserve)
857 return_val = false;
861 close_src_and_dst_desc:
862 if (close (dest_desc) < 0)
864 error (0, errno, _("closing %s"), quote (dst_name));
865 return_val = false;
867 close_src_desc:
868 if (close (source_desc) < 0)
870 error (0, errno, _("closing %s"), quote (src_name));
871 return_val = false;
874 free (buf_alloc);
875 free (name_alloc);
876 return return_val;
879 /* Return true if it's ok that the source and destination
880 files are the `same' by some measure. The goal is to avoid
881 making the `copy' operation remove both copies of the file
882 in that case, while still allowing the user to e.g., move or
883 copy a regular file onto a symlink that points to it.
884 Try to minimize the cost of this function in the common case.
885 Set *RETURN_NOW if we've determined that the caller has no more
886 work to do and should return successfully, right away.
888 Set *UNLINK_SRC if we've determined that the caller wants to do
889 `rename (a, b)' where `a' and `b' are distinct hard links to the same
890 file. In that case, the caller should try to unlink `a' and then return
891 successfully. Ideally, we wouldn't have to do that, and we'd be
892 able to rely on rename to remove the source file. However, POSIX
893 mistakenly requires that such a rename call do *nothing* and return
894 successfully. */
896 static bool
897 same_file_ok (char const *src_name, struct stat const *src_sb,
898 char const *dst_name, struct stat const *dst_sb,
899 const struct cp_options *x, bool *return_now, bool *unlink_src)
901 const struct stat *src_sb_link;
902 const struct stat *dst_sb_link;
903 struct stat tmp_dst_sb;
904 struct stat tmp_src_sb;
906 bool same_link;
907 bool same = SAME_INODE (*src_sb, *dst_sb);
909 *return_now = false;
910 *unlink_src = false;
912 /* FIXME: this should (at the very least) be moved into the following
913 if-block. More likely, it should be removed, because it inhibits
914 making backups. But removing it will result in a change in behavior
915 that will probably have to be documented -- and tests will have to
916 be updated. */
917 if (same && x->hard_link)
919 *return_now = true;
920 return true;
923 if (x->dereference == DEREF_NEVER)
925 same_link = same;
927 /* If both the source and destination files are symlinks (and we'll
928 know this here IFF preserving symlinks), then it's ok -- as long
929 as they are distinct. */
930 if (S_ISLNK (src_sb->st_mode) && S_ISLNK (dst_sb->st_mode))
931 return ! same_name (src_name, dst_name);
933 src_sb_link = src_sb;
934 dst_sb_link = dst_sb;
936 else
938 if (!same)
939 return true;
941 if (lstat (dst_name, &tmp_dst_sb) != 0
942 || lstat (src_name, &tmp_src_sb) != 0)
943 return true;
945 src_sb_link = &tmp_src_sb;
946 dst_sb_link = &tmp_dst_sb;
948 same_link = SAME_INODE (*src_sb_link, *dst_sb_link);
950 /* If both are symlinks, then it's ok, but only if the destination
951 will be unlinked before being opened. This is like the test
952 above, but with the addition of the unlink_dest_before_opening
953 conjunct because otherwise, with two symlinks to the same target,
954 we'd end up truncating the source file. */
955 if (S_ISLNK (src_sb_link->st_mode) && S_ISLNK (dst_sb_link->st_mode)
956 && x->unlink_dest_before_opening)
957 return true;
960 /* The backup code ensures there's a copy, so it's usually ok to
961 remove any destination file. One exception is when both
962 source and destination are the same directory entry. In that
963 case, moving the destination file aside (in making the backup)
964 would also rename the source file and result in an error. */
965 if (x->backup_type != no_backups)
967 if (!same_link)
969 /* In copy mode when dereferencing symlinks, if the source is a
970 symlink and the dest is not, then backing up the destination
971 (moving it aside) would make it a dangling symlink, and the
972 subsequent attempt to open it in copy_reg would fail with
973 a misleading diagnostic. Avoid that by returning zero in
974 that case so the caller can make cp (or mv when it has to
975 resort to reading the source file) fail now. */
977 /* FIXME-note: even with the following kludge, we can still provoke
978 the offending diagnostic. It's just a little harder to do :-)
979 $ rm -f a b c; touch c; ln -s c b; ln -s b a; cp -b a b
980 cp: cannot open `a' for reading: No such file or directory
981 That's misleading, since a subsequent `ls' shows that `a'
982 is still there.
983 One solution would be to open the source file *before* moving
984 aside the destination, but that'd involve a big rewrite. */
985 if ( ! x->move_mode
986 && x->dereference != DEREF_NEVER
987 && S_ISLNK (src_sb_link->st_mode)
988 && ! S_ISLNK (dst_sb_link->st_mode))
989 return false;
991 return true;
994 return ! same_name (src_name, dst_name);
997 #if 0
998 /* FIXME: use or remove */
1000 /* If we're making a backup, we'll detect the problem case in
1001 copy_reg because SRC_NAME will no longer exist. Allowing
1002 the test to be deferred lets cp do some useful things.
1003 But when creating hardlinks and SRC_NAME is a symlink
1004 but DST_NAME is not we must test anyway. */
1005 if (x->hard_link
1006 || !S_ISLNK (src_sb_link->st_mode)
1007 || S_ISLNK (dst_sb_link->st_mode))
1008 return true;
1010 if (x->dereference != DEREF_NEVER)
1011 return true;
1012 #endif
1014 /* They may refer to the same file if we're in move mode and the
1015 target is a symlink. That is ok, since we remove any existing
1016 destination file before opening it -- via `rename' if they're on
1017 the same file system, via `unlink (DST_NAME)' otherwise.
1018 It's also ok if they're distinct hard links to the same file. */
1019 if (x->move_mode || x->unlink_dest_before_opening)
1021 if (S_ISLNK (dst_sb_link->st_mode))
1022 return true;
1024 if (same_link
1025 && 1 < dst_sb_link->st_nlink
1026 && ! same_name (src_name, dst_name))
1028 if (x->move_mode)
1030 *unlink_src = true;
1031 *return_now = true;
1033 return true;
1037 /* If neither is a symlink, then it's ok as long as they aren't
1038 hard links to the same file. */
1039 if (!S_ISLNK (src_sb_link->st_mode) && !S_ISLNK (dst_sb_link->st_mode))
1041 if (!SAME_INODE (*src_sb_link, *dst_sb_link))
1042 return true;
1044 /* If they are the same file, it's ok if we're making hard links. */
1045 if (x->hard_link)
1047 *return_now = true;
1048 return true;
1052 /* It's ok to remove a destination symlink. But that works only when we
1053 unlink before opening the destination and when the source and destination
1054 files are on the same partition. */
1055 if (x->unlink_dest_before_opening
1056 && S_ISLNK (dst_sb_link->st_mode))
1057 return dst_sb_link->st_dev == src_sb_link->st_dev;
1059 if (x->dereference == DEREF_NEVER)
1061 if ( ! S_ISLNK (src_sb_link->st_mode))
1062 tmp_src_sb = *src_sb_link;
1063 else if (stat (src_name, &tmp_src_sb) != 0)
1064 return true;
1066 if ( ! S_ISLNK (dst_sb_link->st_mode))
1067 tmp_dst_sb = *dst_sb_link;
1068 else if (stat (dst_name, &tmp_dst_sb) != 0)
1069 return true;
1071 if ( ! SAME_INODE (tmp_src_sb, tmp_dst_sb))
1072 return true;
1074 /* FIXME: shouldn't this be testing whether we're making symlinks? */
1075 if (x->hard_link)
1077 *return_now = true;
1078 return true;
1082 return false;
1085 /* Return true if FILE, with mode MODE, is writable in the sense of 'mv'.
1086 Always consider a symbolic link to be writable. */
1087 static bool
1088 writable_destination (char const *file, mode_t mode)
1090 return (S_ISLNK (mode)
1091 || can_write_any_file ()
1092 || euidaccess (file, W_OK) == 0);
1095 static void
1096 overwrite_prompt (char const *dst_name, struct stat const *dst_sb)
1098 if (! writable_destination (dst_name, dst_sb->st_mode))
1100 char perms[12]; /* "-rwxrwxrwx " ls-style modes. */
1101 strmode (dst_sb->st_mode, perms);
1102 perms[10] = '\0';
1103 fprintf (stderr,
1104 _("%s: try to overwrite %s, overriding mode %04lo (%s)? "),
1105 program_name, quote (dst_name),
1106 (unsigned long int) (dst_sb->st_mode & CHMOD_MODE_BITS),
1107 &perms[1]);
1109 else
1111 fprintf (stderr, _("%s: overwrite %s? "),
1112 program_name, quote (dst_name));
1116 /* Initialize the hash table implementing a set of F_triple entries
1117 corresponding to destination files. */
1118 extern void
1119 dest_info_init (struct cp_options *x)
1121 x->dest_info
1122 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
1123 NULL,
1124 triple_hash,
1125 triple_compare,
1126 triple_free);
1129 /* Initialize the hash table implementing a set of F_triple entries
1130 corresponding to source files listed on the command line. */
1131 extern void
1132 src_info_init (struct cp_options *x)
1135 /* Note that we use triple_hash_no_name here.
1136 Contrast with the use of triple_hash above.
1137 That is necessary because a source file may be specified
1138 in many different ways. We want to warn about this
1139 cp a a d/
1140 as well as this:
1141 cp a ./a d/
1143 x->src_info
1144 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
1145 NULL,
1146 triple_hash_no_name,
1147 triple_compare,
1148 triple_free);
1151 /* When effecting a move (e.g., for mv(1)), and given the name DST_NAME
1152 of the destination and a corresponding stat buffer, DST_SB, return
1153 true if the logical `move' operation should _not_ proceed.
1154 Otherwise, return false.
1155 Depending on options specified in X, this code may issue an
1156 interactive prompt asking whether it's ok to overwrite DST_NAME. */
1157 static bool
1158 abandon_move (const struct cp_options *x,
1159 char const *dst_name,
1160 struct stat const *dst_sb)
1162 assert (x->move_mode);
1163 return (x->interactive == I_ALWAYS_NO
1164 || ((x->interactive == I_ASK_USER
1165 || (x->interactive == I_UNSPECIFIED
1166 && x->stdin_tty
1167 && ! writable_destination (dst_name, dst_sb->st_mode)))
1168 && (overwrite_prompt (dst_name, dst_sb), 1)
1169 && ! yesno ()));
1172 /* Print --verbose output on standard output, e.g. `new' -> `old'.
1173 If BACKUP_DST_NAME is non-NULL, then also indicate that it is
1174 the name of a backup file. */
1175 static void
1176 emit_verbose (char const *src, char const *dst, char const *backup_dst_name)
1178 printf ("%s -> %s", quote_n (0, src), quote_n (1, dst));
1179 if (backup_dst_name)
1180 printf (_(" (backup: %s)"), quote (backup_dst_name));
1181 putchar ('\n');
1184 /* A wrapper around "setfscreatecon (NULL)" that exits upon failure. */
1185 static void
1186 restore_default_fscreatecon_or_die (void)
1188 if (setfscreatecon (NULL) != 0)
1189 error (EXIT_FAILURE, errno,
1190 _("failed to restore the default file creation context"));
1193 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
1194 any type. NEW_DST should be true if the file DST_NAME cannot
1195 exist because its parent directory was just created; NEW_DST should
1196 be false if DST_NAME might already exist. DEVICE is the device
1197 number of the parent directory, or 0 if the parent of this file is
1198 not known. ANCESTORS points to a linked, null terminated list of
1199 devices and inodes of parent directories of SRC_NAME. COMMAND_LINE_ARG
1200 is true iff SRC_NAME was specified on the command line.
1201 FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG is both input and output.
1202 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
1203 same as) DST_NAME; otherwise, clear it.
1204 Return true if successful. */
1205 static bool
1206 copy_internal (char const *src_name, char const *dst_name,
1207 bool new_dst,
1208 dev_t device,
1209 struct dir_list *ancestors,
1210 const struct cp_options *x,
1211 bool command_line_arg,
1212 bool *first_dir_created_per_command_line_arg,
1213 bool *copy_into_self,
1214 bool *rename_succeeded)
1216 struct stat src_sb;
1217 struct stat dst_sb;
1218 mode_t src_mode;
1219 mode_t dst_mode IF_LINT (= 0);
1220 mode_t dst_mode_bits;
1221 mode_t omitted_permissions;
1222 bool restore_dst_mode = false;
1223 char *earlier_file = NULL;
1224 char *dst_backup = NULL;
1225 bool backup_succeeded = false;
1226 bool delayed_ok;
1227 bool copied_as_regular = false;
1228 bool dest_is_symlink = false;
1229 bool have_dst_lstat = false;
1231 if (x->move_mode && rename_succeeded)
1232 *rename_succeeded = false;
1234 *copy_into_self = false;
1236 if (XSTAT (x, src_name, &src_sb) != 0)
1238 error (0, errno, _("cannot stat %s"), quote (src_name));
1239 return false;
1242 src_mode = src_sb.st_mode;
1244 if (S_ISDIR (src_mode) && !x->recursive)
1246 error (0, 0, _("omitting directory %s"), quote (src_name));
1247 return false;
1250 /* Detect the case in which the same source file appears more than
1251 once on the command line and no backup option has been selected.
1252 If so, simply warn and don't copy it the second time.
1253 This check is enabled only if x->src_info is non-NULL. */
1254 if (command_line_arg)
1256 if ( ! S_ISDIR (src_sb.st_mode)
1257 && x->backup_type == no_backups
1258 && seen_file (x->src_info, src_name, &src_sb))
1260 error (0, 0, _("warning: source file %s specified more than once"),
1261 quote (src_name));
1262 return true;
1265 record_file (x->src_info, src_name, &src_sb);
1268 if (!new_dst)
1270 /* Regular files can be created by writing through symbolic
1271 links, but other files cannot. So use stat on the
1272 destination when copying a regular file, and lstat otherwise.
1273 However, if we intend to unlink or remove the destination
1274 first, use lstat, since a copy won't actually be made to the
1275 destination in that case. */
1276 bool use_stat =
1277 ((S_ISREG (src_mode)
1278 || (x->copy_as_regular
1279 && ! (S_ISDIR (src_mode) || S_ISLNK (src_mode))))
1280 && ! (x->move_mode || x->symbolic_link || x->hard_link
1281 || x->backup_type != no_backups
1282 || x->unlink_dest_before_opening));
1283 if ((use_stat
1284 ? stat (dst_name, &dst_sb)
1285 : lstat (dst_name, &dst_sb))
1286 != 0)
1288 if (errno != ENOENT)
1290 error (0, errno, _("cannot stat %s"), quote (dst_name));
1291 return false;
1293 else
1295 new_dst = true;
1298 else
1299 { /* Here, we know that dst_name exists, at least to the point
1300 that it is stat'able or lstat'able. */
1301 bool return_now;
1302 bool unlink_src;
1304 have_dst_lstat = !use_stat;
1305 if (! same_file_ok (src_name, &src_sb, dst_name, &dst_sb,
1306 x, &return_now, &unlink_src))
1308 error (0, 0, _("%s and %s are the same file"),
1309 quote_n (0, src_name), quote_n (1, dst_name));
1310 return false;
1313 if (!S_ISDIR (src_mode) && x->update)
1315 /* When preserving time stamps (but not moving within a file
1316 system), don't worry if the destination time stamp is
1317 less than the source merely because of time stamp
1318 truncation. */
1319 int options = ((x->preserve_timestamps
1320 && ! (x->move_mode
1321 && dst_sb.st_dev == src_sb.st_dev))
1322 ? UTIMECMP_TRUNCATE_SOURCE
1323 : 0);
1325 if (0 <= utimecmp (dst_name, &dst_sb, &src_sb, options))
1327 /* We're using --update and the destination is not older
1328 than the source, so do not copy or move. Pretend the
1329 rename succeeded, so the caller (if it's mv) doesn't
1330 end up removing the source file. */
1331 if (rename_succeeded)
1332 *rename_succeeded = true;
1333 return true;
1337 /* When there is an existing destination file, we may end up
1338 returning early, and hence not copying/moving the file.
1339 This may be due to an interactive `negative' reply to the
1340 prompt about the existing file. It may also be due to the
1341 use of the --reply=no option.
1343 cp and mv treat -i and -f differently. */
1344 if (x->move_mode)
1346 if (abandon_move (x, dst_name, &dst_sb)
1347 || (unlink_src && unlink (src_name) == 0))
1349 /* Pretend the rename succeeded, so the caller (mv)
1350 doesn't end up removing the source file. */
1351 if (rename_succeeded)
1352 *rename_succeeded = true;
1353 if (unlink_src && x->verbose)
1354 printf (_("removed %s\n"), quote (src_name));
1355 return true;
1357 if (unlink_src)
1359 error (0, errno, _("cannot remove %s"), quote (src_name));
1360 return false;
1363 else
1365 if (! S_ISDIR (src_mode)
1366 && (x->interactive == I_ALWAYS_NO
1367 || (x->interactive == I_ASK_USER
1368 && (overwrite_prompt (dst_name, &dst_sb), 1)
1369 && ! yesno ())))
1370 return true;
1373 if (return_now)
1374 return true;
1376 if (!S_ISDIR (dst_sb.st_mode))
1378 if (S_ISDIR (src_mode))
1380 if (x->move_mode && x->backup_type != no_backups)
1382 /* Moving a directory onto an existing
1383 non-directory is ok only with --backup. */
1385 else
1387 error (0, 0,
1388 _("cannot overwrite non-directory %s with directory %s"),
1389 quote_n (0, dst_name), quote_n (1, src_name));
1390 return false;
1394 /* Don't let the user destroy their data, even if they try hard:
1395 This mv command must fail (likewise for cp):
1396 rm -rf a b c; mkdir a b c; touch a/f b/f; mv a/f b/f c
1397 Otherwise, the contents of b/f would be lost.
1398 In the case of `cp', b/f would be lost if the user simulated
1399 a move using cp and rm.
1400 Note that it works fine if you use --backup=numbered. */
1401 if (command_line_arg
1402 && x->backup_type != numbered_backups
1403 && seen_file (x->dest_info, dst_name, &dst_sb))
1405 error (0, 0,
1406 _("will not overwrite just-created %s with %s"),
1407 quote_n (0, dst_name), quote_n (1, src_name));
1408 return false;
1412 if (!S_ISDIR (src_mode))
1414 if (S_ISDIR (dst_sb.st_mode))
1416 if (x->move_mode && x->backup_type != no_backups)
1418 /* Moving a non-directory onto an existing
1419 directory is ok only with --backup. */
1421 else
1423 error (0, 0,
1424 _("cannot overwrite directory %s with non-directory"),
1425 quote (dst_name));
1426 return false;
1431 if (x->move_mode)
1433 /* Don't allow user to move a directory onto a non-directory. */
1434 if (S_ISDIR (src_sb.st_mode) && !S_ISDIR (dst_sb.st_mode)
1435 && x->backup_type == no_backups)
1437 error (0, 0,
1438 _("cannot move directory onto non-directory: %s -> %s"),
1439 quote_n (0, src_name), quote_n (0, dst_name));
1440 return false;
1444 if (x->backup_type != no_backups
1445 /* Don't try to back up a destination if the last
1446 component of src_name is "." or "..". */
1447 && ! dot_or_dotdot (last_component (src_name))
1448 /* Create a backup of each destination directory in move mode,
1449 but not in copy mode. FIXME: it might make sense to add an
1450 option to suppress backup creation also for move mode.
1451 That would let one use mv to merge new content into an
1452 existing hierarchy. */
1453 && (x->move_mode || ! S_ISDIR (dst_sb.st_mode)))
1455 char *tmp_backup = find_backup_file_name (dst_name,
1456 x->backup_type);
1458 /* Detect (and fail) when creating the backup file would
1459 destroy the source file. Before, running the commands
1460 cd /tmp; rm -f a a~; : > a; echo A > a~; cp --b=simple a~ a
1461 would leave two zero-length files: a and a~. */
1462 /* FIXME: but simply change e.g., the final a~ to `./a~'
1463 and the source will still be destroyed. */
1464 if (STREQ (tmp_backup, src_name))
1466 const char *fmt;
1467 fmt = (x->move_mode
1468 ? _("backing up %s would destroy source; %s not moved")
1469 : _("backing up %s would destroy source; %s not copied"));
1470 error (0, 0, fmt,
1471 quote_n (0, dst_name),
1472 quote_n (1, src_name));
1473 free (tmp_backup);
1474 return false;
1477 /* FIXME: use fts:
1478 Using alloca for a file name that may be arbitrarily
1479 long is not recommended. In fact, even forming such a name
1480 should be discouraged. Eventually, this code will be rewritten
1481 to use fts, so using alloca here will be less of a problem. */
1482 ASSIGN_STRDUPA (dst_backup, tmp_backup);
1483 free (tmp_backup);
1484 if (rename (dst_name, dst_backup) != 0)
1486 if (errno != ENOENT)
1488 error (0, errno, _("cannot backup %s"), quote (dst_name));
1489 return false;
1491 else
1493 dst_backup = NULL;
1496 else
1498 backup_succeeded = true;
1500 new_dst = true;
1502 else if (! S_ISDIR (dst_sb.st_mode)
1503 /* Never unlink dst_name when in move mode. */
1504 && ! x->move_mode
1505 && (x->unlink_dest_before_opening
1506 || (x->preserve_links && 1 < dst_sb.st_nlink)
1507 || (x->dereference == DEREF_NEVER
1508 && ! S_ISREG (src_sb.st_mode))
1511 if (unlink (dst_name) != 0 && errno != ENOENT)
1513 error (0, errno, _("cannot remove %s"), quote (dst_name));
1514 return false;
1516 new_dst = true;
1517 if (x->verbose)
1518 printf (_("removed %s\n"), quote (dst_name));
1523 /* Ensure we don't try to copy through a symlink that was
1524 created by a prior call to this function. */
1525 if (command_line_arg
1526 && x->dest_info
1527 && ! x->move_mode
1528 && x->backup_type == no_backups)
1530 bool lstat_ok = true;
1531 struct stat tmp_buf;
1532 struct stat *dst_lstat_sb;
1534 /* If we called lstat above, good: use that data.
1535 Otherwise, call lstat here, in case dst_name is a symlink. */
1536 if (have_dst_lstat)
1537 dst_lstat_sb = &dst_sb;
1538 else
1540 if (lstat (dst_name, &tmp_buf) == 0)
1541 dst_lstat_sb = &tmp_buf;
1542 else
1543 lstat_ok = false;
1546 /* Never copy through a symlink we've just created. */
1547 if (lstat_ok
1548 && S_ISLNK (dst_lstat_sb->st_mode)
1549 && seen_file (x->dest_info, dst_name, dst_lstat_sb))
1551 error (0, 0,
1552 _("will not copy %s through just-created symlink %s"),
1553 quote_n (0, src_name), quote_n (1, dst_name));
1554 return false;
1558 /* If the source is a directory, we don't always create the destination
1559 directory. So --verbose should not announce anything until we're
1560 sure we'll create a directory. */
1561 if (x->verbose && !S_ISDIR (src_mode))
1562 emit_verbose (src_name, dst_name, backup_succeeded ? dst_backup : NULL);
1564 /* Associate the destination file name with the source device and inode
1565 so that if we encounter a matching dev/ino pair in the source tree
1566 we can arrange to create a hard link between the corresponding names
1567 in the destination tree.
1569 When using the --link (-l) option, there is no need to take special
1570 measures, because (barring race conditions) files that are hard-linked
1571 in the source tree will also be hard-linked in the destination tree.
1573 Sometimes, when preserving links, we have to record dev/ino even
1574 though st_nlink == 1:
1575 - when in move_mode, since we may be moving a group of N hard-linked
1576 files (via two or more command line arguments) to a different
1577 partition; the links may be distributed among the command line
1578 arguments (possibly hierarchies) so that the link count of
1579 the final, once-linked source file is reduced to 1 when it is
1580 considered below. But in this case (for mv) we don't need to
1581 incur the expense of recording the dev/ino => name mapping; all we
1582 really need is a lookup, to see if the dev/ino pair has already
1583 been copied.
1584 - when using -H and processing a command line argument;
1585 that command line argument could be a symlink pointing to another
1586 command line argument. With `cp -H --preserve=link', we hard-link
1587 those two destination files.
1588 - likewise for -L except that it applies to all files, not just
1589 command line arguments.
1591 Also, with --recursive, record dev/ino of each command-line directory.
1592 We'll use that info to detect this problem: cp -R dir dir. */
1594 if (x->move_mode && src_sb.st_nlink == 1)
1596 earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev);
1598 else if (x->preserve_links
1599 && !x->hard_link
1600 && (1 < src_sb.st_nlink
1601 || (command_line_arg
1602 && x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
1603 || x->dereference == DEREF_ALWAYS))
1605 earlier_file = remember_copied (dst_name, src_sb.st_ino, src_sb.st_dev);
1607 else if (x->recursive && S_ISDIR (src_mode))
1609 if (command_line_arg)
1610 earlier_file = remember_copied (dst_name, src_sb.st_ino, src_sb.st_dev);
1611 else
1612 earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev);
1615 /* Did we copy this inode somewhere else (in this command line argument)
1616 and therefore this is a second hard link to the inode? */
1618 if (earlier_file)
1620 /* Avoid damaging the destination file system by refusing to preserve
1621 hard-linked directories (which are found at least in Netapp snapshot
1622 directories). */
1623 if (S_ISDIR (src_mode))
1625 /* If src_name and earlier_file refer to the same directory entry,
1626 then warn about copying a directory into itself. */
1627 if (same_name (src_name, earlier_file))
1629 error (0, 0, _("cannot copy a directory, %s, into itself, %s"),
1630 quote_n (0, top_level_src_name),
1631 quote_n (1, top_level_dst_name));
1632 *copy_into_self = true;
1633 goto un_backup;
1635 else if (x->dereference == DEREF_ALWAYS)
1637 /* This happens when e.g., encountering a directory for the
1638 second or subsequent time via symlinks when cp is invoked
1639 with -R and -L. E.g.,
1640 rm -rf a b c d; mkdir a b c d; ln -s ../c a; ln -s ../c b;
1641 cp -RL a b d
1644 else
1646 error (0, 0, _("will not create hard link %s to directory %s"),
1647 quote_n (0, dst_name), quote_n (1, earlier_file));
1648 goto un_backup;
1651 else
1653 bool link_failed = (link (earlier_file, dst_name) != 0);
1655 /* If the link failed because of an existing destination,
1656 remove that file and then call link again. */
1657 if (link_failed && errno == EEXIST)
1659 if (unlink (dst_name) != 0)
1661 error (0, errno, _("cannot remove %s"), quote (dst_name));
1662 goto un_backup;
1664 if (x->verbose)
1665 printf (_("removed %s\n"), quote (dst_name));
1666 link_failed = (link (earlier_file, dst_name) != 0);
1669 if (link_failed)
1671 error (0, errno, _("cannot create hard link %s to %s"),
1672 quote_n (0, dst_name), quote_n (1, earlier_file));
1673 goto un_backup;
1676 return true;
1680 if (x->move_mode)
1682 if (rename (src_name, dst_name) == 0)
1684 if (x->verbose && S_ISDIR (src_mode))
1685 emit_verbose (src_name, dst_name,
1686 backup_succeeded ? dst_backup : NULL);
1688 if (rename_succeeded)
1689 *rename_succeeded = true;
1691 if (command_line_arg)
1693 /* Record destination dev/ino/name, so that if we are asked
1694 to overwrite that file again, we can detect it and fail. */
1695 /* It's fine to use the _source_ stat buffer (src_sb) to get the
1696 _destination_ dev/ino, since the rename above can't have
1697 changed those, and `mv' always uses lstat.
1698 We could limit it further by operating
1699 only on non-directories. */
1700 record_file (x->dest_info, dst_name, &src_sb);
1703 return true;
1706 /* FIXME: someday, consider what to do when moving a directory into
1707 itself but when source and destination are on different devices. */
1709 /* This happens when attempting to rename a directory to a
1710 subdirectory of itself. */
1711 if (errno == EINVAL)
1713 /* FIXME: this is a little fragile in that it relies on rename(2)
1714 failing with a specific errno value. Expect problems on
1715 non-POSIX systems. */
1716 error (0, 0, _("cannot move %s to a subdirectory of itself, %s"),
1717 quote_n (0, top_level_src_name),
1718 quote_n (1, top_level_dst_name));
1720 /* Note that there is no need to call forget_created here,
1721 (compare with the other calls in this file) since the
1722 destination directory didn't exist before. */
1724 *copy_into_self = true;
1725 /* FIXME-cleanup: Don't return true here; adjust mv.c accordingly.
1726 The only caller that uses this code (mv.c) ends up setting its
1727 exit status to nonzero when copy_into_self is nonzero. */
1728 return true;
1731 /* WARNING: there probably exist systems for which an inter-device
1732 rename fails with a value of errno not handled here.
1733 If/as those are reported, add them to the condition below.
1734 If this happens to you, please do the following and send the output
1735 to the bug-reporting address (e.g., in the output of cp --help):
1736 touch k; perl -e 'rename "k","/tmp/k" or print "$!(",$!+0,")\n"'
1737 where your current directory is on one partion and /tmp is the other.
1738 Also, please try to find the E* errno macro name corresponding to
1739 the diagnostic and parenthesized integer, and include that in your
1740 e-mail. One way to do that is to run a command like this
1741 find /usr/include/. -type f \
1742 | xargs grep 'define.*\<E[A-Z]*\>.*\<18\>' /dev/null
1743 where you'd replace `18' with the integer in parentheses that
1744 was output from the perl one-liner above.
1745 If necessary, of course, change `/tmp' to some other directory. */
1746 if (errno != EXDEV)
1748 /* There are many ways this can happen due to a race condition.
1749 When something happens between the initial XSTAT and the
1750 subsequent rename, we can get many different types of errors.
1751 For example, if the destination is initially a non-directory
1752 or non-existent, but it is created as a directory, the rename
1753 fails. If two `mv' commands try to rename the same file at
1754 about the same time, one will succeed and the other will fail.
1755 If the permissions on the directory containing the source or
1756 destination file are made too restrictive, the rename will
1757 fail. Etc. */
1758 error (0, errno,
1759 _("cannot move %s to %s"),
1760 quote_n (0, src_name), quote_n (1, dst_name));
1761 forget_created (src_sb.st_ino, src_sb.st_dev);
1762 return false;
1765 /* The rename attempt has failed. Remove any existing destination
1766 file so that a cross-device `mv' acts as if it were really using
1767 the rename syscall. */
1768 if (unlink (dst_name) != 0 && errno != ENOENT)
1770 error (0, errno,
1771 _("inter-device move failed: %s to %s; unable to remove target"),
1772 quote_n (0, src_name), quote_n (1, dst_name));
1773 forget_created (src_sb.st_ino, src_sb.st_dev);
1774 return false;
1777 new_dst = true;
1780 /* If the ownership might change, or if it is a directory (whose
1781 special mode bits may change after the directory is created),
1782 omit some permissions at first, so unauthorized users cannot nip
1783 in before the file is ready. */
1784 dst_mode_bits = (x->set_mode ? x->mode : src_mode) & CHMOD_MODE_BITS;
1785 omitted_permissions =
1786 (dst_mode_bits
1787 & (x->preserve_ownership ? S_IRWXG | S_IRWXO
1788 : S_ISDIR (src_mode) ? S_IWGRP | S_IWOTH
1789 : 0));
1791 delayed_ok = true;
1793 if (x->preserve_security_context)
1795 security_context_t con;
1797 if (0 <= lgetfilecon (src_name, &con))
1799 if (setfscreatecon (con) < 0)
1801 if (!x->reduce_diagnostics || x->require_preserve_context)
1802 error (0, errno,
1803 _("failed to set default file creation context to %s"),
1804 quote (con));
1805 if (x->require_preserve_context)
1807 freecon (con);
1808 return false;
1811 freecon (con);
1813 else
1815 if (!errno_unsupported (errno) || x->require_preserve_context)
1817 if (!x->reduce_diagnostics || x->require_preserve_context)
1818 error (0, errno,
1819 _("failed to get security context of %s"),
1820 quote (src_name));
1821 if (x->require_preserve_context)
1822 return false;
1827 if (S_ISDIR (src_mode))
1829 struct dir_list *dir;
1831 /* If this directory has been copied before during the
1832 recursion, there is a symbolic link to an ancestor
1833 directory of the symbolic link. It is impossible to
1834 continue to copy this, unless we've got an infinite disk. */
1836 if (is_ancestor (&src_sb, ancestors))
1838 error (0, 0, _("cannot copy cyclic symbolic link %s"),
1839 quote (src_name));
1840 goto un_backup;
1843 /* Insert the current directory in the list of parents. */
1845 dir = alloca (sizeof *dir);
1846 dir->parent = ancestors;
1847 dir->ino = src_sb.st_ino;
1848 dir->dev = src_sb.st_dev;
1850 if (new_dst || !S_ISDIR (dst_sb.st_mode))
1852 /* POSIX says mkdir's behavior is implementation-defined when
1853 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
1854 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
1855 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
1856 if (mkdir (dst_name, dst_mode_bits & ~omitted_permissions) != 0)
1858 error (0, errno, _("cannot create directory %s"),
1859 quote (dst_name));
1860 goto un_backup;
1863 /* We need search and write permissions to the new directory
1864 for writing the directory's contents. Check if these
1865 permissions are there. */
1867 if (lstat (dst_name, &dst_sb) != 0)
1869 error (0, errno, _("cannot stat %s"), quote (dst_name));
1870 goto un_backup;
1872 else if ((dst_sb.st_mode & S_IRWXU) != S_IRWXU)
1874 /* Make the new directory searchable and writable. */
1876 dst_mode = dst_sb.st_mode;
1877 restore_dst_mode = true;
1879 if (lchmod (dst_name, dst_mode | S_IRWXU) != 0)
1881 error (0, errno, _("setting permissions for %s"),
1882 quote (dst_name));
1883 goto un_backup;
1887 /* Record the created directory's inode and device numbers into
1888 the search structure, so that we can avoid copying it again.
1889 Do this only for the first directory that is created for each
1890 source command line argument. */
1891 if (!*first_dir_created_per_command_line_arg)
1893 remember_copied (dst_name, dst_sb.st_ino, dst_sb.st_dev);
1894 *first_dir_created_per_command_line_arg = true;
1897 if (x->verbose)
1898 emit_verbose (src_name, dst_name, NULL);
1901 /* Decide whether to copy the contents of the directory. */
1902 if (x->one_file_system && device != 0 && device != src_sb.st_dev)
1904 /* Here, we are crossing a file system boundary and cp's -x option
1905 is in effect: so don't copy the contents of this directory. */
1907 else
1909 /* Copy the contents of the directory. Don't just return if
1910 this fails -- otherwise, the failure to read a single file
1911 in a source directory would cause the containing destination
1912 directory not to have owner/perms set properly. */
1913 delayed_ok = copy_dir (src_name, dst_name, new_dst, &src_sb, dir, x,
1914 first_dir_created_per_command_line_arg,
1915 copy_into_self);
1918 else if (x->symbolic_link)
1920 dest_is_symlink = true;
1921 if (*src_name != '/')
1923 /* Check that DST_NAME denotes a file in the current directory. */
1924 struct stat dot_sb;
1925 struct stat dst_parent_sb;
1926 char *dst_parent;
1927 bool in_current_dir;
1929 dst_parent = dir_name (dst_name);
1931 in_current_dir = (STREQ (".", dst_parent)
1932 /* If either stat call fails, it's ok not to report
1933 the failure and say dst_name is in the current
1934 directory. Other things will fail later. */
1935 || stat (".", &dot_sb) != 0
1936 || stat (dst_parent, &dst_parent_sb) != 0
1937 || SAME_INODE (dot_sb, dst_parent_sb));
1938 free (dst_parent);
1940 if (! in_current_dir)
1942 error (0, 0,
1943 _("%s: can make relative symbolic links only in current directory"),
1944 quote (dst_name));
1945 goto un_backup;
1948 if (symlink (src_name, dst_name) != 0)
1950 error (0, errno, _("cannot create symbolic link %s to %s"),
1951 quote_n (0, dst_name), quote_n (1, src_name));
1952 goto un_backup;
1956 else if (x->hard_link
1957 #ifdef LINK_FOLLOWS_SYMLINKS
1958 /* A POSIX-conforming link syscall dereferences a symlink, yet cp,
1959 invoked with `--link --no-dereference', should not. Thus, with
1960 a POSIX-conforming link system call, we can't use link() here,
1961 since that would create a hard link to the referent (effectively
1962 dereferencing the symlink), rather than to the symlink itself.
1963 We can approximate the desired behavior by skipping this hard-link
1964 creating block and instead copying the symlink, via the `S_ISLNK'-
1965 copying code below.
1966 When link operates on the symlinks themselves, we use this block
1967 and just call link(). */
1968 && !(S_ISLNK (src_mode) && x->dereference == DEREF_NEVER)
1969 #endif
1972 if (link (src_name, dst_name))
1974 error (0, errno, _("cannot create link %s"), quote (dst_name));
1975 goto un_backup;
1978 else if (S_ISREG (src_mode)
1979 || (x->copy_as_regular && !S_ISLNK (src_mode)))
1981 copied_as_regular = true;
1982 /* POSIX says the permission bits of the source file must be
1983 used as the 3rd argument in the open call. Historical
1984 practice passed all the source mode bits to 'open', but the extra
1985 bits were ignored, so it should be the same either way. */
1986 if (! copy_reg (src_name, dst_name, x, src_mode & S_IRWXUGO,
1987 omitted_permissions, &new_dst, &src_sb))
1988 goto un_backup;
1990 else if (S_ISFIFO (src_mode))
1992 /* Use mknod, rather than mkfifo, because the former preserves
1993 the special mode bits of a fifo on Solaris 10, while mkfifo
1994 does not. But fall back on mkfifo, because on some BSD systems,
1995 mknod always fails when asked to create a FIFO. */
1996 if (mknod (dst_name, src_mode & ~omitted_permissions, 0) != 0)
1997 if (mkfifo (dst_name, src_mode & ~S_IFIFO & ~omitted_permissions) != 0)
1999 error (0, errno, _("cannot create fifo %s"), quote (dst_name));
2000 goto un_backup;
2003 else if (S_ISBLK (src_mode) || S_ISCHR (src_mode) || S_ISSOCK (src_mode))
2005 if (mknod (dst_name, src_mode & ~omitted_permissions, src_sb.st_rdev)
2006 != 0)
2008 error (0, errno, _("cannot create special file %s"),
2009 quote (dst_name));
2010 goto un_backup;
2013 else if (S_ISLNK (src_mode))
2015 char *src_link_val = areadlink_with_size (src_name, src_sb.st_size);
2016 dest_is_symlink = true;
2017 if (src_link_val == NULL)
2019 error (0, errno, _("cannot read symbolic link %s"), quote (src_name));
2020 goto un_backup;
2023 if (symlink (src_link_val, dst_name) == 0)
2024 free (src_link_val);
2025 else
2027 int saved_errno = errno;
2028 bool same_link = false;
2029 if (x->update && !new_dst && S_ISLNK (dst_sb.st_mode)
2030 && dst_sb.st_size == strlen (src_link_val))
2032 /* See if the destination is already the desired symlink.
2033 FIXME: This behavior isn't documented, and seems wrong
2034 in some cases, e.g., if the destination symlink has the
2035 wrong ownership, permissions, or time stamps. */
2036 char *dest_link_val =
2037 areadlink_with_size (dst_name, dst_sb.st_size);
2038 if (dest_link_val && STREQ (dest_link_val, src_link_val))
2039 same_link = true;
2040 free (dest_link_val);
2042 free (src_link_val);
2044 if (! same_link)
2046 error (0, saved_errno, _("cannot create symbolic link %s"),
2047 quote (dst_name));
2048 goto un_backup;
2052 if (x->preserve_security_context)
2053 restore_default_fscreatecon_or_die ();
2055 if (x->preserve_ownership)
2057 /* Preserve the owner and group of the just-`copied'
2058 symbolic link, if possible. */
2059 if (HAVE_LCHOWN
2060 && lchown (dst_name, src_sb.st_uid, src_sb.st_gid) != 0
2061 && ! chown_failure_ok (x))
2063 error (0, errno, _("failed to preserve ownership for %s"),
2064 dst_name);
2065 goto un_backup;
2067 else
2069 /* Can't preserve ownership of symlinks.
2070 FIXME: maybe give a warning or even error for symlinks
2071 in directories with the sticky bit set -- there, not
2072 preserving owner/group is a potential security problem. */
2076 else
2078 error (0, 0, _("%s has unknown file type"), quote (src_name));
2079 goto un_backup;
2082 if (command_line_arg && x->dest_info)
2084 /* Now that the destination file is very likely to exist,
2085 add its info to the set. */
2086 struct stat sb;
2087 if (lstat (dst_name, &sb) == 0)
2088 record_file (x->dest_info, dst_name, &sb);
2091 /* If we've just created a hard-link due to cp's --link option,
2092 we're done. */
2093 if (x->hard_link && ! S_ISDIR (src_mode))
2094 return delayed_ok;
2096 if (copied_as_regular)
2097 return delayed_ok;
2099 /* POSIX says that `cp -p' must restore the following:
2100 - permission bits
2101 - setuid, setgid bits
2102 - owner and group
2103 If it fails to restore any of those, we may give a warning but
2104 the destination must not be removed.
2105 FIXME: implement the above. */
2107 /* Adjust the times (and if possible, ownership) for the copy.
2108 chown turns off set[ug]id bits for non-root,
2109 so do the chmod last. */
2111 if (x->preserve_timestamps)
2113 struct timespec timespec[2];
2114 timespec[0] = get_stat_atime (&src_sb);
2115 timespec[1] = get_stat_mtime (&src_sb);
2117 if (utimensat_if_possible (dst_name, timespec) != 0)
2119 error (0, errno, _("preserving times for %s"), quote (dst_name));
2120 if (x->require_preserve)
2121 return false;
2125 /* The operations beyond this point may dereference a symlink. */
2126 if (dest_is_symlink)
2127 return delayed_ok;
2129 /* Avoid calling chown if we know it's not necessary. */
2130 if (x->preserve_ownership
2131 && (new_dst || !SAME_OWNER_AND_GROUP (src_sb, dst_sb)))
2133 switch (set_owner (x, dst_name, -1, &src_sb, new_dst, &dst_sb))
2135 case -1:
2136 return false;
2138 case 0:
2139 src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX);
2140 break;
2144 set_author (dst_name, -1, &src_sb);
2146 if (x->preserve_xattr && ! copy_attr_by_name (src_name, dst_name, x)
2147 && x->require_preserve_xattr)
2148 return false;
2150 if (x->preserve_mode || x->move_mode)
2152 if (copy_acl (src_name, -1, dst_name, -1, src_mode) != 0
2153 && x->require_preserve)
2154 return false;
2156 else if (x->set_mode)
2158 if (set_acl (dst_name, -1, x->mode) != 0)
2159 return false;
2161 else
2163 if (omitted_permissions)
2165 omitted_permissions &= ~ cached_umask ();
2167 if (omitted_permissions && !restore_dst_mode)
2169 /* Permissions were deliberately omitted when the file
2170 was created due to security concerns. See whether
2171 they need to be re-added now. It'd be faster to omit
2172 the lstat, but deducing the current destination mode
2173 is tricky in the presence of implementation-defined
2174 rules for special mode bits. */
2175 if (new_dst && lstat (dst_name, &dst_sb) != 0)
2177 error (0, errno, _("cannot stat %s"), quote (dst_name));
2178 return false;
2180 dst_mode = dst_sb.st_mode;
2181 if (omitted_permissions & ~dst_mode)
2182 restore_dst_mode = true;
2186 if (restore_dst_mode)
2188 if (lchmod (dst_name, dst_mode | omitted_permissions) != 0)
2190 error (0, errno, _("preserving permissions for %s"),
2191 quote (dst_name));
2192 if (x->require_preserve)
2193 return false;
2198 return delayed_ok;
2200 un_backup:
2202 if (x->preserve_security_context)
2203 restore_default_fscreatecon_or_die ();
2205 /* We have failed to create the destination file.
2206 If we've just added a dev/ino entry via the remember_copied
2207 call above (i.e., unless we've just failed to create a hard link),
2208 remove the entry associating the source dev/ino with the
2209 destination file name, so we don't try to `preserve' a link
2210 to a file we didn't create. */
2211 if (earlier_file == NULL)
2212 forget_created (src_sb.st_ino, src_sb.st_dev);
2214 if (dst_backup)
2216 if (rename (dst_backup, dst_name) != 0)
2217 error (0, errno, _("cannot un-backup %s"), quote (dst_name));
2218 else
2220 if (x->verbose)
2221 printf (_("%s -> %s (unbackup)\n"),
2222 quote_n (0, dst_backup), quote_n (1, dst_name));
2225 return false;
2228 static bool
2229 valid_options (const struct cp_options *co)
2231 assert (co != NULL);
2232 assert (VALID_BACKUP_TYPE (co->backup_type));
2233 assert (VALID_SPARSE_MODE (co->sparse_mode));
2234 assert (!(co->hard_link && co->symbolic_link));
2235 return true;
2238 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
2239 any type. NONEXISTENT_DST should be true if the file DST_NAME
2240 is known not to exist (e.g., because its parent directory was just
2241 created); NONEXISTENT_DST should be false if DST_NAME might already
2242 exist. OPTIONS is ... FIXME-describe
2243 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
2244 same as) DST_NAME; otherwise, set clear it.
2245 Return true if successful. */
2247 extern bool
2248 copy (char const *src_name, char const *dst_name,
2249 bool nonexistent_dst, const struct cp_options *options,
2250 bool *copy_into_self, bool *rename_succeeded)
2252 assert (valid_options (options));
2254 /* Record the file names: they're used in case of error, when copying
2255 a directory into itself. I don't like to make these tools do *any*
2256 extra work in the common case when that work is solely to handle
2257 exceptional cases, but in this case, I don't see a way to derive the
2258 top level source and destination directory names where they're used.
2259 An alternative is to use COPY_INTO_SELF and print the diagnostic
2260 from every caller -- but I don't want to do that. */
2261 top_level_src_name = src_name;
2262 top_level_dst_name = dst_name;
2264 bool first_dir_created_per_command_line_arg = false;
2265 return copy_internal (src_name, dst_name, nonexistent_dst, 0, NULL,
2266 options, true,
2267 &first_dir_created_per_command_line_arg,
2268 copy_into_self, rename_succeeded);
2271 /* Set *X to the default options for a value of type struct cp_options. */
2273 extern void
2274 cp_options_default (struct cp_options *x)
2276 memset (x, 0, sizeof *x);
2277 #ifdef PRIV_FILE_CHOWN
2279 priv_set_t *pset = priv_allocset ();
2280 if (!pset)
2281 xalloc_die ();
2282 if (getppriv (PRIV_EFFECTIVE, pset) == 0)
2284 x->chown_privileges = priv_ismember (pset, PRIV_FILE_CHOWN);
2285 x->owner_privileges = priv_ismember (pset, PRIV_FILE_OWNER);
2287 priv_freeset (pset);
2289 #else
2290 x->chown_privileges = x->owner_privileges = (geteuid () == 0);
2291 #endif
2294 /* Return true if it's OK for chown to fail, where errno is
2295 the error number that chown failed with and X is the copying
2296 option set. */
2298 extern bool
2299 chown_failure_ok (struct cp_options const *x)
2301 /* If non-root uses -p, it's ok if we can't preserve ownership.
2302 But root probably wants to know, e.g. if NFS disallows it,
2303 or if the target system doesn't support file ownership. */
2305 return ((errno == EPERM || errno == EINVAL) && !x->chown_privileges);
2308 /* Similarly, return true if it's OK for chmod and similar operations
2309 to fail, where errno is the error number that chmod failed with and
2310 X is the copying option set. */
2312 static bool
2313 owner_failure_ok (struct cp_options const *x)
2315 return ((errno == EPERM || errno == EINVAL) && !x->owner_privileges);
2318 /* Return the user's umask, caching the result. */
2320 extern mode_t
2321 cached_umask (void)
2323 static mode_t mask = (mode_t) -1;
2324 if (mask == (mode_t) -1)
2326 mask = umask (0);
2327 umask (mask);
2329 return mask;