cp -up: preserve all hard links
[coreutils/ericb.git] / src / copy.c
blobdf8b1db749944c7ee6c4046e82078374e76bb567
1 /* copy.c -- core functions for copying files and directories
2 Copyright (C) 1989-1991, 1995-2011 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 /* Extracted from cp.c and librarified by Jim Meyering. */
19 #include <config.h>
20 #include <stdio.h>
21 #include <assert.h>
22 #include <sys/ioctl.h>
23 #include <sys/types.h>
24 #include <selinux/selinux.h>
26 #if HAVE_HURD_H
27 # include <hurd.h>
28 #endif
29 #if HAVE_PRIV_H
30 # include <priv.h>
31 #endif
33 #include "system.h"
34 #include "acl.h"
35 #include "backupfile.h"
36 #include "buffer-lcm.h"
37 #include "copy.h"
38 #include "cp-hash.h"
39 #include "extent-scan.h"
40 #include "error.h"
41 #include "fcntl--.h"
42 #include "fiemap.h"
43 #include "file-set.h"
44 #include "filemode.h"
45 #include "filenamecat.h"
46 #include "full-write.h"
47 #include "hash.h"
48 #include "hash-triple.h"
49 #include "ignore-value.h"
50 #include "ioblksize.h"
51 #include "quote.h"
52 #include "same.h"
53 #include "savedir.h"
54 #include "stat-size.h"
55 #include "stat-time.h"
56 #include "utimecmp.h"
57 #include "utimens.h"
58 #include "write-any-file.h"
59 #include "areadlink.h"
60 #include "yesno.h"
62 #if USE_XATTR
63 # include <attr/error_context.h>
64 # include <attr/libattr.h>
65 # include <stdarg.h>
66 # include "verror.h"
67 #endif
69 #ifndef HAVE_FCHOWN
70 # define HAVE_FCHOWN false
71 # define fchown(fd, uid, gid) (-1)
72 #endif
74 #ifndef HAVE_LCHOWN
75 # define HAVE_LCHOWN false
76 # define lchown(name, uid, gid) chown (name, uid, gid)
77 #endif
79 #ifndef HAVE_MKFIFO
80 static int
81 rpl_mkfifo (char const *file, mode_t mode)
83 errno = ENOTSUP;
84 return -1;
86 # define mkfifo rpl_mkfifo
87 #endif
89 #ifndef USE_ACL
90 # define USE_ACL 0
91 #endif
93 #define SAME_OWNER(A, B) ((A).st_uid == (B).st_uid)
94 #define SAME_GROUP(A, B) ((A).st_gid == (B).st_gid)
95 #define SAME_OWNER_AND_GROUP(A, B) (SAME_OWNER (A, B) && SAME_GROUP (A, B))
97 struct dir_list
99 struct dir_list *parent;
100 ino_t ino;
101 dev_t dev;
104 /* Initial size of the cp.dest_info hash table. */
105 #define DEST_INFO_INITIAL_CAPACITY 61
107 static bool copy_internal (char const *src_name, char const *dst_name,
108 bool new_dst, dev_t device,
109 struct dir_list *ancestors,
110 const struct cp_options *x,
111 bool command_line_arg,
112 bool *first_dir_created_per_command_line_arg,
113 bool *copy_into_self,
114 bool *rename_succeeded);
115 static bool owner_failure_ok (struct cp_options const *x);
117 /* Pointers to the file names: they're used in the diagnostic that is issued
118 when we detect the user is trying to copy a directory into itself. */
119 static char const *top_level_src_name;
120 static char const *top_level_dst_name;
122 /* Set the timestamp of symlink, FILE, to TIMESPEC.
123 If this system lacks support for that, simply return 0. */
124 static inline int
125 utimens_symlink (char const *file, struct timespec const *timespec)
127 int err = lutimens (file, timespec);
128 /* When configuring on a system with new headers and libraries, and
129 running on one with a kernel that is old enough to lack the syscall,
130 utimensat fails with ENOSYS. Ignore that. */
131 if (err && errno == ENOSYS)
132 err = 0;
133 return err;
136 /* Copy the regular file open on SRC_FD/SRC_NAME to DST_FD/DST_NAME,
137 honoring the MAKE_HOLES setting and using the BUF_SIZE-byte buffer
138 BUF for temporary storage. Copy no more than MAX_N_READ bytes.
139 Return true upon successful completion;
140 print a diagnostic and return false upon error.
141 Note that for best results, BUF should be "well"-aligned.
142 BUF must have sizeof(uintptr_t)-1 bytes of additional space
143 beyond BUF[BUF_SIZE-1].
144 Set *LAST_WRITE_MADE_HOLE to true if the final operation on
145 DEST_FD introduced a hole. Set *TOTAL_N_READ to the number of
146 bytes read. */
147 static bool
148 sparse_copy (int src_fd, int dest_fd, char *buf, size_t buf_size,
149 bool make_holes,
150 char const *src_name, char const *dst_name,
151 uintmax_t max_n_read, off_t *total_n_read,
152 bool *last_write_made_hole)
154 typedef uintptr_t word;
155 *last_write_made_hole = false;
156 *total_n_read = 0;
158 while (max_n_read)
160 word *wp = NULL;
162 ssize_t n_read = read (src_fd, buf, MIN (max_n_read, buf_size));
163 if (n_read < 0)
165 if (errno == EINTR)
166 continue;
167 error (0, errno, _("reading %s"), quote (src_name));
168 return false;
170 if (n_read == 0)
171 break;
172 max_n_read -= n_read;
173 *total_n_read += n_read;
175 if (make_holes)
177 char *cp;
179 /* Sentinel to stop loop. */
180 buf[n_read] = '\1';
181 #ifdef lint
182 /* Usually, buf[n_read] is not the byte just before a "word"
183 (aka uintptr_t) boundary. In that case, the word-oriented
184 test below (*wp++ == 0) would read some uninitialized bytes
185 after the sentinel. To avoid false-positive reports about
186 this condition (e.g., from a tool like valgrind), set the
187 remaining bytes -- to any value. */
188 memset (buf + n_read + 1, 0, sizeof (word) - 1);
189 #endif
191 /* Find first nonzero *word*, or the word with the sentinel. */
193 wp = (word *) buf;
194 while (*wp++ == 0)
195 continue;
197 /* Find the first nonzero *byte*, or the sentinel. */
199 cp = (char *) (wp - 1);
200 while (*cp++ == 0)
201 continue;
203 if (cp <= buf + n_read)
204 /* Clear to indicate that a normal write is needed. */
205 wp = NULL;
206 else
208 /* We found the sentinel, so the whole input block was zero.
209 Make a hole. */
210 if (lseek (dest_fd, n_read, SEEK_CUR) < 0)
212 error (0, errno, _("cannot lseek %s"), quote (dst_name));
213 return false;
215 *last_write_made_hole = true;
219 if (!wp)
221 size_t n = n_read;
222 if (full_write (dest_fd, buf, n) != n)
224 error (0, errno, _("writing %s"), quote (dst_name));
225 return false;
227 *last_write_made_hole = false;
229 /* It is tempting to return early here upon a short read from a
230 regular file. That would save the final read syscall for each
231 file. Unfortunately that doesn't work for certain files in
232 /proc with linux kernels from at least 2.6.9 .. 2.6.29. */
236 return true;
239 /* Perform the O(1) btrfs clone operation, if possible.
240 Upon success, return 0. Otherwise, return -1 and set errno. */
241 static inline int
242 clone_file (int dest_fd, int src_fd)
244 #ifdef __linux__
245 # undef BTRFS_IOCTL_MAGIC
246 # define BTRFS_IOCTL_MAGIC 0x94
247 # undef BTRFS_IOC_CLONE
248 # define BTRFS_IOC_CLONE _IOW (BTRFS_IOCTL_MAGIC, 9, int)
249 return ioctl (dest_fd, BTRFS_IOC_CLONE, src_fd);
250 #else
251 (void) dest_fd;
252 (void) src_fd;
253 errno = ENOTSUP;
254 return -1;
255 #endif
258 /* Write N_BYTES zero bytes to file descriptor FD. Return true if successful.
259 Upon write failure, set errno and return false. */
260 static bool
261 write_zeros (int fd, uint64_t n_bytes)
263 static char *zeros;
264 static size_t nz = IO_BUFSIZE;
266 /* Attempt to use a relatively large calloc'd source buffer for
267 efficiency, but if that allocation fails, resort to a smaller
268 statically allocated one. */
269 if (zeros == NULL)
271 static char fallback[1024];
272 zeros = calloc (nz, 1);
273 if (zeros == NULL)
275 zeros = fallback;
276 nz = sizeof fallback;
280 while (n_bytes)
282 uint64_t n = MIN (nz, n_bytes);
283 if ((full_write (fd, zeros, n)) != n)
284 return false;
285 n_bytes -= n;
288 return true;
291 /* Perform an efficient extent copy, if possible. This avoids
292 the overhead of detecting holes in hole-introducing/preserving
293 copy, and thus makes copying sparse files much more efficient.
294 Upon a successful copy, return true. If the initial extent scan
295 fails, set *NORMAL_COPY_REQUIRED to true and return false.
296 Upon any other failure, set *NORMAL_COPY_REQUIRED to false and
297 return false. */
298 static bool
299 extent_copy (int src_fd, int dest_fd, char *buf, size_t buf_size,
300 off_t src_total_size, enum Sparse_type sparse_mode,
301 char const *src_name, char const *dst_name,
302 bool *require_normal_copy)
304 struct extent_scan scan;
305 off_t last_ext_start = 0;
306 uint64_t last_ext_len = 0;
308 /* Keep track of the output position.
309 We may need this at the end, for a final ftruncate. */
310 off_t dest_pos = 0;
312 extent_scan_init (src_fd, &scan);
314 *require_normal_copy = false;
315 bool wrote_hole_at_eof = true;
318 bool ok = extent_scan_read (&scan);
319 if (! ok)
321 if (scan.hit_final_extent)
322 break;
324 if (scan.initial_scan_failed)
326 *require_normal_copy = true;
327 return false;
330 error (0, errno, _("%s: failed to get extents info"),
331 quote (src_name));
332 return false;
335 unsigned int i;
336 bool empty_extent = false;
337 for (i = 0; i < scan.ei_count || empty_extent; i++)
339 off_t ext_start;
340 uint64_t ext_len;
341 uint64_t hole_size;
343 if (i < scan.ei_count)
345 ext_start = scan.ext_info[i].ext_logical;
346 ext_len = scan.ext_info[i].ext_length;
348 else /* empty extent at EOF. */
350 i--;
351 ext_start = last_ext_start + scan.ext_info[i].ext_length;
352 ext_len = 0;
355 hole_size = ext_start - last_ext_start - last_ext_len;
357 wrote_hole_at_eof = false;
359 if (hole_size)
361 if (lseek (src_fd, ext_start, SEEK_SET) < 0)
363 error (0, errno, _("cannot lseek %s"), quote (src_name));
364 fail:
365 extent_scan_free (&scan);
366 return false;
369 if ((empty_extent && sparse_mode == SPARSE_ALWAYS)
370 || (!empty_extent && sparse_mode != SPARSE_NEVER))
372 if (lseek (dest_fd, ext_start, SEEK_SET) < 0)
374 error (0, errno, _("cannot lseek %s"), quote (dst_name));
375 goto fail;
377 wrote_hole_at_eof = true;
379 else
381 /* When not inducing holes and when there is a hole between
382 the end of the previous extent and the beginning of the
383 current one, write zeros to the destination file. */
384 off_t nzeros = hole_size;
385 if (empty_extent)
386 nzeros = MIN (src_total_size - dest_pos, hole_size);
388 if (! write_zeros (dest_fd, nzeros))
390 error (0, errno, _("%s: write failed"), quote (dst_name));
391 goto fail;
394 dest_pos = MIN (src_total_size, ext_start);
398 last_ext_start = ext_start;
400 /* Treat an unwritten but allocated extent much like a hole.
401 I.E. don't read, but don't convert to a hole in the destination,
402 unless SPARSE_ALWAYS. */
403 /* For now, do not treat FIEMAP_EXTENT_UNWRITTEN specially,
404 because that (in combination with no sync) would lead to data
405 loss at least on XFS and ext4 when using 2.6.39-rc3 kernels. */
406 if (0 && (scan.ext_info[i].ext_flags & FIEMAP_EXTENT_UNWRITTEN))
408 empty_extent = true;
409 last_ext_len = 0;
410 if (ext_len == 0) /* The last extent is empty and processed. */
411 empty_extent = false;
413 else
415 off_t n_read;
416 empty_extent = false;
417 last_ext_len = ext_len;
419 if ( ! sparse_copy (src_fd, dest_fd, buf, buf_size,
420 sparse_mode == SPARSE_ALWAYS,
421 src_name, dst_name, ext_len, &n_read,
422 &wrote_hole_at_eof))
423 goto fail;
425 dest_pos = ext_start + n_read;
428 /* If the file ends with unwritten extents not accounted for in the
429 size, then skip processing them, and the associated redundant
430 read() calls which will always return 0. We will need to
431 remove this when we add fallocate() so that we can maintain
432 extents beyond the apparent size. */
433 if (dest_pos == src_total_size)
435 scan.hit_final_extent = true;
436 break;
440 /* Release the space allocated to scan->ext_info. */
441 extent_scan_free (&scan);
444 while (! scan.hit_final_extent);
446 /* When the source file ends with a hole, we have to do a little more work,
447 since the above copied only up to and including the final extent.
448 In order to complete the copy, we may have to insert a hole or write
449 zeros in the destination corresponding to the source file's hole-at-EOF.
451 In addition, if the final extent was a block of zeros at EOF and we've
452 just converted them to a hole in the destination, we must call ftruncate
453 here in order to record the proper length in the destination. */
454 if ((dest_pos < src_total_size || wrote_hole_at_eof)
455 && (sparse_mode != SPARSE_NEVER
456 ? ftruncate (dest_fd, src_total_size)
457 : ! write_zeros (dest_fd, src_total_size - dest_pos)))
459 error (0, errno, _("failed to extend %s"), quote (dst_name));
460 return false;
463 return true;
466 /* FIXME: describe */
467 /* FIXME: rewrite this to use a hash table so we avoid the quadratic
468 performance hit that's probably noticeable only on trees deeper
469 than a few hundred levels. See use of active_dir_map in remove.c */
471 static bool _GL_ATTRIBUTE_PURE
472 is_ancestor (const struct stat *sb, const struct dir_list *ancestors)
474 while (ancestors != 0)
476 if (ancestors->ino == sb->st_ino && ancestors->dev == sb->st_dev)
477 return true;
478 ancestors = ancestors->parent;
480 return false;
483 static bool
484 errno_unsupported (int err)
486 return err == ENOTSUP || err == ENODATA;
489 #if USE_XATTR
490 static void
491 copy_attr_error (struct error_context *ctx ATTRIBUTE_UNUSED,
492 char const *fmt, ...)
494 if (!errno_unsupported (errno))
496 int err = errno;
497 va_list ap;
499 /* use verror module to print error message */
500 va_start (ap, fmt);
501 verror (0, err, fmt, ap);
502 va_end (ap);
506 static void
507 copy_attr_allerror (struct error_context *ctx ATTRIBUTE_UNUSED,
508 char const *fmt, ...)
510 int err = errno;
511 va_list ap;
513 /* use verror module to print error message */
514 va_start (ap, fmt);
515 verror (0, err, fmt, ap);
516 va_end (ap);
519 static char const *
520 copy_attr_quote (struct error_context *ctx ATTRIBUTE_UNUSED, char const *str)
522 return quote (str);
525 static void
526 copy_attr_free (struct error_context *ctx ATTRIBUTE_UNUSED,
527 char const *str ATTRIBUTE_UNUSED)
531 /* If positive SRC_FD and DST_FD descriptors are passed,
532 then copy by fd, otherwise copy by name. */
534 static bool
535 copy_attr (char const *src_path, int src_fd,
536 char const *dst_path, int dst_fd, struct cp_options const *x)
538 int ret;
539 bool all_errors = (!x->data_copy_required || x->require_preserve_xattr);
540 bool some_errors = (!all_errors && !x->reduce_diagnostics);
541 struct error_context ctx =
543 .error = all_errors ? copy_attr_allerror : copy_attr_error,
544 .quote = copy_attr_quote,
545 .quote_free = copy_attr_free
547 if (0 <= src_fd && 0 <= dst_fd)
548 ret = attr_copy_fd (src_path, src_fd, dst_path, dst_fd, 0,
549 (all_errors || some_errors ? &ctx : NULL));
550 else
551 ret = attr_copy_file (src_path, dst_path, 0,
552 (all_errors || some_errors ? &ctx : NULL));
554 return ret == 0;
556 #else /* USE_XATTR */
558 static bool
559 copy_attr (char const *src_path ATTRIBUTE_UNUSED,
560 int src_fd ATTRIBUTE_UNUSED,
561 char const *dst_path ATTRIBUTE_UNUSED,
562 int dst_fd ATTRIBUTE_UNUSED,
563 struct cp_options const *x ATTRIBUTE_UNUSED)
565 return true;
567 #endif /* USE_XATTR */
569 /* Read the contents of the directory SRC_NAME_IN, and recursively
570 copy the contents to DST_NAME_IN. NEW_DST is true if
571 DST_NAME_IN is a directory that was created previously in the
572 recursion. SRC_SB and ANCESTORS describe SRC_NAME_IN.
573 Set *COPY_INTO_SELF if SRC_NAME_IN is a parent of
574 (or the same as) DST_NAME_IN; otherwise, clear it.
575 Propagate *FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG from
576 caller to each invocation of copy_internal. Be careful to
577 pass the address of a temporary, and to update
578 *FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG only upon completion.
579 Return true if successful. */
581 static bool
582 copy_dir (char const *src_name_in, char const *dst_name_in, bool new_dst,
583 const struct stat *src_sb, struct dir_list *ancestors,
584 const struct cp_options *x,
585 bool *first_dir_created_per_command_line_arg,
586 bool *copy_into_self)
588 char *name_space;
589 char *namep;
590 struct cp_options non_command_line_options = *x;
591 bool ok = true;
593 name_space = savedir (src_name_in);
594 if (name_space == NULL)
596 /* This diagnostic is a bit vague because savedir can fail in
597 several different ways. */
598 error (0, errno, _("cannot access %s"), quote (src_name_in));
599 return false;
602 /* For cp's -H option, dereference command line arguments, but do not
603 dereference symlinks that are found via recursive traversal. */
604 if (x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
605 non_command_line_options.dereference = DEREF_NEVER;
607 bool new_first_dir_created = false;
608 namep = name_space;
609 while (*namep != '\0')
611 bool local_copy_into_self;
612 char *src_name = file_name_concat (src_name_in, namep, NULL);
613 char *dst_name = file_name_concat (dst_name_in, namep, NULL);
614 bool first_dir_created = *first_dir_created_per_command_line_arg;
616 ok &= copy_internal (src_name, dst_name, new_dst, src_sb->st_dev,
617 ancestors, &non_command_line_options, false,
618 &first_dir_created,
619 &local_copy_into_self, NULL);
620 *copy_into_self |= local_copy_into_self;
622 free (dst_name);
623 free (src_name);
625 /* If we're copying into self, there's no point in continuing,
626 and in fact, that would even infloop, now that we record only
627 the first created directory per command line argument. */
628 if (local_copy_into_self)
629 break;
631 new_first_dir_created |= first_dir_created;
632 namep += strlen (namep) + 1;
634 free (name_space);
635 *first_dir_created_per_command_line_arg = new_first_dir_created;
637 return ok;
640 /* Set the owner and owning group of DEST_DESC to the st_uid and
641 st_gid fields of SRC_SB. If DEST_DESC is undefined (-1), set
642 the owner and owning group of DST_NAME instead; for
643 safety prefer lchown if the system supports it since no
644 symbolic links should be involved. DEST_DESC must
645 refer to the same file as DEST_NAME if defined.
646 Upon failure to set both UID and GID, try to set only the GID.
647 NEW_DST is true if the file was newly created; otherwise,
648 DST_SB is the status of the destination.
649 Return 1 if the initial syscall succeeds, 0 if it fails but it's OK
650 not to preserve ownership, -1 otherwise. */
652 static int
653 set_owner (const struct cp_options *x, char const *dst_name, int dest_desc,
654 struct stat const *src_sb, bool new_dst,
655 struct stat const *dst_sb)
657 uid_t uid = src_sb->st_uid;
658 gid_t gid = src_sb->st_gid;
660 /* Naively changing the ownership of an already-existing file before
661 changing its permissions would create a window of vulnerability if
662 the file's old permissions are too generous for the new owner and
663 group. Avoid the window by first changing to a restrictive
664 temporary mode if necessary. */
666 if (!new_dst && (x->preserve_mode || x->move_mode || x->set_mode))
668 mode_t old_mode = dst_sb->st_mode;
669 mode_t new_mode =
670 (x->preserve_mode || x->move_mode ? src_sb->st_mode : x->mode);
671 mode_t restrictive_temp_mode = old_mode & new_mode & S_IRWXU;
673 if ((USE_ACL
674 || (old_mode & CHMOD_MODE_BITS
675 & (~new_mode | S_ISUID | S_ISGID | S_ISVTX)))
676 && qset_acl (dst_name, dest_desc, restrictive_temp_mode) != 0)
678 if (! owner_failure_ok (x))
679 error (0, errno, _("clearing permissions for %s"),
680 quote (dst_name));
681 return -x->require_preserve;
685 if (HAVE_FCHOWN && dest_desc != -1)
687 if (fchown (dest_desc, uid, gid) == 0)
688 return 1;
689 if (errno == EPERM || errno == EINVAL)
691 /* We've failed to set *both*. Now, try to set just the group
692 ID, but ignore any failure here, and don't change errno. */
693 int saved_errno = errno;
694 ignore_value (fchown (dest_desc, -1, gid));
695 errno = saved_errno;
698 else
700 if (lchown (dst_name, uid, gid) == 0)
701 return 1;
702 if (errno == EPERM || errno == EINVAL)
704 /* We've failed to set *both*. Now, try to set just the group
705 ID, but ignore any failure here, and don't change errno. */
706 int saved_errno = errno;
707 ignore_value (lchown (dst_name, -1, gid));
708 errno = saved_errno;
712 if (! chown_failure_ok (x))
714 error (0, errno, _("failed to preserve ownership for %s"),
715 quote (dst_name));
716 if (x->require_preserve)
717 return -1;
720 return 0;
723 /* Set the st_author field of DEST_DESC to the st_author field of
724 SRC_SB. If DEST_DESC is undefined (-1), set the st_author field
725 of DST_NAME instead. DEST_DESC must refer to the same file as
726 DEST_NAME if defined. */
728 static void
729 set_author (const char *dst_name, int dest_desc, const struct stat *src_sb)
731 #if HAVE_STRUCT_STAT_ST_AUTHOR
732 /* FIXME: Modify the following code so that it does not
733 follow symbolic links. */
735 /* Preserve the st_author field. */
736 file_t file = (dest_desc < 0
737 ? file_name_lookup (dst_name, 0, 0)
738 : getdport (dest_desc));
739 if (file == MACH_PORT_NULL)
740 error (0, errno, _("failed to lookup file %s"), quote (dst_name));
741 else
743 error_t err = file_chauthor (file, src_sb->st_author);
744 if (err)
745 error (0, err, _("failed to preserve authorship for %s"),
746 quote (dst_name));
747 mach_port_deallocate (mach_task_self (), file);
749 #else
750 (void) dst_name;
751 (void) dest_desc;
752 (void) src_sb;
753 #endif
756 /* Change the file mode bits of the file identified by DESC or NAME to MODE.
757 Use DESC if DESC is valid and fchmod is available, NAME otherwise. */
759 static int
760 fchmod_or_lchmod (int desc, char const *name, mode_t mode)
762 #if HAVE_FCHMOD
763 if (0 <= desc)
764 return fchmod (desc, mode);
765 #endif
766 return lchmod (name, mode);
769 #ifndef HAVE_STRUCT_STAT_ST_BLOCKS
770 # define HAVE_STRUCT_STAT_ST_BLOCKS 0
771 #endif
773 /* Use a heuristic to determine whether stat buffer SB comes from a file
774 with sparse blocks. If the file has fewer blocks than would normally
775 be needed for a file of its size, then at least one of the blocks in
776 the file is a hole. In that case, return true. */
777 static bool
778 is_probably_sparse (struct stat const *sb)
780 return (HAVE_STRUCT_STAT_ST_BLOCKS
781 && S_ISREG (sb->st_mode)
782 && ST_NBLOCKS (*sb) < sb->st_size / ST_NBLOCKSIZE);
786 /* Copy a regular file from SRC_NAME to DST_NAME.
787 If the source file contains holes, copies holes and blocks of zeros
788 in the source file as holes in the destination file.
789 (Holes are read as zeroes by the `read' system call.)
790 When creating the destination, use DST_MODE & ~OMITTED_PERMISSIONS
791 as the third argument in the call to open, adding
792 OMITTED_PERMISSIONS after copying as needed.
793 X provides many option settings.
794 Return true if successful.
795 *NEW_DST is as in copy_internal.
796 SRC_SB is the result of calling XSTAT (aka stat) on SRC_NAME. */
798 static bool
799 copy_reg (char const *src_name, char const *dst_name,
800 const struct cp_options *x,
801 mode_t dst_mode, mode_t omitted_permissions, bool *new_dst,
802 struct stat const *src_sb)
804 char *buf;
805 char *buf_alloc = NULL;
806 char *name_alloc = NULL;
807 int dest_desc;
808 int dest_errno;
809 int source_desc;
810 mode_t src_mode = src_sb->st_mode;
811 struct stat sb;
812 struct stat src_open_sb;
813 bool return_val = true;
814 bool data_copy_required = x->data_copy_required;
816 source_desc = open (src_name,
817 (O_RDONLY | O_BINARY
818 | (x->dereference == DEREF_NEVER ? O_NOFOLLOW : 0)));
819 if (source_desc < 0)
821 error (0, errno, _("cannot open %s for reading"), quote (src_name));
822 return false;
825 if (fstat (source_desc, &src_open_sb) != 0)
827 error (0, errno, _("cannot fstat %s"), quote (src_name));
828 return_val = false;
829 goto close_src_desc;
832 /* Compare the source dev/ino from the open file to the incoming,
833 saved ones obtained via a previous call to stat. */
834 if (! SAME_INODE (*src_sb, src_open_sb))
836 error (0, 0,
837 _("skipping file %s, as it was replaced while being copied"),
838 quote (src_name));
839 return_val = false;
840 goto close_src_desc;
843 /* The semantics of the following open calls are mandated
844 by the specs for both cp and mv. */
845 if (! *new_dst)
847 dest_desc = open (dst_name, O_WRONLY | O_TRUNC | O_BINARY);
848 dest_errno = errno;
850 /* When using cp --preserve=context to copy to an existing destination,
851 use the default context rather than that of the source. Why?
852 1) the src context may prohibit writing, and
853 2) because it's more consistent to use the same context
854 that is used when the destination file doesn't already exist. */
855 if (x->preserve_security_context && 0 <= dest_desc)
857 bool all_errors = (!x->data_copy_required
858 || x->require_preserve_context);
859 bool some_errors = !all_errors && !x->reduce_diagnostics;
860 security_context_t con = NULL;
862 if (getfscreatecon (&con) < 0)
864 if (all_errors || (some_errors && !errno_unsupported (errno)))
865 error (0, errno, _("failed to get file system create context"));
866 if (x->require_preserve_context)
868 return_val = false;
869 goto close_src_and_dst_desc;
873 if (con)
875 if (fsetfilecon (dest_desc, con) < 0)
877 if (all_errors || (some_errors && !errno_unsupported (errno)))
878 error (0, errno,
879 _("failed to set the security context of %s to %s"),
880 quote_n (0, dst_name), quote_n (1, con));
881 if (x->require_preserve_context)
883 return_val = false;
884 freecon (con);
885 goto close_src_and_dst_desc;
888 freecon (con);
892 if (dest_desc < 0 && x->unlink_dest_after_failed_open)
894 if (unlink (dst_name) != 0)
896 error (0, errno, _("cannot remove %s"), quote (dst_name));
897 return_val = false;
898 goto close_src_desc;
900 if (x->verbose)
901 printf (_("removed %s\n"), quote (dst_name));
903 /* Tell caller that the destination file was unlinked. */
904 *new_dst = true;
908 if (*new_dst)
910 int open_flags = O_WRONLY | O_CREAT | O_BINARY;
911 dest_desc = open (dst_name, open_flags | O_EXCL,
912 dst_mode & ~omitted_permissions);
913 dest_errno = errno;
915 /* When trying to copy through a dangling destination symlink,
916 the above open fails with EEXIST. If that happens, and
917 lstat'ing the DST_NAME shows that it is a symlink, then we
918 have a problem: trying to resolve this dangling symlink to
919 a directory/destination-entry pair is fundamentally racy,
920 so punt. If x->open_dangling_dest_symlink is set (cp sets
921 that when POSIXLY_CORRECT is set in the environment), simply
922 call open again, but without O_EXCL (potentially dangerous).
923 If not, fail with a diagnostic. These shenanigans are necessary
924 only when copying, i.e., not in move_mode. */
925 if (dest_desc < 0 && dest_errno == EEXIST && ! x->move_mode)
927 struct stat dangling_link_sb;
928 if (lstat (dst_name, &dangling_link_sb) == 0
929 && S_ISLNK (dangling_link_sb.st_mode))
931 if (x->open_dangling_dest_symlink)
933 dest_desc = open (dst_name, open_flags,
934 dst_mode & ~omitted_permissions);
935 dest_errno = errno;
937 else
939 error (0, 0, _("not writing through dangling symlink %s"),
940 quote (dst_name));
941 return_val = false;
942 goto close_src_desc;
947 /* Improve quality of diagnostic when a nonexistent dst_name
948 ends in a slash and open fails with errno == EISDIR. */
949 if (dest_desc < 0 && dest_errno == EISDIR
950 && *dst_name && dst_name[strlen (dst_name) - 1] == '/')
951 dest_errno = ENOTDIR;
953 else
954 omitted_permissions = 0;
956 if (dest_desc < 0)
958 error (0, dest_errno, _("cannot create regular file %s"),
959 quote (dst_name));
960 return_val = false;
961 goto close_src_desc;
964 if (fstat (dest_desc, &sb) != 0)
966 error (0, errno, _("cannot fstat %s"), quote (dst_name));
967 return_val = false;
968 goto close_src_and_dst_desc;
971 /* --attributes-only overrides --reflink. */
972 if (data_copy_required && x->reflink_mode)
974 bool clone_ok = clone_file (dest_desc, source_desc) == 0;
975 if (clone_ok || x->reflink_mode == REFLINK_ALWAYS)
977 if (!clone_ok)
979 error (0, errno, _("failed to clone %s from %s"),
980 quote_n (0, dst_name), quote_n (1, src_name));
981 return_val = false;
982 goto close_src_and_dst_desc;
984 data_copy_required = false;
988 if (data_copy_required)
990 typedef uintptr_t word;
992 /* Choose a suitable buffer size; it may be adjusted later. */
993 size_t buf_alignment = lcm (getpagesize (), sizeof (word));
994 size_t buf_alignment_slop = sizeof (word) + buf_alignment - 1;
995 size_t buf_size = io_blksize (sb);
997 /* Deal with sparse files. */
998 bool make_holes = false;
999 bool sparse_src = false;
1001 if (S_ISREG (sb.st_mode))
1003 /* Even with --sparse=always, try to create holes only
1004 if the destination is a regular file. */
1005 if (x->sparse_mode == SPARSE_ALWAYS)
1006 make_holes = true;
1008 /* Use a heuristic to determine whether SRC_NAME contains any sparse
1009 blocks. If the file has fewer blocks than would normally be
1010 needed for a file of its size, then at least one of the blocks in
1011 the file is a hole. */
1012 sparse_src = is_probably_sparse (&src_open_sb);
1013 if (x->sparse_mode == SPARSE_AUTO && sparse_src)
1014 make_holes = true;
1017 /* If not making a sparse file, try to use a more-efficient
1018 buffer size. */
1019 if (! make_holes)
1021 /* Compute the least common multiple of the input and output
1022 buffer sizes, adjusting for outlandish values. */
1023 size_t blcm_max = MIN (SIZE_MAX, SSIZE_MAX) - buf_alignment_slop;
1024 size_t blcm = buffer_lcm (io_blksize (src_open_sb), buf_size,
1025 blcm_max);
1027 /* Do not bother with a buffer larger than the input file, plus one
1028 byte to make sure the file has not grown while reading it. */
1029 if (S_ISREG (src_open_sb.st_mode) && src_open_sb.st_size < buf_size)
1030 buf_size = src_open_sb.st_size + 1;
1032 /* However, stick with a block size that is a positive multiple of
1033 blcm, overriding the above adjustments. Watch out for
1034 overflow. */
1035 buf_size += blcm - 1;
1036 buf_size -= buf_size % blcm;
1037 if (buf_size == 0 || blcm_max < buf_size)
1038 buf_size = blcm;
1041 /* Make a buffer with space for a sentinel at the end. */
1042 buf_alloc = xmalloc (buf_size + buf_alignment_slop);
1043 buf = ptr_align (buf_alloc, buf_alignment);
1045 if (sparse_src)
1047 bool normal_copy_required;
1049 /* Perform an efficient extent-based copy, falling back to the
1050 standard copy only if the initial extent scan fails. If the
1051 '--sparse=never' option is specified, write all data but use
1052 any extents to read more efficiently. */
1053 if (extent_copy (source_desc, dest_desc, buf, buf_size,
1054 src_open_sb.st_size,
1055 S_ISREG (sb.st_mode) ? x->sparse_mode : SPARSE_NEVER,
1056 src_name, dst_name, &normal_copy_required))
1057 goto preserve_metadata;
1059 if (! normal_copy_required)
1061 return_val = false;
1062 goto close_src_and_dst_desc;
1066 off_t n_read;
1067 bool wrote_hole_at_eof;
1068 if ( ! sparse_copy (source_desc, dest_desc, buf, buf_size,
1069 make_holes, src_name, dst_name,
1070 UINTMAX_MAX, &n_read,
1071 &wrote_hole_at_eof)
1072 || (wrote_hole_at_eof &&
1073 ftruncate (dest_desc, n_read) < 0))
1075 error (0, errno, _("failed to extend %s"), quote (dst_name));
1076 return_val = false;
1077 goto close_src_and_dst_desc;
1081 preserve_metadata:
1082 if (x->preserve_timestamps)
1084 struct timespec timespec[2];
1085 timespec[0] = get_stat_atime (src_sb);
1086 timespec[1] = get_stat_mtime (src_sb);
1088 if (fdutimens (dest_desc, dst_name, timespec) != 0)
1090 error (0, errno, _("preserving times for %s"), quote (dst_name));
1091 if (x->require_preserve)
1093 return_val = false;
1094 goto close_src_and_dst_desc;
1099 /* Set ownership before xattrs as changing owners will
1100 clear capabilities. */
1101 if (x->preserve_ownership && ! SAME_OWNER_AND_GROUP (*src_sb, sb))
1103 switch (set_owner (x, dst_name, dest_desc, src_sb, *new_dst, &sb))
1105 case -1:
1106 return_val = false;
1107 goto close_src_and_dst_desc;
1109 case 0:
1110 src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX);
1111 break;
1115 /* To allow copying xattrs on read-only files, temporarily chmod u+rw.
1116 This workaround is required as an inode permission check is done
1117 by xattr_permission() in fs/xattr.c of the GNU/Linux kernel tree. */
1118 if (x->preserve_xattr)
1120 bool access_changed = false;
1122 if (!(sb.st_mode & S_IWUSR) && geteuid () != 0)
1123 access_changed = fchmod_or_lchmod (dest_desc, dst_name, 0600) == 0;
1125 if (!copy_attr (src_name, source_desc, dst_name, dest_desc, x)
1126 && x->require_preserve_xattr)
1127 return_val = false;
1129 if (access_changed)
1130 fchmod_or_lchmod (dest_desc, dst_name, dst_mode & ~omitted_permissions);
1133 set_author (dst_name, dest_desc, src_sb);
1135 if (x->preserve_mode || x->move_mode)
1137 if (copy_acl (src_name, source_desc, dst_name, dest_desc, src_mode) != 0
1138 && x->require_preserve)
1139 return_val = false;
1141 else if (x->set_mode)
1143 if (set_acl (dst_name, dest_desc, x->mode) != 0)
1144 return_val = false;
1146 else if (omitted_permissions)
1148 omitted_permissions &= ~ cached_umask ();
1149 if (omitted_permissions
1150 && fchmod_or_lchmod (dest_desc, dst_name, dst_mode) != 0)
1152 error (0, errno, _("preserving permissions for %s"),
1153 quote (dst_name));
1154 if (x->require_preserve)
1155 return_val = false;
1159 close_src_and_dst_desc:
1160 if (close (dest_desc) < 0)
1162 error (0, errno, _("closing %s"), quote (dst_name));
1163 return_val = false;
1165 close_src_desc:
1166 if (close (source_desc) < 0)
1168 error (0, errno, _("closing %s"), quote (src_name));
1169 return_val = false;
1172 free (buf_alloc);
1173 free (name_alloc);
1174 return return_val;
1177 /* Return true if it's ok that the source and destination
1178 files are the `same' by some measure. The goal is to avoid
1179 making the `copy' operation remove both copies of the file
1180 in that case, while still allowing the user to e.g., move or
1181 copy a regular file onto a symlink that points to it.
1182 Try to minimize the cost of this function in the common case.
1183 Set *RETURN_NOW if we've determined that the caller has no more
1184 work to do and should return successfully, right away.
1186 Set *UNLINK_SRC if we've determined that the caller wants to do
1187 `rename (a, b)' where `a' and `b' are distinct hard links to the same
1188 file. In that case, the caller should try to unlink `a' and then return
1189 successfully. Ideally, we wouldn't have to do that, and we'd be
1190 able to rely on rename to remove the source file. However, POSIX
1191 mistakenly requires that such a rename call do *nothing* and return
1192 successfully. */
1194 static bool
1195 same_file_ok (char const *src_name, struct stat const *src_sb,
1196 char const *dst_name, struct stat const *dst_sb,
1197 const struct cp_options *x, bool *return_now, bool *unlink_src)
1199 const struct stat *src_sb_link;
1200 const struct stat *dst_sb_link;
1201 struct stat tmp_dst_sb;
1202 struct stat tmp_src_sb;
1204 bool same_link;
1205 bool same = SAME_INODE (*src_sb, *dst_sb);
1207 *return_now = false;
1208 *unlink_src = false;
1210 /* FIXME: this should (at the very least) be moved into the following
1211 if-block. More likely, it should be removed, because it inhibits
1212 making backups. But removing it will result in a change in behavior
1213 that will probably have to be documented -- and tests will have to
1214 be updated. */
1215 if (same && x->hard_link)
1217 *return_now = true;
1218 return true;
1221 if (x->dereference == DEREF_NEVER)
1223 same_link = same;
1225 /* If both the source and destination files are symlinks (and we'll
1226 know this here IFF preserving symlinks), then it's ok -- as long
1227 as they are distinct. */
1228 if (S_ISLNK (src_sb->st_mode) && S_ISLNK (dst_sb->st_mode))
1229 return ! same_name (src_name, dst_name);
1231 src_sb_link = src_sb;
1232 dst_sb_link = dst_sb;
1234 else
1236 if (!same)
1237 return true;
1239 if (lstat (dst_name, &tmp_dst_sb) != 0
1240 || lstat (src_name, &tmp_src_sb) != 0)
1241 return true;
1243 src_sb_link = &tmp_src_sb;
1244 dst_sb_link = &tmp_dst_sb;
1246 same_link = SAME_INODE (*src_sb_link, *dst_sb_link);
1248 /* If both are symlinks, then it's ok, but only if the destination
1249 will be unlinked before being opened. This is like the test
1250 above, but with the addition of the unlink_dest_before_opening
1251 conjunct because otherwise, with two symlinks to the same target,
1252 we'd end up truncating the source file. */
1253 if (S_ISLNK (src_sb_link->st_mode) && S_ISLNK (dst_sb_link->st_mode)
1254 && x->unlink_dest_before_opening)
1255 return true;
1258 /* The backup code ensures there's a copy, so it's usually ok to
1259 remove any destination file. One exception is when both
1260 source and destination are the same directory entry. In that
1261 case, moving the destination file aside (in making the backup)
1262 would also rename the source file and result in an error. */
1263 if (x->backup_type != no_backups)
1265 if (!same_link)
1267 /* In copy mode when dereferencing symlinks, if the source is a
1268 symlink and the dest is not, then backing up the destination
1269 (moving it aside) would make it a dangling symlink, and the
1270 subsequent attempt to open it in copy_reg would fail with
1271 a misleading diagnostic. Avoid that by returning zero in
1272 that case so the caller can make cp (or mv when it has to
1273 resort to reading the source file) fail now. */
1275 /* FIXME-note: even with the following kludge, we can still provoke
1276 the offending diagnostic. It's just a little harder to do :-)
1277 $ rm -f a b c; touch c; ln -s c b; ln -s b a; cp -b a b
1278 cp: cannot open `a' for reading: No such file or directory
1279 That's misleading, since a subsequent `ls' shows that `a'
1280 is still there.
1281 One solution would be to open the source file *before* moving
1282 aside the destination, but that'd involve a big rewrite. */
1283 if ( ! x->move_mode
1284 && x->dereference != DEREF_NEVER
1285 && S_ISLNK (src_sb_link->st_mode)
1286 && ! S_ISLNK (dst_sb_link->st_mode))
1287 return false;
1289 return true;
1292 return ! same_name (src_name, dst_name);
1295 #if 0
1296 /* FIXME: use or remove */
1298 /* If we're making a backup, we'll detect the problem case in
1299 copy_reg because SRC_NAME will no longer exist. Allowing
1300 the test to be deferred lets cp do some useful things.
1301 But when creating hardlinks and SRC_NAME is a symlink
1302 but DST_NAME is not we must test anyway. */
1303 if (x->hard_link
1304 || !S_ISLNK (src_sb_link->st_mode)
1305 || S_ISLNK (dst_sb_link->st_mode))
1306 return true;
1308 if (x->dereference != DEREF_NEVER)
1309 return true;
1310 #endif
1312 /* They may refer to the same file if we're in move mode and the
1313 target is a symlink. That is ok, since we remove any existing
1314 destination file before opening it -- via `rename' if they're on
1315 the same file system, via `unlink (DST_NAME)' otherwise.
1316 It's also ok if they're distinct hard links to the same file. */
1317 if (x->move_mode || x->unlink_dest_before_opening)
1319 if (S_ISLNK (dst_sb_link->st_mode))
1320 return true;
1322 if (same_link
1323 && 1 < dst_sb_link->st_nlink
1324 && ! same_name (src_name, dst_name))
1326 if (x->move_mode)
1328 *unlink_src = true;
1329 *return_now = true;
1331 return true;
1335 /* If neither is a symlink, then it's ok as long as they aren't
1336 hard links to the same file. */
1337 if (!S_ISLNK (src_sb_link->st_mode) && !S_ISLNK (dst_sb_link->st_mode))
1339 if (!SAME_INODE (*src_sb_link, *dst_sb_link))
1340 return true;
1342 /* If they are the same file, it's ok if we're making hard links. */
1343 if (x->hard_link)
1345 *return_now = true;
1346 return true;
1350 /* It's ok to remove a destination symlink. But that works only when we
1351 unlink before opening the destination and when the source and destination
1352 files are on the same partition. */
1353 if (x->unlink_dest_before_opening
1354 && S_ISLNK (dst_sb_link->st_mode))
1355 return dst_sb_link->st_dev == src_sb_link->st_dev;
1357 if (x->dereference == DEREF_NEVER)
1359 if ( ! S_ISLNK (src_sb_link->st_mode))
1360 tmp_src_sb = *src_sb_link;
1361 else if (stat (src_name, &tmp_src_sb) != 0)
1362 return true;
1364 if ( ! S_ISLNK (dst_sb_link->st_mode))
1365 tmp_dst_sb = *dst_sb_link;
1366 else if (stat (dst_name, &tmp_dst_sb) != 0)
1367 return true;
1369 if ( ! SAME_INODE (tmp_src_sb, tmp_dst_sb))
1370 return true;
1372 /* FIXME: shouldn't this be testing whether we're making symlinks? */
1373 if (x->hard_link)
1375 *return_now = true;
1376 return true;
1380 return false;
1383 /* Return true if FILE, with mode MODE, is writable in the sense of 'mv'.
1384 Always consider a symbolic link to be writable. */
1385 static bool
1386 writable_destination (char const *file, mode_t mode)
1388 return (S_ISLNK (mode)
1389 || can_write_any_file ()
1390 || euidaccess (file, W_OK) == 0);
1393 static void
1394 overwrite_prompt (char const *dst_name, struct stat const *dst_sb)
1396 if (! writable_destination (dst_name, dst_sb->st_mode))
1398 char perms[12]; /* "-rwxrwxrwx " ls-style modes. */
1399 strmode (dst_sb->st_mode, perms);
1400 perms[10] = '\0';
1401 fprintf (stderr,
1402 _("%s: try to overwrite %s, overriding mode %04lo (%s)? "),
1403 program_name, quote (dst_name),
1404 (unsigned long int) (dst_sb->st_mode & CHMOD_MODE_BITS),
1405 &perms[1]);
1407 else
1409 fprintf (stderr, _("%s: overwrite %s? "),
1410 program_name, quote (dst_name));
1414 /* Initialize the hash table implementing a set of F_triple entries
1415 corresponding to destination files. */
1416 extern void
1417 dest_info_init (struct cp_options *x)
1419 x->dest_info
1420 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
1421 NULL,
1422 triple_hash,
1423 triple_compare,
1424 triple_free);
1427 /* Initialize the hash table implementing a set of F_triple entries
1428 corresponding to source files listed on the command line. */
1429 extern void
1430 src_info_init (struct cp_options *x)
1433 /* Note that we use triple_hash_no_name here.
1434 Contrast with the use of triple_hash above.
1435 That is necessary because a source file may be specified
1436 in many different ways. We want to warn about this
1437 cp a a d/
1438 as well as this:
1439 cp a ./a d/
1441 x->src_info
1442 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
1443 NULL,
1444 triple_hash_no_name,
1445 triple_compare,
1446 triple_free);
1449 /* When effecting a move (e.g., for mv(1)), and given the name DST_NAME
1450 of the destination and a corresponding stat buffer, DST_SB, return
1451 true if the logical `move' operation should _not_ proceed.
1452 Otherwise, return false.
1453 Depending on options specified in X, this code may issue an
1454 interactive prompt asking whether it's ok to overwrite DST_NAME. */
1455 static bool
1456 abandon_move (const struct cp_options *x,
1457 char const *dst_name,
1458 struct stat const *dst_sb)
1460 assert (x->move_mode);
1461 return (x->interactive == I_ALWAYS_NO
1462 || ((x->interactive == I_ASK_USER
1463 || (x->interactive == I_UNSPECIFIED
1464 && x->stdin_tty
1465 && ! writable_destination (dst_name, dst_sb->st_mode)))
1466 && (overwrite_prompt (dst_name, dst_sb), 1)
1467 && ! yesno ()));
1470 /* Print --verbose output on standard output, e.g. `new' -> `old'.
1471 If BACKUP_DST_NAME is non-NULL, then also indicate that it is
1472 the name of a backup file. */
1473 static void
1474 emit_verbose (char const *src, char const *dst, char const *backup_dst_name)
1476 printf ("%s -> %s", quote_n (0, src), quote_n (1, dst));
1477 if (backup_dst_name)
1478 printf (_(" (backup: %s)"), quote (backup_dst_name));
1479 putchar ('\n');
1482 /* A wrapper around "setfscreatecon (NULL)" that exits upon failure. */
1483 static void
1484 restore_default_fscreatecon_or_die (void)
1486 if (setfscreatecon (NULL) != 0)
1487 error (EXIT_FAILURE, errno,
1488 _("failed to restore the default file creation context"));
1491 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
1492 any type. NEW_DST should be true if the file DST_NAME cannot
1493 exist because its parent directory was just created; NEW_DST should
1494 be false if DST_NAME might already exist. DEVICE is the device
1495 number of the parent directory, or 0 if the parent of this file is
1496 not known. ANCESTORS points to a linked, null terminated list of
1497 devices and inodes of parent directories of SRC_NAME. COMMAND_LINE_ARG
1498 is true iff SRC_NAME was specified on the command line.
1499 FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG is both input and output.
1500 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
1501 same as) DST_NAME; otherwise, clear it.
1502 Return true if successful. */
1503 static bool
1504 copy_internal (char const *src_name, char const *dst_name,
1505 bool new_dst,
1506 dev_t device,
1507 struct dir_list *ancestors,
1508 const struct cp_options *x,
1509 bool command_line_arg,
1510 bool *first_dir_created_per_command_line_arg,
1511 bool *copy_into_self,
1512 bool *rename_succeeded)
1514 struct stat src_sb;
1515 struct stat dst_sb;
1516 mode_t src_mode;
1517 mode_t dst_mode IF_LINT ( = 0);
1518 mode_t dst_mode_bits;
1519 mode_t omitted_permissions;
1520 bool restore_dst_mode = false;
1521 char *earlier_file = NULL;
1522 char *dst_backup = NULL;
1523 bool backup_succeeded = false;
1524 bool delayed_ok;
1525 bool copied_as_regular = false;
1526 bool dest_is_symlink = false;
1527 bool have_dst_lstat = false;
1529 if (x->move_mode && rename_succeeded)
1530 *rename_succeeded = false;
1532 *copy_into_self = false;
1534 if (XSTAT (x, src_name, &src_sb) != 0)
1536 error (0, errno, _("cannot stat %s"), quote (src_name));
1537 return false;
1540 src_mode = src_sb.st_mode;
1542 if (S_ISDIR (src_mode) && !x->recursive)
1544 error (0, 0, _("omitting directory %s"), quote (src_name));
1545 return false;
1548 /* Detect the case in which the same source file appears more than
1549 once on the command line and no backup option has been selected.
1550 If so, simply warn and don't copy it the second time.
1551 This check is enabled only if x->src_info is non-NULL. */
1552 if (command_line_arg)
1554 if ( ! S_ISDIR (src_sb.st_mode)
1555 && x->backup_type == no_backups
1556 && seen_file (x->src_info, src_name, &src_sb))
1558 error (0, 0, _("warning: source file %s specified more than once"),
1559 quote (src_name));
1560 return true;
1563 record_file (x->src_info, src_name, &src_sb);
1566 if (!new_dst)
1568 /* Regular files can be created by writing through symbolic
1569 links, but other files cannot. So use stat on the
1570 destination when copying a regular file, and lstat otherwise.
1571 However, if we intend to unlink or remove the destination
1572 first, use lstat, since a copy won't actually be made to the
1573 destination in that case. */
1574 bool use_stat =
1575 ((S_ISREG (src_mode)
1576 || (x->copy_as_regular
1577 && ! (S_ISDIR (src_mode) || S_ISLNK (src_mode))))
1578 && ! (x->move_mode || x->symbolic_link || x->hard_link
1579 || x->backup_type != no_backups
1580 || x->unlink_dest_before_opening));
1581 if ((use_stat
1582 ? stat (dst_name, &dst_sb)
1583 : lstat (dst_name, &dst_sb))
1584 != 0)
1586 if (errno != ENOENT)
1588 error (0, errno, _("cannot stat %s"), quote (dst_name));
1589 return false;
1591 else
1593 new_dst = true;
1596 else
1597 { /* Here, we know that dst_name exists, at least to the point
1598 that it is stat'able or lstat'able. */
1599 bool return_now;
1600 bool unlink_src;
1602 have_dst_lstat = !use_stat;
1603 if (! same_file_ok (src_name, &src_sb, dst_name, &dst_sb,
1604 x, &return_now, &unlink_src))
1606 error (0, 0, _("%s and %s are the same file"),
1607 quote_n (0, src_name), quote_n (1, dst_name));
1608 return false;
1611 if (!S_ISDIR (src_mode) && x->update)
1613 /* When preserving time stamps (but not moving within a file
1614 system), don't worry if the destination time stamp is
1615 less than the source merely because of time stamp
1616 truncation. */
1617 int options = ((x->preserve_timestamps
1618 && ! (x->move_mode
1619 && dst_sb.st_dev == src_sb.st_dev))
1620 ? UTIMECMP_TRUNCATE_SOURCE
1621 : 0);
1623 if (0 <= utimecmp (dst_name, &dst_sb, &src_sb, options))
1625 /* We're using --update and the destination is not older
1626 than the source, so do not copy or move. Pretend the
1627 rename succeeded, so the caller (if it's mv) doesn't
1628 end up removing the source file. */
1629 if (rename_succeeded)
1630 *rename_succeeded = true;
1632 /* However, we still must record that we've processed
1633 this src/dest pair, in case this source file is
1634 hard-linked to another one. In that case, we'll use
1635 the mapping information to link the corresponding
1636 destination names. */
1637 earlier_file = remember_copied (dst_name, src_sb.st_ino,
1638 src_sb.st_dev);
1639 if (earlier_file)
1640 goto create_hard_link;
1642 return true;
1646 /* When there is an existing destination file, we may end up
1647 returning early, and hence not copying/moving the file.
1648 This may be due to an interactive `negative' reply to the
1649 prompt about the existing file. It may also be due to the
1650 use of the --reply=no option.
1652 cp and mv treat -i and -f differently. */
1653 if (x->move_mode)
1655 if (abandon_move (x, dst_name, &dst_sb)
1656 || (unlink_src && unlink (src_name) == 0))
1658 /* Pretend the rename succeeded, so the caller (mv)
1659 doesn't end up removing the source file. */
1660 if (rename_succeeded)
1661 *rename_succeeded = true;
1662 if (unlink_src && x->verbose)
1663 printf (_("removed %s\n"), quote (src_name));
1664 return true;
1666 if (unlink_src)
1668 error (0, errno, _("cannot remove %s"), quote (src_name));
1669 return false;
1672 else
1674 if (! S_ISDIR (src_mode)
1675 && (x->interactive == I_ALWAYS_NO
1676 || (x->interactive == I_ASK_USER
1677 && (overwrite_prompt (dst_name, &dst_sb), 1)
1678 && ! yesno ())))
1679 return true;
1682 if (return_now)
1683 return true;
1685 if (!S_ISDIR (dst_sb.st_mode))
1687 if (S_ISDIR (src_mode))
1689 if (x->move_mode && x->backup_type != no_backups)
1691 /* Moving a directory onto an existing
1692 non-directory is ok only with --backup. */
1694 else
1696 error (0, 0,
1697 _("cannot overwrite non-directory %s with directory %s"),
1698 quote_n (0, dst_name), quote_n (1, src_name));
1699 return false;
1703 /* Don't let the user destroy their data, even if they try hard:
1704 This mv command must fail (likewise for cp):
1705 rm -rf a b c; mkdir a b c; touch a/f b/f; mv a/f b/f c
1706 Otherwise, the contents of b/f would be lost.
1707 In the case of `cp', b/f would be lost if the user simulated
1708 a move using cp and rm.
1709 Note that it works fine if you use --backup=numbered. */
1710 if (command_line_arg
1711 && x->backup_type != numbered_backups
1712 && seen_file (x->dest_info, dst_name, &dst_sb))
1714 error (0, 0,
1715 _("will not overwrite just-created %s with %s"),
1716 quote_n (0, dst_name), quote_n (1, src_name));
1717 return false;
1721 if (!S_ISDIR (src_mode))
1723 if (S_ISDIR (dst_sb.st_mode))
1725 if (x->move_mode && x->backup_type != no_backups)
1727 /* Moving a non-directory onto an existing
1728 directory is ok only with --backup. */
1730 else
1732 error (0, 0,
1733 _("cannot overwrite directory %s with non-directory"),
1734 quote (dst_name));
1735 return false;
1740 if (x->move_mode)
1742 /* Don't allow user to move a directory onto a non-directory. */
1743 if (S_ISDIR (src_sb.st_mode) && !S_ISDIR (dst_sb.st_mode)
1744 && x->backup_type == no_backups)
1746 error (0, 0,
1747 _("cannot move directory onto non-directory: %s -> %s"),
1748 quote_n (0, src_name), quote_n (0, dst_name));
1749 return false;
1753 if (x->backup_type != no_backups
1754 /* Don't try to back up a destination if the last
1755 component of src_name is "." or "..". */
1756 && ! dot_or_dotdot (last_component (src_name))
1757 /* Create a backup of each destination directory in move mode,
1758 but not in copy mode. FIXME: it might make sense to add an
1759 option to suppress backup creation also for move mode.
1760 That would let one use mv to merge new content into an
1761 existing hierarchy. */
1762 && (x->move_mode || ! S_ISDIR (dst_sb.st_mode)))
1764 char *tmp_backup = find_backup_file_name (dst_name,
1765 x->backup_type);
1767 /* Detect (and fail) when creating the backup file would
1768 destroy the source file. Before, running the commands
1769 cd /tmp; rm -f a a~; : > a; echo A > a~; cp --b=simple a~ a
1770 would leave two zero-length files: a and a~. */
1771 /* FIXME: but simply change e.g., the final a~ to `./a~'
1772 and the source will still be destroyed. */
1773 if (STREQ (tmp_backup, src_name))
1775 const char *fmt;
1776 fmt = (x->move_mode
1777 ? _("backing up %s would destroy source; %s not moved")
1778 : _("backing up %s would destroy source; %s not copied"));
1779 error (0, 0, fmt,
1780 quote_n (0, dst_name),
1781 quote_n (1, src_name));
1782 free (tmp_backup);
1783 return false;
1786 /* FIXME: use fts:
1787 Using alloca for a file name that may be arbitrarily
1788 long is not recommended. In fact, even forming such a name
1789 should be discouraged. Eventually, this code will be rewritten
1790 to use fts, so using alloca here will be less of a problem. */
1791 ASSIGN_STRDUPA (dst_backup, tmp_backup);
1792 free (tmp_backup);
1793 if (rename (dst_name, dst_backup) != 0)
1795 if (errno != ENOENT)
1797 error (0, errno, _("cannot backup %s"), quote (dst_name));
1798 return false;
1800 else
1802 dst_backup = NULL;
1805 else
1807 backup_succeeded = true;
1809 new_dst = true;
1811 else if (! S_ISDIR (dst_sb.st_mode)
1812 /* Never unlink dst_name when in move mode. */
1813 && ! x->move_mode
1814 && (x->unlink_dest_before_opening
1815 || (x->preserve_links && 1 < dst_sb.st_nlink)
1816 || (x->dereference == DEREF_NEVER
1817 && ! S_ISREG (src_sb.st_mode))
1820 if (unlink (dst_name) != 0 && errno != ENOENT)
1822 error (0, errno, _("cannot remove %s"), quote (dst_name));
1823 return false;
1825 new_dst = true;
1826 if (x->verbose)
1827 printf (_("removed %s\n"), quote (dst_name));
1832 /* Ensure we don't try to copy through a symlink that was
1833 created by a prior call to this function. */
1834 if (command_line_arg
1835 && x->dest_info
1836 && ! x->move_mode
1837 && x->backup_type == no_backups)
1839 bool lstat_ok = true;
1840 struct stat tmp_buf;
1841 struct stat *dst_lstat_sb;
1843 /* If we called lstat above, good: use that data.
1844 Otherwise, call lstat here, in case dst_name is a symlink. */
1845 if (have_dst_lstat)
1846 dst_lstat_sb = &dst_sb;
1847 else
1849 if (lstat (dst_name, &tmp_buf) == 0)
1850 dst_lstat_sb = &tmp_buf;
1851 else
1852 lstat_ok = false;
1855 /* Never copy through a symlink we've just created. */
1856 if (lstat_ok
1857 && S_ISLNK (dst_lstat_sb->st_mode)
1858 && seen_file (x->dest_info, dst_name, dst_lstat_sb))
1860 error (0, 0,
1861 _("will not copy %s through just-created symlink %s"),
1862 quote_n (0, src_name), quote_n (1, dst_name));
1863 return false;
1867 /* If the source is a directory, we don't always create the destination
1868 directory. So --verbose should not announce anything until we're
1869 sure we'll create a directory. */
1870 if (x->verbose && !S_ISDIR (src_mode))
1871 emit_verbose (src_name, dst_name, backup_succeeded ? dst_backup : NULL);
1873 /* Associate the destination file name with the source device and inode
1874 so that if we encounter a matching dev/ino pair in the source tree
1875 we can arrange to create a hard link between the corresponding names
1876 in the destination tree.
1878 When using the --link (-l) option, there is no need to take special
1879 measures, because (barring race conditions) files that are hard-linked
1880 in the source tree will also be hard-linked in the destination tree.
1882 Sometimes, when preserving links, we have to record dev/ino even
1883 though st_nlink == 1:
1884 - when in move_mode, since we may be moving a group of N hard-linked
1885 files (via two or more command line arguments) to a different
1886 partition; the links may be distributed among the command line
1887 arguments (possibly hierarchies) so that the link count of
1888 the final, once-linked source file is reduced to 1 when it is
1889 considered below. But in this case (for mv) we don't need to
1890 incur the expense of recording the dev/ino => name mapping; all we
1891 really need is a lookup, to see if the dev/ino pair has already
1892 been copied.
1893 - when using -H and processing a command line argument;
1894 that command line argument could be a symlink pointing to another
1895 command line argument. With `cp -H --preserve=link', we hard-link
1896 those two destination files.
1897 - likewise for -L except that it applies to all files, not just
1898 command line arguments.
1900 Also, with --recursive, record dev/ino of each command-line directory.
1901 We'll use that info to detect this problem: cp -R dir dir. */
1903 if (x->move_mode && src_sb.st_nlink == 1)
1905 earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev);
1907 else if (x->preserve_links
1908 && !x->hard_link
1909 && (1 < src_sb.st_nlink
1910 || (command_line_arg
1911 && x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
1912 || x->dereference == DEREF_ALWAYS))
1914 earlier_file = remember_copied (dst_name, src_sb.st_ino, src_sb.st_dev);
1916 else if (x->recursive && S_ISDIR (src_mode))
1918 if (command_line_arg)
1919 earlier_file = remember_copied (dst_name, src_sb.st_ino, src_sb.st_dev);
1920 else
1921 earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev);
1924 /* Did we copy this inode somewhere else (in this command line argument)
1925 and therefore this is a second hard link to the inode? */
1927 if (earlier_file)
1929 /* Avoid damaging the destination file system by refusing to preserve
1930 hard-linked directories (which are found at least in Netapp snapshot
1931 directories). */
1932 if (S_ISDIR (src_mode))
1934 /* If src_name and earlier_file refer to the same directory entry,
1935 then warn about copying a directory into itself. */
1936 if (same_name (src_name, earlier_file))
1938 error (0, 0, _("cannot copy a directory, %s, into itself, %s"),
1939 quote_n (0, top_level_src_name),
1940 quote_n (1, top_level_dst_name));
1941 *copy_into_self = true;
1942 goto un_backup;
1944 else if (x->dereference == DEREF_ALWAYS)
1946 /* This happens when e.g., encountering a directory for the
1947 second or subsequent time via symlinks when cp is invoked
1948 with -R and -L. E.g.,
1949 rm -rf a b c d; mkdir a b c d; ln -s ../c a; ln -s ../c b;
1950 cp -RL a b d
1953 else
1955 error (0, 0, _("will not create hard link %s to directory %s"),
1956 quote_n (0, dst_name), quote_n (1, earlier_file));
1957 goto un_backup;
1960 else
1962 create_hard_link:;
1963 /* We want to guarantee that symlinks are not followed. */
1964 bool link_failed = (linkat (AT_FDCWD, earlier_file, AT_FDCWD,
1965 dst_name, 0) != 0);
1967 /* If the link failed because of an existing destination,
1968 remove that file and then call link again. */
1969 if (link_failed && errno == EEXIST)
1971 if (unlink (dst_name) != 0)
1973 error (0, errno, _("cannot remove %s"), quote (dst_name));
1974 goto un_backup;
1976 if (x->verbose)
1977 printf (_("removed %s\n"), quote (dst_name));
1978 link_failed = (linkat (AT_FDCWD, earlier_file, AT_FDCWD,
1979 dst_name, 0) != 0);
1982 if (link_failed)
1984 error (0, errno, _("cannot create hard link %s to %s"),
1985 quote_n (0, dst_name), quote_n (1, earlier_file));
1986 goto un_backup;
1989 return true;
1993 if (x->move_mode)
1995 if (rename (src_name, dst_name) == 0)
1997 if (x->verbose && S_ISDIR (src_mode))
1998 emit_verbose (src_name, dst_name,
1999 backup_succeeded ? dst_backup : NULL);
2001 if (rename_succeeded)
2002 *rename_succeeded = true;
2004 if (command_line_arg)
2006 /* Record destination dev/ino/name, so that if we are asked
2007 to overwrite that file again, we can detect it and fail. */
2008 /* It's fine to use the _source_ stat buffer (src_sb) to get the
2009 _destination_ dev/ino, since the rename above can't have
2010 changed those, and `mv' always uses lstat.
2011 We could limit it further by operating
2012 only on non-directories. */
2013 record_file (x->dest_info, dst_name, &src_sb);
2016 return true;
2019 /* FIXME: someday, consider what to do when moving a directory into
2020 itself but when source and destination are on different devices. */
2022 /* This happens when attempting to rename a directory to a
2023 subdirectory of itself. */
2024 if (errno == EINVAL)
2026 /* FIXME: this is a little fragile in that it relies on rename(2)
2027 failing with a specific errno value. Expect problems on
2028 non-POSIX systems. */
2029 error (0, 0, _("cannot move %s to a subdirectory of itself, %s"),
2030 quote_n (0, top_level_src_name),
2031 quote_n (1, top_level_dst_name));
2033 /* Note that there is no need to call forget_created here,
2034 (compare with the other calls in this file) since the
2035 destination directory didn't exist before. */
2037 *copy_into_self = true;
2038 /* FIXME-cleanup: Don't return true here; adjust mv.c accordingly.
2039 The only caller that uses this code (mv.c) ends up setting its
2040 exit status to nonzero when copy_into_self is nonzero. */
2041 return true;
2044 /* WARNING: there probably exist systems for which an inter-device
2045 rename fails with a value of errno not handled here.
2046 If/as those are reported, add them to the condition below.
2047 If this happens to you, please do the following and send the output
2048 to the bug-reporting address (e.g., in the output of cp --help):
2049 touch k; perl -e 'rename "k","/tmp/k" or print "$!(",$!+0,")\n"'
2050 where your current directory is on one partion and /tmp is the other.
2051 Also, please try to find the E* errno macro name corresponding to
2052 the diagnostic and parenthesized integer, and include that in your
2053 e-mail. One way to do that is to run a command like this
2054 find /usr/include/. -type f \
2055 | xargs grep 'define.*\<E[A-Z]*\>.*\<18\>' /dev/null
2056 where you'd replace `18' with the integer in parentheses that
2057 was output from the perl one-liner above.
2058 If necessary, of course, change `/tmp' to some other directory. */
2059 if (errno != EXDEV)
2061 /* There are many ways this can happen due to a race condition.
2062 When something happens between the initial XSTAT and the
2063 subsequent rename, we can get many different types of errors.
2064 For example, if the destination is initially a non-directory
2065 or non-existent, but it is created as a directory, the rename
2066 fails. If two `mv' commands try to rename the same file at
2067 about the same time, one will succeed and the other will fail.
2068 If the permissions on the directory containing the source or
2069 destination file are made too restrictive, the rename will
2070 fail. Etc. */
2071 error (0, errno,
2072 _("cannot move %s to %s"),
2073 quote_n (0, src_name), quote_n (1, dst_name));
2074 forget_created (src_sb.st_ino, src_sb.st_dev);
2075 return false;
2078 /* The rename attempt has failed. Remove any existing destination
2079 file so that a cross-device `mv' acts as if it were really using
2080 the rename syscall. */
2081 if (unlink (dst_name) != 0 && errno != ENOENT)
2083 error (0, errno,
2084 _("inter-device move failed: %s to %s; unable to remove target"),
2085 quote_n (0, src_name), quote_n (1, dst_name));
2086 forget_created (src_sb.st_ino, src_sb.st_dev);
2087 return false;
2090 new_dst = true;
2093 /* If the ownership might change, or if it is a directory (whose
2094 special mode bits may change after the directory is created),
2095 omit some permissions at first, so unauthorized users cannot nip
2096 in before the file is ready. */
2097 dst_mode_bits = (x->set_mode ? x->mode : src_mode) & CHMOD_MODE_BITS;
2098 omitted_permissions =
2099 (dst_mode_bits
2100 & (x->preserve_ownership ? S_IRWXG | S_IRWXO
2101 : S_ISDIR (src_mode) ? S_IWGRP | S_IWOTH
2102 : 0));
2104 delayed_ok = true;
2106 if (x->preserve_security_context)
2108 bool all_errors = !x->data_copy_required || x->require_preserve_context;
2109 bool some_errors = !all_errors && !x->reduce_diagnostics;
2110 security_context_t con;
2112 if (0 <= lgetfilecon (src_name, &con))
2114 if (setfscreatecon (con) < 0)
2116 if (all_errors || (some_errors && !errno_unsupported (errno)))
2117 error (0, errno,
2118 _("failed to set default file creation context to %s"),
2119 quote (con));
2120 if (x->require_preserve_context)
2122 freecon (con);
2123 return false;
2126 freecon (con);
2128 else
2130 if (all_errors || (some_errors && !errno_unsupported (errno)))
2132 error (0, errno,
2133 _("failed to get security context of %s"),
2134 quote (src_name));
2136 if (x->require_preserve_context)
2137 return false;
2141 if (S_ISDIR (src_mode))
2143 struct dir_list *dir;
2145 /* If this directory has been copied before during the
2146 recursion, there is a symbolic link to an ancestor
2147 directory of the symbolic link. It is impossible to
2148 continue to copy this, unless we've got an infinite disk. */
2150 if (is_ancestor (&src_sb, ancestors))
2152 error (0, 0, _("cannot copy cyclic symbolic link %s"),
2153 quote (src_name));
2154 goto un_backup;
2157 /* Insert the current directory in the list of parents. */
2159 dir = alloca (sizeof *dir);
2160 dir->parent = ancestors;
2161 dir->ino = src_sb.st_ino;
2162 dir->dev = src_sb.st_dev;
2164 if (new_dst || !S_ISDIR (dst_sb.st_mode))
2166 /* POSIX says mkdir's behavior is implementation-defined when
2167 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
2168 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
2169 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
2170 if (mkdir (dst_name, dst_mode_bits & ~omitted_permissions) != 0)
2172 error (0, errno, _("cannot create directory %s"),
2173 quote (dst_name));
2174 goto un_backup;
2177 /* We need search and write permissions to the new directory
2178 for writing the directory's contents. Check if these
2179 permissions are there. */
2181 if (lstat (dst_name, &dst_sb) != 0)
2183 error (0, errno, _("cannot stat %s"), quote (dst_name));
2184 goto un_backup;
2186 else if ((dst_sb.st_mode & S_IRWXU) != S_IRWXU)
2188 /* Make the new directory searchable and writable. */
2190 dst_mode = dst_sb.st_mode;
2191 restore_dst_mode = true;
2193 if (lchmod (dst_name, dst_mode | S_IRWXU) != 0)
2195 error (0, errno, _("setting permissions for %s"),
2196 quote (dst_name));
2197 goto un_backup;
2201 /* Record the created directory's inode and device numbers into
2202 the search structure, so that we can avoid copying it again.
2203 Do this only for the first directory that is created for each
2204 source command line argument. */
2205 if (!*first_dir_created_per_command_line_arg)
2207 remember_copied (dst_name, dst_sb.st_ino, dst_sb.st_dev);
2208 *first_dir_created_per_command_line_arg = true;
2211 if (x->verbose)
2212 emit_verbose (src_name, dst_name, NULL);
2215 /* Decide whether to copy the contents of the directory. */
2216 if (x->one_file_system && device != 0 && device != src_sb.st_dev)
2218 /* Here, we are crossing a file system boundary and cp's -x option
2219 is in effect: so don't copy the contents of this directory. */
2221 else
2223 /* Copy the contents of the directory. Don't just return if
2224 this fails -- otherwise, the failure to read a single file
2225 in a source directory would cause the containing destination
2226 directory not to have owner/perms set properly. */
2227 delayed_ok = copy_dir (src_name, dst_name, new_dst, &src_sb, dir, x,
2228 first_dir_created_per_command_line_arg,
2229 copy_into_self);
2232 else if (x->symbolic_link)
2234 dest_is_symlink = true;
2235 if (*src_name != '/')
2237 /* Check that DST_NAME denotes a file in the current directory. */
2238 struct stat dot_sb;
2239 struct stat dst_parent_sb;
2240 char *dst_parent;
2241 bool in_current_dir;
2243 dst_parent = dir_name (dst_name);
2245 in_current_dir = (STREQ (".", dst_parent)
2246 /* If either stat call fails, it's ok not to report
2247 the failure and say dst_name is in the current
2248 directory. Other things will fail later. */
2249 || stat (".", &dot_sb) != 0
2250 || stat (dst_parent, &dst_parent_sb) != 0
2251 || SAME_INODE (dot_sb, dst_parent_sb));
2252 free (dst_parent);
2254 if (! in_current_dir)
2256 error (0, 0,
2257 _("%s: can make relative symbolic links only in current directory"),
2258 quote (dst_name));
2259 goto un_backup;
2262 if (symlink (src_name, dst_name) != 0)
2264 error (0, errno, _("cannot create symbolic link %s to %s"),
2265 quote_n (0, dst_name), quote_n (1, src_name));
2266 goto un_backup;
2270 /* POSIX 2008 states that it is implementation-defined whether
2271 link() on a symlink creates a hard-link to the symlink, or only
2272 to the referent (effectively dereferencing the symlink) (POSIX
2273 2001 required the latter behavior, although many systems provided
2274 the former). Yet cp, invoked with `--link --no-dereference',
2275 should not follow the link. We can approximate the desired
2276 behavior by skipping this hard-link creating block and instead
2277 copying the symlink, via the `S_ISLNK'- copying code below.
2278 LINK_FOLLOWS_SYMLINKS is tri-state; if it is -1, we don't know
2279 how link() behaves, so we use the fallback case for safety.
2281 Note gnulib's linkat module, guarantees that the symlink is not
2282 dereferenced. However its emulation currently doesn't maintain
2283 timestamps or ownership so we only call it when we know the
2284 emulation will not be needed. */
2285 else if (x->hard_link
2286 && !(LINK_FOLLOWS_SYMLINKS && S_ISLNK (src_mode)
2287 && x->dereference == DEREF_NEVER))
2289 if (linkat (AT_FDCWD, src_name, AT_FDCWD, dst_name, 0))
2291 error (0, errno, _("cannot create link %s"), quote (dst_name));
2292 goto un_backup;
2295 else if (S_ISREG (src_mode)
2296 || (x->copy_as_regular && !S_ISLNK (src_mode)))
2298 copied_as_regular = true;
2299 /* POSIX says the permission bits of the source file must be
2300 used as the 3rd argument in the open call. Historical
2301 practice passed all the source mode bits to 'open', but the extra
2302 bits were ignored, so it should be the same either way. */
2303 if (! copy_reg (src_name, dst_name, x, src_mode & S_IRWXUGO,
2304 omitted_permissions, &new_dst, &src_sb))
2305 goto un_backup;
2307 else if (S_ISFIFO (src_mode))
2309 /* Use mknod, rather than mkfifo, because the former preserves
2310 the special mode bits of a fifo on Solaris 10, while mkfifo
2311 does not. But fall back on mkfifo, because on some BSD systems,
2312 mknod always fails when asked to create a FIFO. */
2313 if (mknod (dst_name, src_mode & ~omitted_permissions, 0) != 0)
2314 if (mkfifo (dst_name, src_mode & ~S_IFIFO & ~omitted_permissions) != 0)
2316 error (0, errno, _("cannot create fifo %s"), quote (dst_name));
2317 goto un_backup;
2320 else if (S_ISBLK (src_mode) || S_ISCHR (src_mode) || S_ISSOCK (src_mode))
2322 if (mknod (dst_name, src_mode & ~omitted_permissions, src_sb.st_rdev)
2323 != 0)
2325 error (0, errno, _("cannot create special file %s"),
2326 quote (dst_name));
2327 goto un_backup;
2330 else if (S_ISLNK (src_mode))
2332 char *src_link_val = areadlink_with_size (src_name, src_sb.st_size);
2333 dest_is_symlink = true;
2334 if (src_link_val == NULL)
2336 error (0, errno, _("cannot read symbolic link %s"), quote (src_name));
2337 goto un_backup;
2340 if (symlink (src_link_val, dst_name) == 0)
2341 free (src_link_val);
2342 else
2344 int saved_errno = errno;
2345 bool same_link = false;
2346 if (x->update && !new_dst && S_ISLNK (dst_sb.st_mode)
2347 && dst_sb.st_size == strlen (src_link_val))
2349 /* See if the destination is already the desired symlink.
2350 FIXME: This behavior isn't documented, and seems wrong
2351 in some cases, e.g., if the destination symlink has the
2352 wrong ownership, permissions, or time stamps. */
2353 char *dest_link_val =
2354 areadlink_with_size (dst_name, dst_sb.st_size);
2355 if (dest_link_val && STREQ (dest_link_val, src_link_val))
2356 same_link = true;
2357 free (dest_link_val);
2359 free (src_link_val);
2361 if (! same_link)
2363 error (0, saved_errno, _("cannot create symbolic link %s"),
2364 quote (dst_name));
2365 goto un_backup;
2369 if (x->preserve_security_context)
2370 restore_default_fscreatecon_or_die ();
2372 if (x->preserve_ownership)
2374 /* Preserve the owner and group of the just-`copied'
2375 symbolic link, if possible. */
2376 if (HAVE_LCHOWN
2377 && lchown (dst_name, src_sb.st_uid, src_sb.st_gid) != 0
2378 && ! chown_failure_ok (x))
2380 error (0, errno, _("failed to preserve ownership for %s"),
2381 dst_name);
2382 goto un_backup;
2384 else
2386 /* Can't preserve ownership of symlinks.
2387 FIXME: maybe give a warning or even error for symlinks
2388 in directories with the sticky bit set -- there, not
2389 preserving owner/group is a potential security problem. */
2393 else
2395 error (0, 0, _("%s has unknown file type"), quote (src_name));
2396 goto un_backup;
2399 if (command_line_arg && x->dest_info)
2401 /* Now that the destination file is very likely to exist,
2402 add its info to the set. */
2403 struct stat sb;
2404 if (lstat (dst_name, &sb) == 0)
2405 record_file (x->dest_info, dst_name, &sb);
2408 /* If we've just created a hard-link due to cp's --link option,
2409 we're done. */
2410 if (x->hard_link && ! S_ISDIR (src_mode)
2411 && !(LINK_FOLLOWS_SYMLINKS && S_ISLNK (src_mode)
2412 && x->dereference == DEREF_NEVER))
2413 return delayed_ok;
2415 if (copied_as_regular)
2416 return delayed_ok;
2418 /* POSIX says that `cp -p' must restore the following:
2419 - permission bits
2420 - setuid, setgid bits
2421 - owner and group
2422 If it fails to restore any of those, we may give a warning but
2423 the destination must not be removed.
2424 FIXME: implement the above. */
2426 /* Adjust the times (and if possible, ownership) for the copy.
2427 chown turns off set[ug]id bits for non-root,
2428 so do the chmod last. */
2430 if (x->preserve_timestamps)
2432 struct timespec timespec[2];
2433 timespec[0] = get_stat_atime (&src_sb);
2434 timespec[1] = get_stat_mtime (&src_sb);
2436 if ((dest_is_symlink
2437 ? utimens_symlink (dst_name, timespec)
2438 : utimens (dst_name, timespec))
2439 != 0)
2441 error (0, errno, _("preserving times for %s"), quote (dst_name));
2442 if (x->require_preserve)
2443 return false;
2447 /* The operations beyond this point may dereference a symlink. */
2448 if (dest_is_symlink)
2449 return delayed_ok;
2451 /* Avoid calling chown if we know it's not necessary. */
2452 if (x->preserve_ownership
2453 && (new_dst || !SAME_OWNER_AND_GROUP (src_sb, dst_sb)))
2455 switch (set_owner (x, dst_name, -1, &src_sb, new_dst, &dst_sb))
2457 case -1:
2458 return false;
2460 case 0:
2461 src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX);
2462 break;
2466 set_author (dst_name, -1, &src_sb);
2468 if (x->preserve_xattr && ! copy_attr (src_name, -1, dst_name, -1, x)
2469 && x->require_preserve_xattr)
2470 return false;
2472 if (x->preserve_mode || x->move_mode)
2474 if (copy_acl (src_name, -1, dst_name, -1, src_mode) != 0
2475 && x->require_preserve)
2476 return false;
2478 else if (x->set_mode)
2480 if (set_acl (dst_name, -1, x->mode) != 0)
2481 return false;
2483 else
2485 if (omitted_permissions)
2487 omitted_permissions &= ~ cached_umask ();
2489 if (omitted_permissions && !restore_dst_mode)
2491 /* Permissions were deliberately omitted when the file
2492 was created due to security concerns. See whether
2493 they need to be re-added now. It'd be faster to omit
2494 the lstat, but deducing the current destination mode
2495 is tricky in the presence of implementation-defined
2496 rules for special mode bits. */
2497 if (new_dst && lstat (dst_name, &dst_sb) != 0)
2499 error (0, errno, _("cannot stat %s"), quote (dst_name));
2500 return false;
2502 dst_mode = dst_sb.st_mode;
2503 if (omitted_permissions & ~dst_mode)
2504 restore_dst_mode = true;
2508 if (restore_dst_mode)
2510 if (lchmod (dst_name, dst_mode | omitted_permissions) != 0)
2512 error (0, errno, _("preserving permissions for %s"),
2513 quote (dst_name));
2514 if (x->require_preserve)
2515 return false;
2520 return delayed_ok;
2522 un_backup:
2524 if (x->preserve_security_context)
2525 restore_default_fscreatecon_or_die ();
2527 /* We have failed to create the destination file.
2528 If we've just added a dev/ino entry via the remember_copied
2529 call above (i.e., unless we've just failed to create a hard link),
2530 remove the entry associating the source dev/ino with the
2531 destination file name, so we don't try to `preserve' a link
2532 to a file we didn't create. */
2533 if (earlier_file == NULL)
2534 forget_created (src_sb.st_ino, src_sb.st_dev);
2536 if (dst_backup)
2538 if (rename (dst_backup, dst_name) != 0)
2539 error (0, errno, _("cannot un-backup %s"), quote (dst_name));
2540 else
2542 if (x->verbose)
2543 printf (_("%s -> %s (unbackup)\n"),
2544 quote_n (0, dst_backup), quote_n (1, dst_name));
2547 return false;
2550 static bool _GL_ATTRIBUTE_PURE
2551 valid_options (const struct cp_options *co)
2553 assert (co != NULL);
2554 assert (VALID_BACKUP_TYPE (co->backup_type));
2555 assert (VALID_SPARSE_MODE (co->sparse_mode));
2556 assert (VALID_REFLINK_MODE (co->reflink_mode));
2557 assert (!(co->hard_link && co->symbolic_link));
2558 assert (!
2559 (co->reflink_mode == REFLINK_ALWAYS
2560 && co->sparse_mode != SPARSE_AUTO));
2561 return true;
2564 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
2565 any type. NONEXISTENT_DST should be true if the file DST_NAME
2566 is known not to exist (e.g., because its parent directory was just
2567 created); NONEXISTENT_DST should be false if DST_NAME might already
2568 exist. OPTIONS is ... FIXME-describe
2569 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
2570 same as) DST_NAME; otherwise, set clear it.
2571 Return true if successful. */
2573 extern bool
2574 copy (char const *src_name, char const *dst_name,
2575 bool nonexistent_dst, const struct cp_options *options,
2576 bool *copy_into_self, bool *rename_succeeded)
2578 assert (valid_options (options));
2580 /* Record the file names: they're used in case of error, when copying
2581 a directory into itself. I don't like to make these tools do *any*
2582 extra work in the common case when that work is solely to handle
2583 exceptional cases, but in this case, I don't see a way to derive the
2584 top level source and destination directory names where they're used.
2585 An alternative is to use COPY_INTO_SELF and print the diagnostic
2586 from every caller -- but I don't want to do that. */
2587 top_level_src_name = src_name;
2588 top_level_dst_name = dst_name;
2590 bool first_dir_created_per_command_line_arg = false;
2591 return copy_internal (src_name, dst_name, nonexistent_dst, 0, NULL,
2592 options, true,
2593 &first_dir_created_per_command_line_arg,
2594 copy_into_self, rename_succeeded);
2597 /* Set *X to the default options for a value of type struct cp_options. */
2599 extern void
2600 cp_options_default (struct cp_options *x)
2602 memset (x, 0, sizeof *x);
2603 #ifdef PRIV_FILE_CHOWN
2605 priv_set_t *pset = priv_allocset ();
2606 if (!pset)
2607 xalloc_die ();
2608 if (getppriv (PRIV_EFFECTIVE, pset) == 0)
2610 x->chown_privileges = priv_ismember (pset, PRIV_FILE_CHOWN);
2611 x->owner_privileges = priv_ismember (pset, PRIV_FILE_OWNER);
2613 priv_freeset (pset);
2615 #else
2616 x->chown_privileges = x->owner_privileges = (geteuid () == 0);
2617 #endif
2620 /* Return true if it's OK for chown to fail, where errno is
2621 the error number that chown failed with and X is the copying
2622 option set. */
2624 extern bool
2625 chown_failure_ok (struct cp_options const *x)
2627 /* If non-root uses -p, it's ok if we can't preserve ownership.
2628 But root probably wants to know, e.g. if NFS disallows it,
2629 or if the target system doesn't support file ownership. */
2631 return ((errno == EPERM || errno == EINVAL) && !x->chown_privileges);
2634 /* Similarly, return true if it's OK for chmod and similar operations
2635 to fail, where errno is the error number that chmod failed with and
2636 X is the copying option set. */
2638 static bool
2639 owner_failure_ok (struct cp_options const *x)
2641 return ((errno == EPERM || errno == EINVAL) && !x->owner_privileges);
2644 /* Return the user's umask, caching the result. */
2646 extern mode_t
2647 cached_umask (void)
2649 static mode_t mask = (mode_t) -1;
2650 if (mask == (mode_t) -1)
2652 mask = umask (0);
2653 umask (mask);
2655 return mask;