global: convert indentation-TABs to spaces
[coreutils.git] / src / copy.c
blob238764a3998efd2bd0d8b817b9b10d16bde6c4b1
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 /* Set the timestamp of symlink, FILE, to TIMESPEC.
122 If this system lacks support for that, simply return 0. */
123 static inline int
124 utimens_symlink (char const *file, struct timespec const *timespec)
126 int err = 0;
128 #if HAVE_UTIMENSAT
129 err = utimensat (AT_FDCWD, file, timespec, AT_SYMLINK_NOFOLLOW);
130 /* When configuring on a system with new headers and libraries, and
131 running on one with a kernel that is old enough to lack the syscall,
132 utimensat fails with ENOSYS. Ignore that. */
133 if (err && errno == ENOSYS)
134 err = 0;
135 #endif
137 return err;
140 /* Perform the O(1) btrfs clone operation, if possible.
141 Upon success, return 0. Otherwise, return -1 and set errno. */
142 static inline int
143 clone_file (int dest_fd, int src_fd)
145 #ifdef __linux__
146 # undef BTRFS_IOCTL_MAGIC
147 # define BTRFS_IOCTL_MAGIC 0x94
148 # undef BTRFS_IOC_CLONE
149 # define BTRFS_IOC_CLONE _IOW (BTRFS_IOCTL_MAGIC, 9, int)
150 return ioctl (dest_fd, BTRFS_IOC_CLONE, src_fd);
151 #else
152 errno = ENOTSUP;
153 return -1;
154 #endif
157 /* FIXME: describe */
158 /* FIXME: rewrite this to use a hash table so we avoid the quadratic
159 performance hit that's probably noticeable only on trees deeper
160 than a few hundred levels. See use of active_dir_map in remove.c */
162 static bool
163 is_ancestor (const struct stat *sb, const struct dir_list *ancestors)
165 while (ancestors != 0)
167 if (ancestors->ino == sb->st_ino && ancestors->dev == sb->st_dev)
168 return true;
169 ancestors = ancestors->parent;
171 return false;
174 static bool
175 errno_unsupported (int err)
177 return err == ENOTSUP || err == ENODATA;
180 #if USE_XATTR
181 static void
182 copy_attr_error (struct error_context *ctx ATTRIBUTE_UNUSED,
183 char const *fmt, ...)
185 int err = errno;
186 va_list ap;
188 if (!errno_unsupported (errno))
190 /* use verror module to print error message */
191 va_start (ap, fmt);
192 verror (0, err, fmt, ap);
193 va_end (ap);
197 static void
198 copy_attr_allerror (struct error_context *ctx ATTRIBUTE_UNUSED,
199 char const *fmt, ...)
201 int err = errno;
202 va_list ap;
204 /* use verror module to print error message */
205 va_start (ap, fmt);
206 verror (0, err, fmt, ap);
207 va_end (ap);
210 static char const *
211 copy_attr_quote (struct error_context *ctx ATTRIBUTE_UNUSED, char const *str)
213 return quote (str);
216 static void
217 copy_attr_free (struct error_context *ctx ATTRIBUTE_UNUSED,
218 char const *str ATTRIBUTE_UNUSED)
222 static bool
223 copy_attr_by_fd (char const *src_path, int src_fd,
224 char const *dst_path, int dst_fd, const struct cp_options *x)
226 struct error_context ctx =
228 .error = x->require_preserve_xattr ? copy_attr_allerror : copy_attr_error,
229 .quote = copy_attr_quote,
230 .quote_free = copy_attr_free
232 return 0 == attr_copy_fd (src_path, src_fd, dst_path, dst_fd, 0,
233 (x->reduce_diagnostics
234 && !x->require_preserve_xattr)? NULL : &ctx);
237 static bool
238 copy_attr_by_name (char const *src_path, char const *dst_path,
239 const struct cp_options *x)
241 struct error_context ctx =
243 .error = x->require_preserve_xattr ? copy_attr_allerror : copy_attr_error,
244 .quote = copy_attr_quote,
245 .quote_free = copy_attr_free
247 return 0 == attr_copy_file (src_path, dst_path, 0,
248 (x-> reduce_diagnostics
249 && !x->require_preserve_xattr) ? NULL : &ctx);
251 #else /* USE_XATTR */
253 static bool
254 copy_attr_by_fd (char const *src_path, int src_fd,
255 char const *dst_path, int dst_fd, const struct cp_options *x)
257 return true;
260 static bool
261 copy_attr_by_name (char const *src_path, char const *dst_path,
262 const struct cp_options *x)
264 return true;
266 #endif /* USE_XATTR */
268 /* Read the contents of the directory SRC_NAME_IN, and recursively
269 copy the contents to DST_NAME_IN. NEW_DST is true if
270 DST_NAME_IN is a directory that was created previously in the
271 recursion. SRC_SB and ANCESTORS describe SRC_NAME_IN.
272 Set *COPY_INTO_SELF if SRC_NAME_IN is a parent of
273 FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG FIXME
274 (or the same as) DST_NAME_IN; otherwise, clear it.
275 Return true if successful. */
277 static bool
278 copy_dir (char const *src_name_in, char const *dst_name_in, bool new_dst,
279 const struct stat *src_sb, struct dir_list *ancestors,
280 const struct cp_options *x,
281 bool *first_dir_created_per_command_line_arg,
282 bool *copy_into_self)
284 char *name_space;
285 char *namep;
286 struct cp_options non_command_line_options = *x;
287 bool ok = true;
289 name_space = savedir (src_name_in);
290 if (name_space == NULL)
292 /* This diagnostic is a bit vague because savedir can fail in
293 several different ways. */
294 error (0, errno, _("cannot access %s"), quote (src_name_in));
295 return false;
298 /* For cp's -H option, dereference command line arguments, but do not
299 dereference symlinks that are found via recursive traversal. */
300 if (x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
301 non_command_line_options.dereference = DEREF_NEVER;
303 namep = name_space;
304 while (*namep != '\0')
306 bool local_copy_into_self;
307 char *src_name = file_name_concat (src_name_in, namep, NULL);
308 char *dst_name = file_name_concat (dst_name_in, namep, NULL);
310 ok &= copy_internal (src_name, dst_name, new_dst, src_sb->st_dev,
311 ancestors, &non_command_line_options, false,
312 first_dir_created_per_command_line_arg,
313 &local_copy_into_self, NULL);
314 *copy_into_self |= local_copy_into_self;
316 free (dst_name);
317 free (src_name);
319 /* If we're copying into self, there's no point in continuing,
320 and in fact, that would even infloop, now that we record only
321 the first created directory per command line argument. */
322 if (local_copy_into_self)
323 break;
325 namep += strlen (namep) + 1;
327 free (name_space);
328 return ok;
331 /* Set the owner and owning group of DEST_DESC to the st_uid and
332 st_gid fields of SRC_SB. If DEST_DESC is undefined (-1), set
333 the owner and owning group of DST_NAME instead; for
334 safety prefer lchown if the system supports it since no
335 symbolic links should be involved. DEST_DESC must
336 refer to the same file as DEST_NAME if defined.
337 Upon failure to set both UID and GID, try to set only the GID.
338 NEW_DST is true if the file was newly created; otherwise,
339 DST_SB is the status of the destination.
340 Return 1 if the initial syscall succeeds, 0 if it fails but it's OK
341 not to preserve ownership, -1 otherwise. */
343 static int
344 set_owner (const struct cp_options *x, char const *dst_name, int dest_desc,
345 struct stat const *src_sb, bool new_dst,
346 struct stat const *dst_sb)
348 uid_t uid = src_sb->st_uid;
349 gid_t gid = src_sb->st_gid;
351 /* Naively changing the ownership of an already-existing file before
352 changing its permissions would create a window of vulnerability if
353 the file's old permissions are too generous for the new owner and
354 group. Avoid the window by first changing to a restrictive
355 temporary mode if necessary. */
357 if (!new_dst && (x->preserve_mode | x->move_mode | x->set_mode))
359 mode_t old_mode = dst_sb->st_mode;
360 mode_t new_mode =
361 (x->preserve_mode | x->move_mode ? src_sb->st_mode : x->mode);
362 mode_t restrictive_temp_mode = old_mode & new_mode & S_IRWXU;
364 if ((USE_ACL
365 || (old_mode & CHMOD_MODE_BITS
366 & (~new_mode | S_ISUID | S_ISGID | S_ISVTX)))
367 && qset_acl (dst_name, dest_desc, restrictive_temp_mode) != 0)
369 if (! owner_failure_ok (x))
370 error (0, errno, _("clearing permissions for %s"), quote (dst_name));
371 return -x->require_preserve;
375 if (HAVE_FCHOWN && dest_desc != -1)
377 if (fchown (dest_desc, uid, gid) == 0)
378 return 1;
379 if (errno == EPERM || errno == EINVAL)
381 /* We've failed to set *both*. Now, try to set just the group
382 ID, but ignore any failure here, and don't change errno. */
383 int saved_errno = errno;
384 ignore_value (fchown (dest_desc, -1, gid));
385 errno = saved_errno;
388 else
390 if (lchown (dst_name, uid, gid) == 0)
391 return 1;
392 if (errno == EPERM || errno == EINVAL)
394 /* We've failed to set *both*. Now, try to set just the group
395 ID, but ignore any failure here, and don't change errno. */
396 int saved_errno = errno;
397 ignore_value (lchown (dst_name, -1, gid));
398 errno = saved_errno;
402 if (! chown_failure_ok (x))
404 error (0, errno, _("failed to preserve ownership for %s"),
405 quote (dst_name));
406 if (x->require_preserve)
407 return -1;
410 return 0;
413 /* Set the st_author field of DEST_DESC to the st_author field of
414 SRC_SB. If DEST_DESC is undefined (-1), set the st_author field
415 of DST_NAME instead. DEST_DESC must refer to the same file as
416 DEST_NAME if defined. */
418 static void
419 set_author (const char *dst_name, int dest_desc, const struct stat *src_sb)
421 #if HAVE_STRUCT_STAT_ST_AUTHOR
422 /* FIXME: Modify the following code so that it does not
423 follow symbolic links. */
425 /* Preserve the st_author field. */
426 file_t file = (dest_desc < 0
427 ? file_name_lookup (dst_name, 0, 0)
428 : getdport (dest_desc));
429 if (file == MACH_PORT_NULL)
430 error (0, errno, _("failed to lookup file %s"), quote (dst_name));
431 else
433 error_t err = file_chauthor (file, src_sb->st_author);
434 if (err)
435 error (0, err, _("failed to preserve authorship for %s"),
436 quote (dst_name));
437 mach_port_deallocate (mach_task_self (), file);
439 #else
440 (void) dst_name;
441 (void) dest_desc;
442 (void) src_sb;
443 #endif
446 /* Change the file mode bits of the file identified by DESC or NAME to MODE.
447 Use DESC if DESC is valid and fchmod is available, NAME otherwise. */
449 static int
450 fchmod_or_lchmod (int desc, char const *name, mode_t mode)
452 #if HAVE_FCHMOD
453 if (0 <= desc)
454 return fchmod (desc, mode);
455 #endif
456 return lchmod (name, mode);
459 /* Copy a regular file from SRC_NAME to DST_NAME.
460 If the source file contains holes, copies holes and blocks of zeros
461 in the source file as holes in the destination file.
462 (Holes are read as zeroes by the `read' system call.)
463 When creating the destination, use DST_MODE & ~OMITTED_PERMISSIONS
464 as the third argument in the call to open, adding
465 OMITTED_PERMISSIONS after copying as needed.
466 X provides many option settings.
467 Return true if successful.
468 *NEW_DST is as in copy_internal.
469 SRC_SB is the result of calling XSTAT (aka stat) on SRC_NAME. */
471 static bool
472 copy_reg (char const *src_name, char const *dst_name,
473 const struct cp_options *x,
474 mode_t dst_mode, mode_t omitted_permissions, bool *new_dst,
475 struct stat const *src_sb)
477 char *buf;
478 char *buf_alloc = NULL;
479 char *name_alloc = NULL;
480 int dest_desc;
481 int dest_errno;
482 int source_desc;
483 mode_t src_mode = src_sb->st_mode;
484 struct stat sb;
485 struct stat src_open_sb;
486 bool return_val = true;
488 source_desc = open (src_name,
489 (O_RDONLY | O_BINARY
490 | (x->dereference == DEREF_NEVER ? O_NOFOLLOW : 0)));
491 if (source_desc < 0)
493 error (0, errno, _("cannot open %s for reading"), quote (src_name));
494 return false;
497 if (fstat (source_desc, &src_open_sb) != 0)
499 error (0, errno, _("cannot fstat %s"), quote (src_name));
500 return_val = false;
501 goto close_src_desc;
504 /* Compare the source dev/ino from the open file to the incoming,
505 saved ones obtained via a previous call to stat. */
506 if (! SAME_INODE (*src_sb, src_open_sb))
508 error (0, 0,
509 _("skipping file %s, as it was replaced while being copied"),
510 quote (src_name));
511 return_val = false;
512 goto close_src_desc;
515 /* The semantics of the following open calls are mandated
516 by the specs for both cp and mv. */
517 if (! *new_dst)
519 dest_desc = open (dst_name, O_WRONLY | O_TRUNC | O_BINARY);
520 dest_errno = errno;
522 /* When using cp --preserve=context to copy to an existing destination,
523 use the default context rather than that of the source. Why?
524 1) the src context may prohibit writing, and
525 2) because it's more consistent to use the same context
526 that is used when the destination file doesn't already exist. */
527 if (x->preserve_security_context && 0 <= dest_desc)
529 security_context_t con = NULL;
530 if (getfscreatecon (&con) < 0)
532 if (!x->reduce_diagnostics || x->require_preserve_context)
533 error (0, errno, _("failed to get file system create context"));
534 if (x->require_preserve_context)
536 return_val = false;
537 goto close_src_and_dst_desc;
541 if (con)
543 if (fsetfilecon (dest_desc, con) < 0)
545 if (!x->reduce_diagnostics || x->require_preserve_context)
546 error (0, errno,
547 _("failed to set the security context of %s to %s"),
548 quote_n (0, dst_name), quote_n (1, con));
549 if (x->require_preserve_context)
551 return_val = false;
552 freecon (con);
553 goto close_src_and_dst_desc;
556 freecon (con);
560 if (dest_desc < 0 && x->unlink_dest_after_failed_open)
562 if (unlink (dst_name) != 0)
564 error (0, errno, _("cannot remove %s"), quote (dst_name));
565 return_val = false;
566 goto close_src_desc;
568 if (x->verbose)
569 printf (_("removed %s\n"), quote (dst_name));
571 /* Tell caller that the destination file was unlinked. */
572 *new_dst = true;
576 if (*new_dst)
578 int open_flags = O_WRONLY | O_CREAT | O_BINARY;
579 dest_desc = open (dst_name, open_flags | O_EXCL,
580 dst_mode & ~omitted_permissions);
581 dest_errno = errno;
583 /* When trying to copy through a dangling destination symlink,
584 the above open fails with EEXIST. If that happens, and
585 lstat'ing the DST_NAME shows that it is a symlink, then we
586 have a problem: trying to resolve this dangling symlink to
587 a directory/destination-entry pair is fundamentally racy,
588 so punt. If POSIXLY_CORRECT is set, simply call open again,
589 but without O_EXCL (potentially dangerous). If not, fail
590 with a diagnostic. These shenanigans are necessary only
591 when copying, i.e., not in move_mode. */
592 if (dest_desc < 0 && dest_errno == EEXIST && ! x->move_mode)
594 struct stat dangling_link_sb;
595 if (lstat (dst_name, &dangling_link_sb) == 0
596 && S_ISLNK (dangling_link_sb.st_mode))
598 if (x->open_dangling_dest_symlink)
600 dest_desc = open (dst_name, open_flags,
601 dst_mode & ~omitted_permissions);
602 dest_errno = errno;
604 else
606 error (0, 0, _("not writing through dangling symlink %s"),
607 quote (dst_name));
608 return_val = false;
609 goto close_src_desc;
614 else
615 omitted_permissions = 0;
617 if (dest_desc < 0)
619 error (0, dest_errno, _("cannot create regular file %s"),
620 quote (dst_name));
621 return_val = false;
622 goto close_src_desc;
625 if (fstat (dest_desc, &sb) != 0)
627 error (0, errno, _("cannot fstat %s"), quote (dst_name));
628 return_val = false;
629 goto close_src_and_dst_desc;
632 if (x->reflink)
634 if (clone_file (dest_desc, source_desc))
636 error (0, errno, _("failed to clone %s"), quote (dst_name));
637 return_val = false;
639 goto close_src_and_dst_desc;
643 typedef uintptr_t word;
644 off_t n_read_total = 0;
646 /* Choose a suitable buffer size; it may be adjusted later. */
647 size_t buf_alignment = lcm (getpagesize (), sizeof (word));
648 size_t buf_alignment_slop = sizeof (word) + buf_alignment - 1;
649 size_t buf_size = io_blksize (sb);
651 /* Deal with sparse files. */
652 bool last_write_made_hole = false;
653 bool make_holes = false;
655 if (S_ISREG (sb.st_mode))
657 /* Even with --sparse=always, try to create holes only
658 if the destination is a regular file. */
659 if (x->sparse_mode == SPARSE_ALWAYS)
660 make_holes = true;
662 #if HAVE_STRUCT_STAT_ST_BLOCKS
663 /* Use a heuristic to determine whether SRC_NAME contains any sparse
664 blocks. If the file has fewer blocks than would normally be
665 needed for a file of its size, then at least one of the blocks in
666 the file is a hole. */
667 if (x->sparse_mode == SPARSE_AUTO && S_ISREG (src_open_sb.st_mode)
668 && ST_NBLOCKS (src_open_sb) < src_open_sb.st_size / ST_NBLOCKSIZE)
669 make_holes = true;
670 #endif
673 /* If not making a sparse file, try to use a more-efficient
674 buffer size. */
675 if (! make_holes)
677 /* Compute the least common multiple of the input and output
678 buffer sizes, adjusting for outlandish values. */
679 size_t blcm_max = MIN (SIZE_MAX, SSIZE_MAX) - buf_alignment_slop;
680 size_t blcm = buffer_lcm (io_blksize (src_open_sb), buf_size,
681 blcm_max);
683 /* Do not bother with a buffer larger than the input file, plus one
684 byte to make sure the file has not grown while reading it. */
685 if (S_ISREG (src_open_sb.st_mode) && src_open_sb.st_size < buf_size)
686 buf_size = src_open_sb.st_size + 1;
688 /* However, stick with a block size that is a positive multiple of
689 blcm, overriding the above adjustments. Watch out for
690 overflow. */
691 buf_size += blcm - 1;
692 buf_size -= buf_size % blcm;
693 if (buf_size == 0 || blcm_max < buf_size)
694 buf_size = blcm;
697 /* Make a buffer with space for a sentinel at the end. */
698 buf_alloc = xmalloc (buf_size + buf_alignment_slop);
699 buf = ptr_align (buf_alloc, buf_alignment);
701 for (;;)
703 word *wp = NULL;
705 ssize_t n_read = read (source_desc, buf, buf_size);
706 if (n_read < 0)
708 #ifdef EINTR
709 if (errno == EINTR)
710 continue;
711 #endif
712 error (0, errno, _("reading %s"), quote (src_name));
713 return_val = false;
714 goto close_src_and_dst_desc;
716 if (n_read == 0)
717 break;
719 n_read_total += n_read;
721 if (make_holes)
723 char *cp;
725 /* Sentinel to stop loop. */
726 buf[n_read] = '\1';
727 #ifdef lint
728 /* Usually, buf[n_read] is not the byte just before a "word"
729 (aka uintptr_t) boundary. In that case, the word-oriented
730 test below (*wp++ == 0) would read some uninitialized bytes
731 after the sentinel. To avoid false-positive reports about
732 this condition (e.g., from a tool like valgrind), set the
733 remaining bytes -- to any value. */
734 memset (buf + n_read + 1, 0, sizeof (word) - 1);
735 #endif
737 /* Find first nonzero *word*, or the word with the sentinel. */
739 wp = (word *) buf;
740 while (*wp++ == 0)
741 continue;
743 /* Find the first nonzero *byte*, or the sentinel. */
745 cp = (char *) (wp - 1);
746 while (*cp++ == 0)
747 continue;
749 if (cp <= buf + n_read)
750 /* Clear to indicate that a normal write is needed. */
751 wp = NULL;
752 else
754 /* We found the sentinel, so the whole input block was zero.
755 Make a hole. */
756 if (lseek (dest_desc, n_read, SEEK_CUR) < 0)
758 error (0, errno, _("cannot lseek %s"), quote (dst_name));
759 return_val = false;
760 goto close_src_and_dst_desc;
762 last_write_made_hole = true;
766 if (!wp)
768 size_t n = n_read;
769 if (full_write (dest_desc, buf, n) != n)
771 error (0, errno, _("writing %s"), quote (dst_name));
772 return_val = false;
773 goto close_src_and_dst_desc;
775 last_write_made_hole = false;
777 /* It is tempting to return early here upon a short read from a
778 regular file. That would save the final read syscall for each
779 file. Unfortunately that doesn't work for certain files in
780 /proc with linux kernels from at least 2.6.9 .. 2.6.29. */
784 /* If the file ends with a `hole', we need to do something to record
785 the length of the file. On modern systems, calling ftruncate does
786 the job. On systems without native ftruncate support, we have to
787 write a byte at the ending position. Otherwise the kernel would
788 truncate the file at the end of the last write operation. */
790 if (last_write_made_hole)
792 if (HAVE_FTRUNCATE
793 ? /* ftruncate sets the file size,
794 so there is no need for a write. */
795 ftruncate (dest_desc, n_read_total) < 0
796 : /* Seek backwards one character and write a null. */
797 (lseek (dest_desc, (off_t) -1, SEEK_CUR) < 0L
798 || full_write (dest_desc, "", 1) != 1))
800 error (0, errno, _("writing %s"), quote (dst_name));
801 return_val = false;
802 goto close_src_and_dst_desc;
807 if (x->preserve_timestamps)
809 struct timespec timespec[2];
810 timespec[0] = get_stat_atime (src_sb);
811 timespec[1] = get_stat_mtime (src_sb);
813 if (gl_futimens (dest_desc, dst_name, timespec) != 0)
815 error (0, errno, _("preserving times for %s"), quote (dst_name));
816 if (x->require_preserve)
818 return_val = false;
819 goto close_src_and_dst_desc;
824 if (x->preserve_ownership && ! SAME_OWNER_AND_GROUP (*src_sb, sb))
826 switch (set_owner (x, dst_name, dest_desc, src_sb, *new_dst, &sb))
828 case -1:
829 return_val = false;
830 goto close_src_and_dst_desc;
832 case 0:
833 src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX);
834 break;
838 set_author (dst_name, dest_desc, src_sb);
840 if (x->preserve_xattr && ! copy_attr_by_fd (src_name, source_desc,
841 dst_name, dest_desc, x)
842 && x->require_preserve_xattr)
843 return false;
845 if (x->preserve_mode || x->move_mode)
847 if (copy_acl (src_name, source_desc, dst_name, dest_desc, src_mode) != 0
848 && x->require_preserve)
849 return_val = false;
851 else if (x->set_mode)
853 if (set_acl (dst_name, dest_desc, x->mode) != 0)
854 return_val = false;
856 else if (omitted_permissions)
858 omitted_permissions &= ~ cached_umask ();
859 if (omitted_permissions
860 && fchmod_or_lchmod (dest_desc, dst_name, dst_mode) != 0)
862 error (0, errno, _("preserving permissions for %s"),
863 quote (dst_name));
864 if (x->require_preserve)
865 return_val = false;
869 close_src_and_dst_desc:
870 if (close (dest_desc) < 0)
872 error (0, errno, _("closing %s"), quote (dst_name));
873 return_val = false;
875 close_src_desc:
876 if (close (source_desc) < 0)
878 error (0, errno, _("closing %s"), quote (src_name));
879 return_val = false;
882 free (buf_alloc);
883 free (name_alloc);
884 return return_val;
887 /* Return true if it's ok that the source and destination
888 files are the `same' by some measure. The goal is to avoid
889 making the `copy' operation remove both copies of the file
890 in that case, while still allowing the user to e.g., move or
891 copy a regular file onto a symlink that points to it.
892 Try to minimize the cost of this function in the common case.
893 Set *RETURN_NOW if we've determined that the caller has no more
894 work to do and should return successfully, right away.
896 Set *UNLINK_SRC if we've determined that the caller wants to do
897 `rename (a, b)' where `a' and `b' are distinct hard links to the same
898 file. In that case, the caller should try to unlink `a' and then return
899 successfully. Ideally, we wouldn't have to do that, and we'd be
900 able to rely on rename to remove the source file. However, POSIX
901 mistakenly requires that such a rename call do *nothing* and return
902 successfully. */
904 static bool
905 same_file_ok (char const *src_name, struct stat const *src_sb,
906 char const *dst_name, struct stat const *dst_sb,
907 const struct cp_options *x, bool *return_now, bool *unlink_src)
909 const struct stat *src_sb_link;
910 const struct stat *dst_sb_link;
911 struct stat tmp_dst_sb;
912 struct stat tmp_src_sb;
914 bool same_link;
915 bool same = SAME_INODE (*src_sb, *dst_sb);
917 *return_now = false;
918 *unlink_src = false;
920 /* FIXME: this should (at the very least) be moved into the following
921 if-block. More likely, it should be removed, because it inhibits
922 making backups. But removing it will result in a change in behavior
923 that will probably have to be documented -- and tests will have to
924 be updated. */
925 if (same && x->hard_link)
927 *return_now = true;
928 return true;
931 if (x->dereference == DEREF_NEVER)
933 same_link = same;
935 /* If both the source and destination files are symlinks (and we'll
936 know this here IFF preserving symlinks), then it's ok -- as long
937 as they are distinct. */
938 if (S_ISLNK (src_sb->st_mode) && S_ISLNK (dst_sb->st_mode))
939 return ! same_name (src_name, dst_name);
941 src_sb_link = src_sb;
942 dst_sb_link = dst_sb;
944 else
946 if (!same)
947 return true;
949 if (lstat (dst_name, &tmp_dst_sb) != 0
950 || lstat (src_name, &tmp_src_sb) != 0)
951 return true;
953 src_sb_link = &tmp_src_sb;
954 dst_sb_link = &tmp_dst_sb;
956 same_link = SAME_INODE (*src_sb_link, *dst_sb_link);
958 /* If both are symlinks, then it's ok, but only if the destination
959 will be unlinked before being opened. This is like the test
960 above, but with the addition of the unlink_dest_before_opening
961 conjunct because otherwise, with two symlinks to the same target,
962 we'd end up truncating the source file. */
963 if (S_ISLNK (src_sb_link->st_mode) && S_ISLNK (dst_sb_link->st_mode)
964 && x->unlink_dest_before_opening)
965 return true;
968 /* The backup code ensures there's a copy, so it's usually ok to
969 remove any destination file. One exception is when both
970 source and destination are the same directory entry. In that
971 case, moving the destination file aside (in making the backup)
972 would also rename the source file and result in an error. */
973 if (x->backup_type != no_backups)
975 if (!same_link)
977 /* In copy mode when dereferencing symlinks, if the source is a
978 symlink and the dest is not, then backing up the destination
979 (moving it aside) would make it a dangling symlink, and the
980 subsequent attempt to open it in copy_reg would fail with
981 a misleading diagnostic. Avoid that by returning zero in
982 that case so the caller can make cp (or mv when it has to
983 resort to reading the source file) fail now. */
985 /* FIXME-note: even with the following kludge, we can still provoke
986 the offending diagnostic. It's just a little harder to do :-)
987 $ rm -f a b c; touch c; ln -s c b; ln -s b a; cp -b a b
988 cp: cannot open `a' for reading: No such file or directory
989 That's misleading, since a subsequent `ls' shows that `a'
990 is still there.
991 One solution would be to open the source file *before* moving
992 aside the destination, but that'd involve a big rewrite. */
993 if ( ! x->move_mode
994 && x->dereference != DEREF_NEVER
995 && S_ISLNK (src_sb_link->st_mode)
996 && ! S_ISLNK (dst_sb_link->st_mode))
997 return false;
999 return true;
1002 return ! same_name (src_name, dst_name);
1005 #if 0
1006 /* FIXME: use or remove */
1008 /* If we're making a backup, we'll detect the problem case in
1009 copy_reg because SRC_NAME will no longer exist. Allowing
1010 the test to be deferred lets cp do some useful things.
1011 But when creating hardlinks and SRC_NAME is a symlink
1012 but DST_NAME is not we must test anyway. */
1013 if (x->hard_link
1014 || !S_ISLNK (src_sb_link->st_mode)
1015 || S_ISLNK (dst_sb_link->st_mode))
1016 return true;
1018 if (x->dereference != DEREF_NEVER)
1019 return true;
1020 #endif
1022 /* They may refer to the same file if we're in move mode and the
1023 target is a symlink. That is ok, since we remove any existing
1024 destination file before opening it -- via `rename' if they're on
1025 the same file system, via `unlink (DST_NAME)' otherwise.
1026 It's also ok if they're distinct hard links to the same file. */
1027 if (x->move_mode || x->unlink_dest_before_opening)
1029 if (S_ISLNK (dst_sb_link->st_mode))
1030 return true;
1032 if (same_link
1033 && 1 < dst_sb_link->st_nlink
1034 && ! same_name (src_name, dst_name))
1036 if (x->move_mode)
1038 *unlink_src = true;
1039 *return_now = true;
1041 return true;
1045 /* If neither is a symlink, then it's ok as long as they aren't
1046 hard links to the same file. */
1047 if (!S_ISLNK (src_sb_link->st_mode) && !S_ISLNK (dst_sb_link->st_mode))
1049 if (!SAME_INODE (*src_sb_link, *dst_sb_link))
1050 return true;
1052 /* If they are the same file, it's ok if we're making hard links. */
1053 if (x->hard_link)
1055 *return_now = true;
1056 return true;
1060 /* It's ok to remove a destination symlink. But that works only when we
1061 unlink before opening the destination and when the source and destination
1062 files are on the same partition. */
1063 if (x->unlink_dest_before_opening
1064 && S_ISLNK (dst_sb_link->st_mode))
1065 return dst_sb_link->st_dev == src_sb_link->st_dev;
1067 if (x->dereference == DEREF_NEVER)
1069 if ( ! S_ISLNK (src_sb_link->st_mode))
1070 tmp_src_sb = *src_sb_link;
1071 else if (stat (src_name, &tmp_src_sb) != 0)
1072 return true;
1074 if ( ! S_ISLNK (dst_sb_link->st_mode))
1075 tmp_dst_sb = *dst_sb_link;
1076 else if (stat (dst_name, &tmp_dst_sb) != 0)
1077 return true;
1079 if ( ! SAME_INODE (tmp_src_sb, tmp_dst_sb))
1080 return true;
1082 /* FIXME: shouldn't this be testing whether we're making symlinks? */
1083 if (x->hard_link)
1085 *return_now = true;
1086 return true;
1090 return false;
1093 /* Return true if FILE, with mode MODE, is writable in the sense of 'mv'.
1094 Always consider a symbolic link to be writable. */
1095 static bool
1096 writable_destination (char const *file, mode_t mode)
1098 return (S_ISLNK (mode)
1099 || can_write_any_file ()
1100 || euidaccess (file, W_OK) == 0);
1103 static void
1104 overwrite_prompt (char const *dst_name, struct stat const *dst_sb)
1106 if (! writable_destination (dst_name, dst_sb->st_mode))
1108 char perms[12]; /* "-rwxrwxrwx " ls-style modes. */
1109 strmode (dst_sb->st_mode, perms);
1110 perms[10] = '\0';
1111 fprintf (stderr,
1112 _("%s: try to overwrite %s, overriding mode %04lo (%s)? "),
1113 program_name, quote (dst_name),
1114 (unsigned long int) (dst_sb->st_mode & CHMOD_MODE_BITS),
1115 &perms[1]);
1117 else
1119 fprintf (stderr, _("%s: overwrite %s? "),
1120 program_name, quote (dst_name));
1124 /* Initialize the hash table implementing a set of F_triple entries
1125 corresponding to destination files. */
1126 extern void
1127 dest_info_init (struct cp_options *x)
1129 x->dest_info
1130 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
1131 NULL,
1132 triple_hash,
1133 triple_compare,
1134 triple_free);
1137 /* Initialize the hash table implementing a set of F_triple entries
1138 corresponding to source files listed on the command line. */
1139 extern void
1140 src_info_init (struct cp_options *x)
1143 /* Note that we use triple_hash_no_name here.
1144 Contrast with the use of triple_hash above.
1145 That is necessary because a source file may be specified
1146 in many different ways. We want to warn about this
1147 cp a a d/
1148 as well as this:
1149 cp a ./a d/
1151 x->src_info
1152 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
1153 NULL,
1154 triple_hash_no_name,
1155 triple_compare,
1156 triple_free);
1159 /* When effecting a move (e.g., for mv(1)), and given the name DST_NAME
1160 of the destination and a corresponding stat buffer, DST_SB, return
1161 true if the logical `move' operation should _not_ proceed.
1162 Otherwise, return false.
1163 Depending on options specified in X, this code may issue an
1164 interactive prompt asking whether it's ok to overwrite DST_NAME. */
1165 static bool
1166 abandon_move (const struct cp_options *x,
1167 char const *dst_name,
1168 struct stat const *dst_sb)
1170 assert (x->move_mode);
1171 return (x->interactive == I_ALWAYS_NO
1172 || ((x->interactive == I_ASK_USER
1173 || (x->interactive == I_UNSPECIFIED
1174 && x->stdin_tty
1175 && ! writable_destination (dst_name, dst_sb->st_mode)))
1176 && (overwrite_prompt (dst_name, dst_sb), 1)
1177 && ! yesno ()));
1180 /* Print --verbose output on standard output, e.g. `new' -> `old'.
1181 If BACKUP_DST_NAME is non-NULL, then also indicate that it is
1182 the name of a backup file. */
1183 static void
1184 emit_verbose (char const *src, char const *dst, char const *backup_dst_name)
1186 printf ("%s -> %s", quote_n (0, src), quote_n (1, dst));
1187 if (backup_dst_name)
1188 printf (_(" (backup: %s)"), quote (backup_dst_name));
1189 putchar ('\n');
1192 /* A wrapper around "setfscreatecon (NULL)" that exits upon failure. */
1193 static void
1194 restore_default_fscreatecon_or_die (void)
1196 if (setfscreatecon (NULL) != 0)
1197 error (EXIT_FAILURE, errno,
1198 _("failed to restore the default file creation context"));
1201 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
1202 any type. NEW_DST should be true if the file DST_NAME cannot
1203 exist because its parent directory was just created; NEW_DST should
1204 be false if DST_NAME might already exist. DEVICE is the device
1205 number of the parent directory, or 0 if the parent of this file is
1206 not known. ANCESTORS points to a linked, null terminated list of
1207 devices and inodes of parent directories of SRC_NAME. COMMAND_LINE_ARG
1208 is true iff SRC_NAME was specified on the command line.
1209 FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG is both input and output.
1210 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
1211 same as) DST_NAME; otherwise, clear it.
1212 Return true if successful. */
1213 static bool
1214 copy_internal (char const *src_name, char const *dst_name,
1215 bool new_dst,
1216 dev_t device,
1217 struct dir_list *ancestors,
1218 const struct cp_options *x,
1219 bool command_line_arg,
1220 bool *first_dir_created_per_command_line_arg,
1221 bool *copy_into_self,
1222 bool *rename_succeeded)
1224 struct stat src_sb;
1225 struct stat dst_sb;
1226 mode_t src_mode;
1227 mode_t dst_mode IF_LINT (= 0);
1228 mode_t dst_mode_bits;
1229 mode_t omitted_permissions;
1230 bool restore_dst_mode = false;
1231 char *earlier_file = NULL;
1232 char *dst_backup = NULL;
1233 bool backup_succeeded = false;
1234 bool delayed_ok;
1235 bool copied_as_regular = false;
1236 bool dest_is_symlink = false;
1237 bool have_dst_lstat = false;
1239 if (x->move_mode && rename_succeeded)
1240 *rename_succeeded = false;
1242 *copy_into_self = false;
1244 if (XSTAT (x, src_name, &src_sb) != 0)
1246 error (0, errno, _("cannot stat %s"), quote (src_name));
1247 return false;
1250 src_mode = src_sb.st_mode;
1252 if (S_ISDIR (src_mode) && !x->recursive)
1254 error (0, 0, _("omitting directory %s"), quote (src_name));
1255 return false;
1258 /* Detect the case in which the same source file appears more than
1259 once on the command line and no backup option has been selected.
1260 If so, simply warn and don't copy it the second time.
1261 This check is enabled only if x->src_info is non-NULL. */
1262 if (command_line_arg)
1264 if ( ! S_ISDIR (src_sb.st_mode)
1265 && x->backup_type == no_backups
1266 && seen_file (x->src_info, src_name, &src_sb))
1268 error (0, 0, _("warning: source file %s specified more than once"),
1269 quote (src_name));
1270 return true;
1273 record_file (x->src_info, src_name, &src_sb);
1276 if (!new_dst)
1278 /* Regular files can be created by writing through symbolic
1279 links, but other files cannot. So use stat on the
1280 destination when copying a regular file, and lstat otherwise.
1281 However, if we intend to unlink or remove the destination
1282 first, use lstat, since a copy won't actually be made to the
1283 destination in that case. */
1284 bool use_stat =
1285 ((S_ISREG (src_mode)
1286 || (x->copy_as_regular
1287 && ! (S_ISDIR (src_mode) || S_ISLNK (src_mode))))
1288 && ! (x->move_mode || x->symbolic_link || x->hard_link
1289 || x->backup_type != no_backups
1290 || x->unlink_dest_before_opening));
1291 if ((use_stat
1292 ? stat (dst_name, &dst_sb)
1293 : lstat (dst_name, &dst_sb))
1294 != 0)
1296 if (errno != ENOENT)
1298 error (0, errno, _("cannot stat %s"), quote (dst_name));
1299 return false;
1301 else
1303 new_dst = true;
1306 else
1307 { /* Here, we know that dst_name exists, at least to the point
1308 that it is stat'able or lstat'able. */
1309 bool return_now;
1310 bool unlink_src;
1312 have_dst_lstat = !use_stat;
1313 if (! same_file_ok (src_name, &src_sb, dst_name, &dst_sb,
1314 x, &return_now, &unlink_src))
1316 error (0, 0, _("%s and %s are the same file"),
1317 quote_n (0, src_name), quote_n (1, dst_name));
1318 return false;
1321 if (!S_ISDIR (src_mode) && x->update)
1323 /* When preserving time stamps (but not moving within a file
1324 system), don't worry if the destination time stamp is
1325 less than the source merely because of time stamp
1326 truncation. */
1327 int options = ((x->preserve_timestamps
1328 && ! (x->move_mode
1329 && dst_sb.st_dev == src_sb.st_dev))
1330 ? UTIMECMP_TRUNCATE_SOURCE
1331 : 0);
1333 if (0 <= utimecmp (dst_name, &dst_sb, &src_sb, options))
1335 /* We're using --update and the destination is not older
1336 than the source, so do not copy or move. Pretend the
1337 rename succeeded, so the caller (if it's mv) doesn't
1338 end up removing the source file. */
1339 if (rename_succeeded)
1340 *rename_succeeded = true;
1341 return true;
1345 /* When there is an existing destination file, we may end up
1346 returning early, and hence not copying/moving the file.
1347 This may be due to an interactive `negative' reply to the
1348 prompt about the existing file. It may also be due to the
1349 use of the --reply=no option.
1351 cp and mv treat -i and -f differently. */
1352 if (x->move_mode)
1354 if (abandon_move (x, dst_name, &dst_sb)
1355 || (unlink_src && unlink (src_name) == 0))
1357 /* Pretend the rename succeeded, so the caller (mv)
1358 doesn't end up removing the source file. */
1359 if (rename_succeeded)
1360 *rename_succeeded = true;
1361 if (unlink_src && x->verbose)
1362 printf (_("removed %s\n"), quote (src_name));
1363 return true;
1365 if (unlink_src)
1367 error (0, errno, _("cannot remove %s"), quote (src_name));
1368 return false;
1371 else
1373 if (! S_ISDIR (src_mode)
1374 && (x->interactive == I_ALWAYS_NO
1375 || (x->interactive == I_ASK_USER
1376 && (overwrite_prompt (dst_name, &dst_sb), 1)
1377 && ! yesno ())))
1378 return true;
1381 if (return_now)
1382 return true;
1384 if (!S_ISDIR (dst_sb.st_mode))
1386 if (S_ISDIR (src_mode))
1388 if (x->move_mode && x->backup_type != no_backups)
1390 /* Moving a directory onto an existing
1391 non-directory is ok only with --backup. */
1393 else
1395 error (0, 0,
1396 _("cannot overwrite non-directory %s with directory %s"),
1397 quote_n (0, dst_name), quote_n (1, src_name));
1398 return false;
1402 /* Don't let the user destroy their data, even if they try hard:
1403 This mv command must fail (likewise for cp):
1404 rm -rf a b c; mkdir a b c; touch a/f b/f; mv a/f b/f c
1405 Otherwise, the contents of b/f would be lost.
1406 In the case of `cp', b/f would be lost if the user simulated
1407 a move using cp and rm.
1408 Note that it works fine if you use --backup=numbered. */
1409 if (command_line_arg
1410 && x->backup_type != numbered_backups
1411 && seen_file (x->dest_info, dst_name, &dst_sb))
1413 error (0, 0,
1414 _("will not overwrite just-created %s with %s"),
1415 quote_n (0, dst_name), quote_n (1, src_name));
1416 return false;
1420 if (!S_ISDIR (src_mode))
1422 if (S_ISDIR (dst_sb.st_mode))
1424 if (x->move_mode && x->backup_type != no_backups)
1426 /* Moving a non-directory onto an existing
1427 directory is ok only with --backup. */
1429 else
1431 error (0, 0,
1432 _("cannot overwrite directory %s with non-directory"),
1433 quote (dst_name));
1434 return false;
1439 if (x->move_mode)
1441 /* Don't allow user to move a directory onto a non-directory. */
1442 if (S_ISDIR (src_sb.st_mode) && !S_ISDIR (dst_sb.st_mode)
1443 && x->backup_type == no_backups)
1445 error (0, 0,
1446 _("cannot move directory onto non-directory: %s -> %s"),
1447 quote_n (0, src_name), quote_n (0, dst_name));
1448 return false;
1452 if (x->backup_type != no_backups
1453 /* Don't try to back up a destination if the last
1454 component of src_name is "." or "..". */
1455 && ! dot_or_dotdot (last_component (src_name))
1456 /* Create a backup of each destination directory in move mode,
1457 but not in copy mode. FIXME: it might make sense to add an
1458 option to suppress backup creation also for move mode.
1459 That would let one use mv to merge new content into an
1460 existing hierarchy. */
1461 && (x->move_mode || ! S_ISDIR (dst_sb.st_mode)))
1463 char *tmp_backup = find_backup_file_name (dst_name,
1464 x->backup_type);
1466 /* Detect (and fail) when creating the backup file would
1467 destroy the source file. Before, running the commands
1468 cd /tmp; rm -f a a~; : > a; echo A > a~; cp --b=simple a~ a
1469 would leave two zero-length files: a and a~. */
1470 /* FIXME: but simply change e.g., the final a~ to `./a~'
1471 and the source will still be destroyed. */
1472 if (STREQ (tmp_backup, src_name))
1474 const char *fmt;
1475 fmt = (x->move_mode
1476 ? _("backing up %s would destroy source; %s not moved")
1477 : _("backing up %s would destroy source; %s not copied"));
1478 error (0, 0, fmt,
1479 quote_n (0, dst_name),
1480 quote_n (1, src_name));
1481 free (tmp_backup);
1482 return false;
1485 /* FIXME: use fts:
1486 Using alloca for a file name that may be arbitrarily
1487 long is not recommended. In fact, even forming such a name
1488 should be discouraged. Eventually, this code will be rewritten
1489 to use fts, so using alloca here will be less of a problem. */
1490 ASSIGN_STRDUPA (dst_backup, tmp_backup);
1491 free (tmp_backup);
1492 if (rename (dst_name, dst_backup) != 0)
1494 if (errno != ENOENT)
1496 error (0, errno, _("cannot backup %s"), quote (dst_name));
1497 return false;
1499 else
1501 dst_backup = NULL;
1504 else
1506 backup_succeeded = true;
1508 new_dst = true;
1510 else if (! S_ISDIR (dst_sb.st_mode)
1511 /* Never unlink dst_name when in move mode. */
1512 && ! x->move_mode
1513 && (x->unlink_dest_before_opening
1514 || (x->preserve_links && 1 < dst_sb.st_nlink)
1515 || (x->dereference == DEREF_NEVER
1516 && ! S_ISREG (src_sb.st_mode))
1519 if (unlink (dst_name) != 0 && errno != ENOENT)
1521 error (0, errno, _("cannot remove %s"), quote (dst_name));
1522 return false;
1524 new_dst = true;
1525 if (x->verbose)
1526 printf (_("removed %s\n"), quote (dst_name));
1531 /* Ensure we don't try to copy through a symlink that was
1532 created by a prior call to this function. */
1533 if (command_line_arg
1534 && x->dest_info
1535 && ! x->move_mode
1536 && x->backup_type == no_backups)
1538 bool lstat_ok = true;
1539 struct stat tmp_buf;
1540 struct stat *dst_lstat_sb;
1542 /* If we called lstat above, good: use that data.
1543 Otherwise, call lstat here, in case dst_name is a symlink. */
1544 if (have_dst_lstat)
1545 dst_lstat_sb = &dst_sb;
1546 else
1548 if (lstat (dst_name, &tmp_buf) == 0)
1549 dst_lstat_sb = &tmp_buf;
1550 else
1551 lstat_ok = false;
1554 /* Never copy through a symlink we've just created. */
1555 if (lstat_ok
1556 && S_ISLNK (dst_lstat_sb->st_mode)
1557 && seen_file (x->dest_info, dst_name, dst_lstat_sb))
1559 error (0, 0,
1560 _("will not copy %s through just-created symlink %s"),
1561 quote_n (0, src_name), quote_n (1, dst_name));
1562 return false;
1566 /* If the source is a directory, we don't always create the destination
1567 directory. So --verbose should not announce anything until we're
1568 sure we'll create a directory. */
1569 if (x->verbose && !S_ISDIR (src_mode))
1570 emit_verbose (src_name, dst_name, backup_succeeded ? dst_backup : NULL);
1572 /* Associate the destination file name with the source device and inode
1573 so that if we encounter a matching dev/ino pair in the source tree
1574 we can arrange to create a hard link between the corresponding names
1575 in the destination tree.
1577 When using the --link (-l) option, there is no need to take special
1578 measures, because (barring race conditions) files that are hard-linked
1579 in the source tree will also be hard-linked in the destination tree.
1581 Sometimes, when preserving links, we have to record dev/ino even
1582 though st_nlink == 1:
1583 - when in move_mode, since we may be moving a group of N hard-linked
1584 files (via two or more command line arguments) to a different
1585 partition; the links may be distributed among the command line
1586 arguments (possibly hierarchies) so that the link count of
1587 the final, once-linked source file is reduced to 1 when it is
1588 considered below. But in this case (for mv) we don't need to
1589 incur the expense of recording the dev/ino => name mapping; all we
1590 really need is a lookup, to see if the dev/ino pair has already
1591 been copied.
1592 - when using -H and processing a command line argument;
1593 that command line argument could be a symlink pointing to another
1594 command line argument. With `cp -H --preserve=link', we hard-link
1595 those two destination files.
1596 - likewise for -L except that it applies to all files, not just
1597 command line arguments.
1599 Also, with --recursive, record dev/ino of each command-line directory.
1600 We'll use that info to detect this problem: cp -R dir dir. */
1602 if (x->move_mode && src_sb.st_nlink == 1)
1604 earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev);
1606 else if (x->preserve_links
1607 && !x->hard_link
1608 && (1 < src_sb.st_nlink
1609 || (command_line_arg
1610 && x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
1611 || x->dereference == DEREF_ALWAYS))
1613 earlier_file = remember_copied (dst_name, src_sb.st_ino, src_sb.st_dev);
1615 else if (x->recursive && S_ISDIR (src_mode))
1617 if (command_line_arg)
1618 earlier_file = remember_copied (dst_name, src_sb.st_ino, src_sb.st_dev);
1619 else
1620 earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev);
1623 /* Did we copy this inode somewhere else (in this command line argument)
1624 and therefore this is a second hard link to the inode? */
1626 if (earlier_file)
1628 /* Avoid damaging the destination file system by refusing to preserve
1629 hard-linked directories (which are found at least in Netapp snapshot
1630 directories). */
1631 if (S_ISDIR (src_mode))
1633 /* If src_name and earlier_file refer to the same directory entry,
1634 then warn about copying a directory into itself. */
1635 if (same_name (src_name, earlier_file))
1637 error (0, 0, _("cannot copy a directory, %s, into itself, %s"),
1638 quote_n (0, top_level_src_name),
1639 quote_n (1, top_level_dst_name));
1640 *copy_into_self = true;
1641 goto un_backup;
1643 else if (x->dereference == DEREF_ALWAYS)
1645 /* This happens when e.g., encountering a directory for the
1646 second or subsequent time via symlinks when cp is invoked
1647 with -R and -L. E.g.,
1648 rm -rf a b c d; mkdir a b c d; ln -s ../c a; ln -s ../c b;
1649 cp -RL a b d
1652 else
1654 error (0, 0, _("will not create hard link %s to directory %s"),
1655 quote_n (0, dst_name), quote_n (1, earlier_file));
1656 goto un_backup;
1659 else
1661 bool link_failed = (link (earlier_file, dst_name) != 0);
1663 /* If the link failed because of an existing destination,
1664 remove that file and then call link again. */
1665 if (link_failed && errno == EEXIST)
1667 if (unlink (dst_name) != 0)
1669 error (0, errno, _("cannot remove %s"), quote (dst_name));
1670 goto un_backup;
1672 if (x->verbose)
1673 printf (_("removed %s\n"), quote (dst_name));
1674 link_failed = (link (earlier_file, dst_name) != 0);
1677 if (link_failed)
1679 error (0, errno, _("cannot create hard link %s to %s"),
1680 quote_n (0, dst_name), quote_n (1, earlier_file));
1681 goto un_backup;
1684 return true;
1688 if (x->move_mode)
1690 if (rename (src_name, dst_name) == 0)
1692 if (x->verbose && S_ISDIR (src_mode))
1693 emit_verbose (src_name, dst_name,
1694 backup_succeeded ? dst_backup : NULL);
1696 if (rename_succeeded)
1697 *rename_succeeded = true;
1699 if (command_line_arg)
1701 /* Record destination dev/ino/name, so that if we are asked
1702 to overwrite that file again, we can detect it and fail. */
1703 /* It's fine to use the _source_ stat buffer (src_sb) to get the
1704 _destination_ dev/ino, since the rename above can't have
1705 changed those, and `mv' always uses lstat.
1706 We could limit it further by operating
1707 only on non-directories. */
1708 record_file (x->dest_info, dst_name, &src_sb);
1711 return true;
1714 /* FIXME: someday, consider what to do when moving a directory into
1715 itself but when source and destination are on different devices. */
1717 /* This happens when attempting to rename a directory to a
1718 subdirectory of itself. */
1719 if (errno == EINVAL)
1721 /* FIXME: this is a little fragile in that it relies on rename(2)
1722 failing with a specific errno value. Expect problems on
1723 non-POSIX systems. */
1724 error (0, 0, _("cannot move %s to a subdirectory of itself, %s"),
1725 quote_n (0, top_level_src_name),
1726 quote_n (1, top_level_dst_name));
1728 /* Note that there is no need to call forget_created here,
1729 (compare with the other calls in this file) since the
1730 destination directory didn't exist before. */
1732 *copy_into_self = true;
1733 /* FIXME-cleanup: Don't return true here; adjust mv.c accordingly.
1734 The only caller that uses this code (mv.c) ends up setting its
1735 exit status to nonzero when copy_into_self is nonzero. */
1736 return true;
1739 /* WARNING: there probably exist systems for which an inter-device
1740 rename fails with a value of errno not handled here.
1741 If/as those are reported, add them to the condition below.
1742 If this happens to you, please do the following and send the output
1743 to the bug-reporting address (e.g., in the output of cp --help):
1744 touch k; perl -e 'rename "k","/tmp/k" or print "$!(",$!+0,")\n"'
1745 where your current directory is on one partion and /tmp is the other.
1746 Also, please try to find the E* errno macro name corresponding to
1747 the diagnostic and parenthesized integer, and include that in your
1748 e-mail. One way to do that is to run a command like this
1749 find /usr/include/. -type f \
1750 | xargs grep 'define.*\<E[A-Z]*\>.*\<18\>' /dev/null
1751 where you'd replace `18' with the integer in parentheses that
1752 was output from the perl one-liner above.
1753 If necessary, of course, change `/tmp' to some other directory. */
1754 if (errno != EXDEV)
1756 /* There are many ways this can happen due to a race condition.
1757 When something happens between the initial XSTAT and the
1758 subsequent rename, we can get many different types of errors.
1759 For example, if the destination is initially a non-directory
1760 or non-existent, but it is created as a directory, the rename
1761 fails. If two `mv' commands try to rename the same file at
1762 about the same time, one will succeed and the other will fail.
1763 If the permissions on the directory containing the source or
1764 destination file are made too restrictive, the rename will
1765 fail. Etc. */
1766 error (0, errno,
1767 _("cannot move %s to %s"),
1768 quote_n (0, src_name), quote_n (1, dst_name));
1769 forget_created (src_sb.st_ino, src_sb.st_dev);
1770 return false;
1773 /* The rename attempt has failed. Remove any existing destination
1774 file so that a cross-device `mv' acts as if it were really using
1775 the rename syscall. */
1776 if (unlink (dst_name) != 0 && errno != ENOENT)
1778 error (0, errno,
1779 _("inter-device move failed: %s to %s; unable to remove target"),
1780 quote_n (0, src_name), quote_n (1, dst_name));
1781 forget_created (src_sb.st_ino, src_sb.st_dev);
1782 return false;
1785 new_dst = true;
1788 /* If the ownership might change, or if it is a directory (whose
1789 special mode bits may change after the directory is created),
1790 omit some permissions at first, so unauthorized users cannot nip
1791 in before the file is ready. */
1792 dst_mode_bits = (x->set_mode ? x->mode : src_mode) & CHMOD_MODE_BITS;
1793 omitted_permissions =
1794 (dst_mode_bits
1795 & (x->preserve_ownership ? S_IRWXG | S_IRWXO
1796 : S_ISDIR (src_mode) ? S_IWGRP | S_IWOTH
1797 : 0));
1799 delayed_ok = true;
1801 if (x->preserve_security_context)
1803 security_context_t con;
1805 if (0 <= lgetfilecon (src_name, &con))
1807 if (setfscreatecon (con) < 0)
1809 if (!x->reduce_diagnostics || x->require_preserve_context)
1810 error (0, errno,
1811 _("failed to set default file creation context to %s"),
1812 quote (con));
1813 if (x->require_preserve_context)
1815 freecon (con);
1816 return false;
1819 freecon (con);
1821 else
1823 if (!errno_unsupported (errno) || x->require_preserve_context)
1825 if (!x->reduce_diagnostics || x->require_preserve_context)
1826 error (0, errno,
1827 _("failed to get security context of %s"),
1828 quote (src_name));
1829 if (x->require_preserve_context)
1830 return false;
1835 if (S_ISDIR (src_mode))
1837 struct dir_list *dir;
1839 /* If this directory has been copied before during the
1840 recursion, there is a symbolic link to an ancestor
1841 directory of the symbolic link. It is impossible to
1842 continue to copy this, unless we've got an infinite disk. */
1844 if (is_ancestor (&src_sb, ancestors))
1846 error (0, 0, _("cannot copy cyclic symbolic link %s"),
1847 quote (src_name));
1848 goto un_backup;
1851 /* Insert the current directory in the list of parents. */
1853 dir = alloca (sizeof *dir);
1854 dir->parent = ancestors;
1855 dir->ino = src_sb.st_ino;
1856 dir->dev = src_sb.st_dev;
1858 if (new_dst || !S_ISDIR (dst_sb.st_mode))
1860 /* POSIX says mkdir's behavior is implementation-defined when
1861 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
1862 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
1863 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
1864 if (mkdir (dst_name, dst_mode_bits & ~omitted_permissions) != 0)
1866 error (0, errno, _("cannot create directory %s"),
1867 quote (dst_name));
1868 goto un_backup;
1871 /* We need search and write permissions to the new directory
1872 for writing the directory's contents. Check if these
1873 permissions are there. */
1875 if (lstat (dst_name, &dst_sb) != 0)
1877 error (0, errno, _("cannot stat %s"), quote (dst_name));
1878 goto un_backup;
1880 else if ((dst_sb.st_mode & S_IRWXU) != S_IRWXU)
1882 /* Make the new directory searchable and writable. */
1884 dst_mode = dst_sb.st_mode;
1885 restore_dst_mode = true;
1887 if (lchmod (dst_name, dst_mode | S_IRWXU) != 0)
1889 error (0, errno, _("setting permissions for %s"),
1890 quote (dst_name));
1891 goto un_backup;
1895 /* Record the created directory's inode and device numbers into
1896 the search structure, so that we can avoid copying it again.
1897 Do this only for the first directory that is created for each
1898 source command line argument. */
1899 if (!*first_dir_created_per_command_line_arg)
1901 remember_copied (dst_name, dst_sb.st_ino, dst_sb.st_dev);
1902 *first_dir_created_per_command_line_arg = true;
1905 if (x->verbose)
1906 emit_verbose (src_name, dst_name, NULL);
1909 /* Decide whether to copy the contents of the directory. */
1910 if (x->one_file_system && device != 0 && device != src_sb.st_dev)
1912 /* Here, we are crossing a file system boundary and cp's -x option
1913 is in effect: so don't copy the contents of this directory. */
1915 else
1917 /* Copy the contents of the directory. Don't just return if
1918 this fails -- otherwise, the failure to read a single file
1919 in a source directory would cause the containing destination
1920 directory not to have owner/perms set properly. */
1921 delayed_ok = copy_dir (src_name, dst_name, new_dst, &src_sb, dir, x,
1922 first_dir_created_per_command_line_arg,
1923 copy_into_self);
1926 else if (x->symbolic_link)
1928 dest_is_symlink = true;
1929 if (*src_name != '/')
1931 /* Check that DST_NAME denotes a file in the current directory. */
1932 struct stat dot_sb;
1933 struct stat dst_parent_sb;
1934 char *dst_parent;
1935 bool in_current_dir;
1937 dst_parent = dir_name (dst_name);
1939 in_current_dir = (STREQ (".", dst_parent)
1940 /* If either stat call fails, it's ok not to report
1941 the failure and say dst_name is in the current
1942 directory. Other things will fail later. */
1943 || stat (".", &dot_sb) != 0
1944 || stat (dst_parent, &dst_parent_sb) != 0
1945 || SAME_INODE (dot_sb, dst_parent_sb));
1946 free (dst_parent);
1948 if (! in_current_dir)
1950 error (0, 0,
1951 _("%s: can make relative symbolic links only in current directory"),
1952 quote (dst_name));
1953 goto un_backup;
1956 if (symlink (src_name, dst_name) != 0)
1958 error (0, errno, _("cannot create symbolic link %s to %s"),
1959 quote_n (0, dst_name), quote_n (1, src_name));
1960 goto un_backup;
1964 else if (x->hard_link
1965 #ifdef LINK_FOLLOWS_SYMLINKS
1966 /* A POSIX-conforming link syscall dereferences a symlink, yet cp,
1967 invoked with `--link --no-dereference', should not. Thus, with
1968 a POSIX-conforming link system call, we can't use link() here,
1969 since that would create a hard link to the referent (effectively
1970 dereferencing the symlink), rather than to the symlink itself.
1971 We can approximate the desired behavior by skipping this hard-link
1972 creating block and instead copying the symlink, via the `S_ISLNK'-
1973 copying code below.
1974 When link operates on the symlinks themselves, we use this block
1975 and just call link(). */
1976 && !(S_ISLNK (src_mode) && x->dereference == DEREF_NEVER)
1977 #endif
1980 if (link (src_name, dst_name))
1982 error (0, errno, _("cannot create link %s"), quote (dst_name));
1983 goto un_backup;
1986 else if (S_ISREG (src_mode)
1987 || (x->copy_as_regular && !S_ISLNK (src_mode)))
1989 copied_as_regular = true;
1990 /* POSIX says the permission bits of the source file must be
1991 used as the 3rd argument in the open call. Historical
1992 practice passed all the source mode bits to 'open', but the extra
1993 bits were ignored, so it should be the same either way. */
1994 if (! copy_reg (src_name, dst_name, x, src_mode & S_IRWXUGO,
1995 omitted_permissions, &new_dst, &src_sb))
1996 goto un_backup;
1998 else if (S_ISFIFO (src_mode))
2000 /* Use mknod, rather than mkfifo, because the former preserves
2001 the special mode bits of a fifo on Solaris 10, while mkfifo
2002 does not. But fall back on mkfifo, because on some BSD systems,
2003 mknod always fails when asked to create a FIFO. */
2004 if (mknod (dst_name, src_mode & ~omitted_permissions, 0) != 0)
2005 if (mkfifo (dst_name, src_mode & ~S_IFIFO & ~omitted_permissions) != 0)
2007 error (0, errno, _("cannot create fifo %s"), quote (dst_name));
2008 goto un_backup;
2011 else if (S_ISBLK (src_mode) || S_ISCHR (src_mode) || S_ISSOCK (src_mode))
2013 if (mknod (dst_name, src_mode & ~omitted_permissions, src_sb.st_rdev)
2014 != 0)
2016 error (0, errno, _("cannot create special file %s"),
2017 quote (dst_name));
2018 goto un_backup;
2021 else if (S_ISLNK (src_mode))
2023 char *src_link_val = areadlink_with_size (src_name, src_sb.st_size);
2024 dest_is_symlink = true;
2025 if (src_link_val == NULL)
2027 error (0, errno, _("cannot read symbolic link %s"), quote (src_name));
2028 goto un_backup;
2031 if (symlink (src_link_val, dst_name) == 0)
2032 free (src_link_val);
2033 else
2035 int saved_errno = errno;
2036 bool same_link = false;
2037 if (x->update && !new_dst && S_ISLNK (dst_sb.st_mode)
2038 && dst_sb.st_size == strlen (src_link_val))
2040 /* See if the destination is already the desired symlink.
2041 FIXME: This behavior isn't documented, and seems wrong
2042 in some cases, e.g., if the destination symlink has the
2043 wrong ownership, permissions, or time stamps. */
2044 char *dest_link_val =
2045 areadlink_with_size (dst_name, dst_sb.st_size);
2046 if (dest_link_val && STREQ (dest_link_val, src_link_val))
2047 same_link = true;
2048 free (dest_link_val);
2050 free (src_link_val);
2052 if (! same_link)
2054 error (0, saved_errno, _("cannot create symbolic link %s"),
2055 quote (dst_name));
2056 goto un_backup;
2060 if (x->preserve_security_context)
2061 restore_default_fscreatecon_or_die ();
2063 if (x->preserve_ownership)
2065 /* Preserve the owner and group of the just-`copied'
2066 symbolic link, if possible. */
2067 if (HAVE_LCHOWN
2068 && lchown (dst_name, src_sb.st_uid, src_sb.st_gid) != 0
2069 && ! chown_failure_ok (x))
2071 error (0, errno, _("failed to preserve ownership for %s"),
2072 dst_name);
2073 goto un_backup;
2075 else
2077 /* Can't preserve ownership of symlinks.
2078 FIXME: maybe give a warning or even error for symlinks
2079 in directories with the sticky bit set -- there, not
2080 preserving owner/group is a potential security problem. */
2084 else
2086 error (0, 0, _("%s has unknown file type"), quote (src_name));
2087 goto un_backup;
2090 if (command_line_arg && x->dest_info)
2092 /* Now that the destination file is very likely to exist,
2093 add its info to the set. */
2094 struct stat sb;
2095 if (lstat (dst_name, &sb) == 0)
2096 record_file (x->dest_info, dst_name, &sb);
2099 /* If we've just created a hard-link due to cp's --link option,
2100 we're done. */
2101 if (x->hard_link && ! S_ISDIR (src_mode))
2102 return delayed_ok;
2104 if (copied_as_regular)
2105 return delayed_ok;
2107 /* POSIX says that `cp -p' must restore the following:
2108 - permission bits
2109 - setuid, setgid bits
2110 - owner and group
2111 If it fails to restore any of those, we may give a warning but
2112 the destination must not be removed.
2113 FIXME: implement the above. */
2115 /* Adjust the times (and if possible, ownership) for the copy.
2116 chown turns off set[ug]id bits for non-root,
2117 so do the chmod last. */
2119 if (x->preserve_timestamps)
2121 struct timespec timespec[2];
2122 timespec[0] = get_stat_atime (&src_sb);
2123 timespec[1] = get_stat_mtime (&src_sb);
2125 if ((dest_is_symlink
2126 ? utimens_symlink (dst_name, timespec)
2127 : utimens (dst_name, timespec))
2128 != 0)
2130 error (0, errno, _("preserving times for %s"), quote (dst_name));
2131 if (x->require_preserve)
2132 return false;
2136 /* The operations beyond this point may dereference a symlink. */
2137 if (dest_is_symlink)
2138 return delayed_ok;
2140 /* Avoid calling chown if we know it's not necessary. */
2141 if (x->preserve_ownership
2142 && (new_dst || !SAME_OWNER_AND_GROUP (src_sb, dst_sb)))
2144 switch (set_owner (x, dst_name, -1, &src_sb, new_dst, &dst_sb))
2146 case -1:
2147 return false;
2149 case 0:
2150 src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX);
2151 break;
2155 set_author (dst_name, -1, &src_sb);
2157 if (x->preserve_xattr && ! copy_attr_by_name (src_name, dst_name, x)
2158 && x->require_preserve_xattr)
2159 return false;
2161 if (x->preserve_mode || x->move_mode)
2163 if (copy_acl (src_name, -1, dst_name, -1, src_mode) != 0
2164 && x->require_preserve)
2165 return false;
2167 else if (x->set_mode)
2169 if (set_acl (dst_name, -1, x->mode) != 0)
2170 return false;
2172 else
2174 if (omitted_permissions)
2176 omitted_permissions &= ~ cached_umask ();
2178 if (omitted_permissions && !restore_dst_mode)
2180 /* Permissions were deliberately omitted when the file
2181 was created due to security concerns. See whether
2182 they need to be re-added now. It'd be faster to omit
2183 the lstat, but deducing the current destination mode
2184 is tricky in the presence of implementation-defined
2185 rules for special mode bits. */
2186 if (new_dst && lstat (dst_name, &dst_sb) != 0)
2188 error (0, errno, _("cannot stat %s"), quote (dst_name));
2189 return false;
2191 dst_mode = dst_sb.st_mode;
2192 if (omitted_permissions & ~dst_mode)
2193 restore_dst_mode = true;
2197 if (restore_dst_mode)
2199 if (lchmod (dst_name, dst_mode | omitted_permissions) != 0)
2201 error (0, errno, _("preserving permissions for %s"),
2202 quote (dst_name));
2203 if (x->require_preserve)
2204 return false;
2209 return delayed_ok;
2211 un_backup:
2213 if (x->preserve_security_context)
2214 restore_default_fscreatecon_or_die ();
2216 /* We have failed to create the destination file.
2217 If we've just added a dev/ino entry via the remember_copied
2218 call above (i.e., unless we've just failed to create a hard link),
2219 remove the entry associating the source dev/ino with the
2220 destination file name, so we don't try to `preserve' a link
2221 to a file we didn't create. */
2222 if (earlier_file == NULL)
2223 forget_created (src_sb.st_ino, src_sb.st_dev);
2225 if (dst_backup)
2227 if (rename (dst_backup, dst_name) != 0)
2228 error (0, errno, _("cannot un-backup %s"), quote (dst_name));
2229 else
2231 if (x->verbose)
2232 printf (_("%s -> %s (unbackup)\n"),
2233 quote_n (0, dst_backup), quote_n (1, dst_name));
2236 return false;
2239 static bool
2240 valid_options (const struct cp_options *co)
2242 assert (co != NULL);
2243 assert (VALID_BACKUP_TYPE (co->backup_type));
2244 assert (VALID_SPARSE_MODE (co->sparse_mode));
2245 assert (!(co->hard_link && co->symbolic_link));
2246 assert (!(co->reflink && co->sparse_mode != SPARSE_AUTO));
2247 return true;
2250 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
2251 any type. NONEXISTENT_DST should be true if the file DST_NAME
2252 is known not to exist (e.g., because its parent directory was just
2253 created); NONEXISTENT_DST should be false if DST_NAME might already
2254 exist. OPTIONS is ... FIXME-describe
2255 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
2256 same as) DST_NAME; otherwise, set clear it.
2257 Return true if successful. */
2259 extern bool
2260 copy (char const *src_name, char const *dst_name,
2261 bool nonexistent_dst, const struct cp_options *options,
2262 bool *copy_into_self, bool *rename_succeeded)
2264 assert (valid_options (options));
2266 /* Record the file names: they're used in case of error, when copying
2267 a directory into itself. I don't like to make these tools do *any*
2268 extra work in the common case when that work is solely to handle
2269 exceptional cases, but in this case, I don't see a way to derive the
2270 top level source and destination directory names where they're used.
2271 An alternative is to use COPY_INTO_SELF and print the diagnostic
2272 from every caller -- but I don't want to do that. */
2273 top_level_src_name = src_name;
2274 top_level_dst_name = dst_name;
2276 bool first_dir_created_per_command_line_arg = false;
2277 return copy_internal (src_name, dst_name, nonexistent_dst, 0, NULL,
2278 options, true,
2279 &first_dir_created_per_command_line_arg,
2280 copy_into_self, rename_succeeded);
2283 /* Set *X to the default options for a value of type struct cp_options. */
2285 extern void
2286 cp_options_default (struct cp_options *x)
2288 memset (x, 0, sizeof *x);
2289 #ifdef PRIV_FILE_CHOWN
2291 priv_set_t *pset = priv_allocset ();
2292 if (!pset)
2293 xalloc_die ();
2294 if (getppriv (PRIV_EFFECTIVE, pset) == 0)
2296 x->chown_privileges = priv_ismember (pset, PRIV_FILE_CHOWN);
2297 x->owner_privileges = priv_ismember (pset, PRIV_FILE_OWNER);
2299 priv_freeset (pset);
2301 #else
2302 x->chown_privileges = x->owner_privileges = (geteuid () == 0);
2303 #endif
2306 /* Return true if it's OK for chown to fail, where errno is
2307 the error number that chown failed with and X is the copying
2308 option set. */
2310 extern bool
2311 chown_failure_ok (struct cp_options const *x)
2313 /* If non-root uses -p, it's ok if we can't preserve ownership.
2314 But root probably wants to know, e.g. if NFS disallows it,
2315 or if the target system doesn't support file ownership. */
2317 return ((errno == EPERM || errno == EINVAL) && !x->chown_privileges);
2320 /* Similarly, return true if it's OK for chmod and similar operations
2321 to fail, where errno is the error number that chmod failed with and
2322 X is the copying option set. */
2324 static bool
2325 owner_failure_ok (struct cp_options const *x)
2327 return ((errno == EPERM || errno == EINVAL) && !x->owner_privileges);
2330 /* Return the user's umask, caching the result. */
2332 extern mode_t
2333 cached_umask (void)
2335 static mode_t mask = (mode_t) -1;
2336 if (mask == (mode_t) -1)
2338 mask = umask (0);
2339 umask (mask);
2341 return mask;