build: merge in bootstrap changes from gnulib
[coreutils.git] / src / copy.c
blobbc4d7bd33596fb9f40d92d2ff1300f7484ea6231
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
955 omitted_permissions = 0;
958 if (dest_desc < 0)
960 error (0, dest_errno, _("cannot create regular file %s"),
961 quote (dst_name));
962 return_val = false;
963 goto close_src_desc;
966 if (fstat (dest_desc, &sb) != 0)
968 error (0, errno, _("cannot fstat %s"), quote (dst_name));
969 return_val = false;
970 goto close_src_and_dst_desc;
973 /* --attributes-only overrides --reflink. */
974 if (data_copy_required && x->reflink_mode)
976 bool clone_ok = clone_file (dest_desc, source_desc) == 0;
977 if (clone_ok || x->reflink_mode == REFLINK_ALWAYS)
979 if (!clone_ok)
981 error (0, errno, _("failed to clone %s from %s"),
982 quote_n (0, dst_name), quote_n (1, src_name));
983 return_val = false;
984 goto close_src_and_dst_desc;
986 data_copy_required = false;
990 if (data_copy_required)
992 typedef uintptr_t word;
994 /* Choose a suitable buffer size; it may be adjusted later. */
995 size_t buf_alignment = lcm (getpagesize (), sizeof (word));
996 size_t buf_alignment_slop = sizeof (word) + buf_alignment - 1;
997 size_t buf_size = io_blksize (sb);
999 /* Deal with sparse files. */
1000 bool make_holes = false;
1001 bool sparse_src = false;
1003 if (S_ISREG (sb.st_mode))
1005 /* Even with --sparse=always, try to create holes only
1006 if the destination is a regular file. */
1007 if (x->sparse_mode == SPARSE_ALWAYS)
1008 make_holes = true;
1010 /* Use a heuristic to determine whether SRC_NAME contains any sparse
1011 blocks. If the file has fewer blocks than would normally be
1012 needed for a file of its size, then at least one of the blocks in
1013 the file is a hole. */
1014 sparse_src = is_probably_sparse (&src_open_sb);
1015 if (x->sparse_mode == SPARSE_AUTO && sparse_src)
1016 make_holes = true;
1019 /* If not making a sparse file, try to use a more-efficient
1020 buffer size. */
1021 if (! make_holes)
1023 /* Compute the least common multiple of the input and output
1024 buffer sizes, adjusting for outlandish values. */
1025 size_t blcm_max = MIN (SIZE_MAX, SSIZE_MAX) - buf_alignment_slop;
1026 size_t blcm = buffer_lcm (io_blksize (src_open_sb), buf_size,
1027 blcm_max);
1029 /* Do not bother with a buffer larger than the input file, plus one
1030 byte to make sure the file has not grown while reading it. */
1031 if (S_ISREG (src_open_sb.st_mode) && src_open_sb.st_size < buf_size)
1032 buf_size = src_open_sb.st_size + 1;
1034 /* However, stick with a block size that is a positive multiple of
1035 blcm, overriding the above adjustments. Watch out for
1036 overflow. */
1037 buf_size += blcm - 1;
1038 buf_size -= buf_size % blcm;
1039 if (buf_size == 0 || blcm_max < buf_size)
1040 buf_size = blcm;
1043 /* Make a buffer with space for a sentinel at the end. */
1044 buf_alloc = xmalloc (buf_size + buf_alignment_slop);
1045 buf = ptr_align (buf_alloc, buf_alignment);
1047 if (sparse_src)
1049 bool normal_copy_required;
1051 /* Perform an efficient extent-based copy, falling back to the
1052 standard copy only if the initial extent scan fails. If the
1053 '--sparse=never' option is specified, write all data but use
1054 any extents to read more efficiently. */
1055 if (extent_copy (source_desc, dest_desc, buf, buf_size,
1056 src_open_sb.st_size,
1057 S_ISREG (sb.st_mode) ? x->sparse_mode : SPARSE_NEVER,
1058 src_name, dst_name, &normal_copy_required))
1059 goto preserve_metadata;
1061 if (! normal_copy_required)
1063 return_val = false;
1064 goto close_src_and_dst_desc;
1068 off_t n_read;
1069 bool wrote_hole_at_eof;
1070 if ( ! sparse_copy (source_desc, dest_desc, buf, buf_size,
1071 make_holes, src_name, dst_name,
1072 UINTMAX_MAX, &n_read,
1073 &wrote_hole_at_eof)
1074 || (wrote_hole_at_eof &&
1075 ftruncate (dest_desc, n_read) < 0))
1077 error (0, errno, _("failed to extend %s"), quote (dst_name));
1078 return_val = false;
1079 goto close_src_and_dst_desc;
1083 preserve_metadata:
1084 if (x->preserve_timestamps)
1086 struct timespec timespec[2];
1087 timespec[0] = get_stat_atime (src_sb);
1088 timespec[1] = get_stat_mtime (src_sb);
1090 if (fdutimens (dest_desc, dst_name, timespec) != 0)
1092 error (0, errno, _("preserving times for %s"), quote (dst_name));
1093 if (x->require_preserve)
1095 return_val = false;
1096 goto close_src_and_dst_desc;
1101 /* Set ownership before xattrs as changing owners will
1102 clear capabilities. */
1103 if (x->preserve_ownership && ! SAME_OWNER_AND_GROUP (*src_sb, sb))
1105 switch (set_owner (x, dst_name, dest_desc, src_sb, *new_dst, &sb))
1107 case -1:
1108 return_val = false;
1109 goto close_src_and_dst_desc;
1111 case 0:
1112 src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX);
1113 break;
1117 /* To allow copying xattrs on read-only files, temporarily chmod u+rw.
1118 This workaround is required as an inode permission check is done
1119 by xattr_permission() in fs/xattr.c of the GNU/Linux kernel tree. */
1120 if (x->preserve_xattr)
1122 bool access_changed = false;
1124 if (!(sb.st_mode & S_IWUSR) && geteuid () != 0)
1125 access_changed = fchmod_or_lchmod (dest_desc, dst_name, 0600) == 0;
1127 if (!copy_attr (src_name, source_desc, dst_name, dest_desc, x)
1128 && x->require_preserve_xattr)
1129 return_val = false;
1131 if (access_changed)
1132 fchmod_or_lchmod (dest_desc, dst_name, dst_mode & ~omitted_permissions);
1135 set_author (dst_name, dest_desc, src_sb);
1137 if (x->preserve_mode || x->move_mode)
1139 if (copy_acl (src_name, source_desc, dst_name, dest_desc, src_mode) != 0
1140 && x->require_preserve)
1141 return_val = false;
1143 else if (x->set_mode)
1145 if (set_acl (dst_name, dest_desc, x->mode) != 0)
1146 return_val = false;
1148 else if (omitted_permissions)
1150 omitted_permissions &= ~ cached_umask ();
1151 if (omitted_permissions
1152 && fchmod_or_lchmod (dest_desc, dst_name, dst_mode) != 0)
1154 error (0, errno, _("preserving permissions for %s"),
1155 quote (dst_name));
1156 if (x->require_preserve)
1157 return_val = false;
1161 close_src_and_dst_desc:
1162 if (close (dest_desc) < 0)
1164 error (0, errno, _("closing %s"), quote (dst_name));
1165 return_val = false;
1167 close_src_desc:
1168 if (close (source_desc) < 0)
1170 error (0, errno, _("closing %s"), quote (src_name));
1171 return_val = false;
1174 free (buf_alloc);
1175 free (name_alloc);
1176 return return_val;
1179 /* Return true if it's ok that the source and destination
1180 files are the `same' by some measure. The goal is to avoid
1181 making the `copy' operation remove both copies of the file
1182 in that case, while still allowing the user to e.g., move or
1183 copy a regular file onto a symlink that points to it.
1184 Try to minimize the cost of this function in the common case.
1185 Set *RETURN_NOW if we've determined that the caller has no more
1186 work to do and should return successfully, right away.
1188 Set *UNLINK_SRC if we've determined that the caller wants to do
1189 `rename (a, b)' where `a' and `b' are distinct hard links to the same
1190 file. In that case, the caller should try to unlink `a' and then return
1191 successfully. Ideally, we wouldn't have to do that, and we'd be
1192 able to rely on rename to remove the source file. However, POSIX
1193 mistakenly requires that such a rename call do *nothing* and return
1194 successfully. */
1196 static bool
1197 same_file_ok (char const *src_name, struct stat const *src_sb,
1198 char const *dst_name, struct stat const *dst_sb,
1199 const struct cp_options *x, bool *return_now, bool *unlink_src)
1201 const struct stat *src_sb_link;
1202 const struct stat *dst_sb_link;
1203 struct stat tmp_dst_sb;
1204 struct stat tmp_src_sb;
1206 bool same_link;
1207 bool same = SAME_INODE (*src_sb, *dst_sb);
1209 *return_now = false;
1210 *unlink_src = false;
1212 /* FIXME: this should (at the very least) be moved into the following
1213 if-block. More likely, it should be removed, because it inhibits
1214 making backups. But removing it will result in a change in behavior
1215 that will probably have to be documented -- and tests will have to
1216 be updated. */
1217 if (same && x->hard_link)
1219 *return_now = true;
1220 return true;
1223 if (x->dereference == DEREF_NEVER)
1225 same_link = same;
1227 /* If both the source and destination files are symlinks (and we'll
1228 know this here IFF preserving symlinks), then it's ok -- as long
1229 as they are distinct. */
1230 if (S_ISLNK (src_sb->st_mode) && S_ISLNK (dst_sb->st_mode))
1231 return ! same_name (src_name, dst_name);
1233 src_sb_link = src_sb;
1234 dst_sb_link = dst_sb;
1236 else
1238 if (!same)
1239 return true;
1241 if (lstat (dst_name, &tmp_dst_sb) != 0
1242 || lstat (src_name, &tmp_src_sb) != 0)
1243 return true;
1245 src_sb_link = &tmp_src_sb;
1246 dst_sb_link = &tmp_dst_sb;
1248 same_link = SAME_INODE (*src_sb_link, *dst_sb_link);
1250 /* If both are symlinks, then it's ok, but only if the destination
1251 will be unlinked before being opened. This is like the test
1252 above, but with the addition of the unlink_dest_before_opening
1253 conjunct because otherwise, with two symlinks to the same target,
1254 we'd end up truncating the source file. */
1255 if (S_ISLNK (src_sb_link->st_mode) && S_ISLNK (dst_sb_link->st_mode)
1256 && x->unlink_dest_before_opening)
1257 return true;
1260 /* The backup code ensures there's a copy, so it's usually ok to
1261 remove any destination file. One exception is when both
1262 source and destination are the same directory entry. In that
1263 case, moving the destination file aside (in making the backup)
1264 would also rename the source file and result in an error. */
1265 if (x->backup_type != no_backups)
1267 if (!same_link)
1269 /* In copy mode when dereferencing symlinks, if the source is a
1270 symlink and the dest is not, then backing up the destination
1271 (moving it aside) would make it a dangling symlink, and the
1272 subsequent attempt to open it in copy_reg would fail with
1273 a misleading diagnostic. Avoid that by returning zero in
1274 that case so the caller can make cp (or mv when it has to
1275 resort to reading the source file) fail now. */
1277 /* FIXME-note: even with the following kludge, we can still provoke
1278 the offending diagnostic. It's just a little harder to do :-)
1279 $ rm -f a b c; touch c; ln -s c b; ln -s b a; cp -b a b
1280 cp: cannot open `a' for reading: No such file or directory
1281 That's misleading, since a subsequent `ls' shows that `a'
1282 is still there.
1283 One solution would be to open the source file *before* moving
1284 aside the destination, but that'd involve a big rewrite. */
1285 if ( ! x->move_mode
1286 && x->dereference != DEREF_NEVER
1287 && S_ISLNK (src_sb_link->st_mode)
1288 && ! S_ISLNK (dst_sb_link->st_mode))
1289 return false;
1291 return true;
1294 return ! same_name (src_name, dst_name);
1297 #if 0
1298 /* FIXME: use or remove */
1300 /* If we're making a backup, we'll detect the problem case in
1301 copy_reg because SRC_NAME will no longer exist. Allowing
1302 the test to be deferred lets cp do some useful things.
1303 But when creating hardlinks and SRC_NAME is a symlink
1304 but DST_NAME is not we must test anyway. */
1305 if (x->hard_link
1306 || !S_ISLNK (src_sb_link->st_mode)
1307 || S_ISLNK (dst_sb_link->st_mode))
1308 return true;
1310 if (x->dereference != DEREF_NEVER)
1311 return true;
1312 #endif
1314 /* They may refer to the same file if we're in move mode and the
1315 target is a symlink. That is ok, since we remove any existing
1316 destination file before opening it -- via `rename' if they're on
1317 the same file system, via `unlink (DST_NAME)' otherwise.
1318 It's also ok if they're distinct hard links to the same file. */
1319 if (x->move_mode || x->unlink_dest_before_opening)
1321 if (S_ISLNK (dst_sb_link->st_mode))
1322 return true;
1324 if (same_link
1325 && 1 < dst_sb_link->st_nlink
1326 && ! same_name (src_name, dst_name))
1328 if (x->move_mode)
1330 *unlink_src = true;
1331 *return_now = true;
1333 return true;
1337 /* If neither is a symlink, then it's ok as long as they aren't
1338 hard links to the same file. */
1339 if (!S_ISLNK (src_sb_link->st_mode) && !S_ISLNK (dst_sb_link->st_mode))
1341 if (!SAME_INODE (*src_sb_link, *dst_sb_link))
1342 return true;
1344 /* If they are the same file, it's ok if we're making hard links. */
1345 if (x->hard_link)
1347 *return_now = true;
1348 return true;
1352 /* It's ok to remove a destination symlink. But that works only when we
1353 unlink before opening the destination and when the source and destination
1354 files are on the same partition. */
1355 if (x->unlink_dest_before_opening
1356 && S_ISLNK (dst_sb_link->st_mode))
1357 return dst_sb_link->st_dev == src_sb_link->st_dev;
1359 if (x->dereference == DEREF_NEVER)
1361 if ( ! S_ISLNK (src_sb_link->st_mode))
1362 tmp_src_sb = *src_sb_link;
1363 else if (stat (src_name, &tmp_src_sb) != 0)
1364 return true;
1366 if ( ! S_ISLNK (dst_sb_link->st_mode))
1367 tmp_dst_sb = *dst_sb_link;
1368 else if (stat (dst_name, &tmp_dst_sb) != 0)
1369 return true;
1371 if ( ! SAME_INODE (tmp_src_sb, tmp_dst_sb))
1372 return true;
1374 /* FIXME: shouldn't this be testing whether we're making symlinks? */
1375 if (x->hard_link)
1377 *return_now = true;
1378 return true;
1382 return false;
1385 /* Return true if FILE, with mode MODE, is writable in the sense of 'mv'.
1386 Always consider a symbolic link to be writable. */
1387 static bool
1388 writable_destination (char const *file, mode_t mode)
1390 return (S_ISLNK (mode)
1391 || can_write_any_file ()
1392 || euidaccess (file, W_OK) == 0);
1395 static void
1396 overwrite_prompt (char const *dst_name, struct stat const *dst_sb)
1398 if (! writable_destination (dst_name, dst_sb->st_mode))
1400 char perms[12]; /* "-rwxrwxrwx " ls-style modes. */
1401 strmode (dst_sb->st_mode, perms);
1402 perms[10] = '\0';
1403 fprintf (stderr,
1404 _("%s: try to overwrite %s, overriding mode %04lo (%s)? "),
1405 program_name, quote (dst_name),
1406 (unsigned long int) (dst_sb->st_mode & CHMOD_MODE_BITS),
1407 &perms[1]);
1409 else
1411 fprintf (stderr, _("%s: overwrite %s? "),
1412 program_name, quote (dst_name));
1416 /* Initialize the hash table implementing a set of F_triple entries
1417 corresponding to destination files. */
1418 extern void
1419 dest_info_init (struct cp_options *x)
1421 x->dest_info
1422 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
1423 NULL,
1424 triple_hash,
1425 triple_compare,
1426 triple_free);
1429 /* Initialize the hash table implementing a set of F_triple entries
1430 corresponding to source files listed on the command line. */
1431 extern void
1432 src_info_init (struct cp_options *x)
1435 /* Note that we use triple_hash_no_name here.
1436 Contrast with the use of triple_hash above.
1437 That is necessary because a source file may be specified
1438 in many different ways. We want to warn about this
1439 cp a a d/
1440 as well as this:
1441 cp a ./a d/
1443 x->src_info
1444 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
1445 NULL,
1446 triple_hash_no_name,
1447 triple_compare,
1448 triple_free);
1451 /* When effecting a move (e.g., for mv(1)), and given the name DST_NAME
1452 of the destination and a corresponding stat buffer, DST_SB, return
1453 true if the logical `move' operation should _not_ proceed.
1454 Otherwise, return false.
1455 Depending on options specified in X, this code may issue an
1456 interactive prompt asking whether it's ok to overwrite DST_NAME. */
1457 static bool
1458 abandon_move (const struct cp_options *x,
1459 char const *dst_name,
1460 struct stat const *dst_sb)
1462 assert (x->move_mode);
1463 return (x->interactive == I_ALWAYS_NO
1464 || ((x->interactive == I_ASK_USER
1465 || (x->interactive == I_UNSPECIFIED
1466 && x->stdin_tty
1467 && ! writable_destination (dst_name, dst_sb->st_mode)))
1468 && (overwrite_prompt (dst_name, dst_sb), 1)
1469 && ! yesno ()));
1472 /* Print --verbose output on standard output, e.g. `new' -> `old'.
1473 If BACKUP_DST_NAME is non-NULL, then also indicate that it is
1474 the name of a backup file. */
1475 static void
1476 emit_verbose (char const *src, char const *dst, char const *backup_dst_name)
1478 printf ("%s -> %s", quote_n (0, src), quote_n (1, dst));
1479 if (backup_dst_name)
1480 printf (_(" (backup: %s)"), quote (backup_dst_name));
1481 putchar ('\n');
1484 /* A wrapper around "setfscreatecon (NULL)" that exits upon failure. */
1485 static void
1486 restore_default_fscreatecon_or_die (void)
1488 if (setfscreatecon (NULL) != 0)
1489 error (EXIT_FAILURE, errno,
1490 _("failed to restore the default file creation context"));
1493 /* Create a hard link DST_NAME to SRC_NAME, honoring the REPLACE and
1494 VERBOSE settings. Return true upon success. Otherwise, diagnose
1495 the failure and return false.
1496 If SRC_NAME is a symbolic link it will not be followed. If the system
1497 doesn't support hard links to symbolic links, then DST_NAME will
1498 be created as a symbolic link to SRC_NAME. */
1499 static bool
1500 create_hard_link (char const *src_name, char const *dst_name,
1501 bool replace, bool verbose)
1503 /* We want to guarantee that symlinks are not followed. */
1504 bool link_failed = (linkat (AT_FDCWD, src_name, AT_FDCWD, dst_name, 0) != 0);
1506 /* If the link failed because of an existing destination,
1507 remove that file and then call link again. */
1508 if (link_failed && replace && errno == EEXIST)
1510 if (unlink (dst_name) != 0)
1512 error (0, errno, _("cannot remove %s"), quote (dst_name));
1513 return false;
1515 if (verbose)
1516 printf (_("removed %s\n"), quote (dst_name));
1517 link_failed = (linkat (AT_FDCWD, src_name, AT_FDCWD, dst_name, 0) != 0);
1520 if (link_failed)
1522 error (0, errno, _("cannot create hard link %s to %s"),
1523 quote_n (0, dst_name), quote_n (1, src_name));
1524 return false;
1527 return true;
1530 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
1531 any type. NEW_DST should be true if the file DST_NAME cannot
1532 exist because its parent directory was just created; NEW_DST should
1533 be false if DST_NAME might already exist. DEVICE is the device
1534 number of the parent directory, or 0 if the parent of this file is
1535 not known. ANCESTORS points to a linked, null terminated list of
1536 devices and inodes of parent directories of SRC_NAME. COMMAND_LINE_ARG
1537 is true iff SRC_NAME was specified on the command line.
1538 FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG is both input and output.
1539 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
1540 same as) DST_NAME; otherwise, clear it.
1541 Return true if successful. */
1542 static bool
1543 copy_internal (char const *src_name, char const *dst_name,
1544 bool new_dst,
1545 dev_t device,
1546 struct dir_list *ancestors,
1547 const struct cp_options *x,
1548 bool command_line_arg,
1549 bool *first_dir_created_per_command_line_arg,
1550 bool *copy_into_self,
1551 bool *rename_succeeded)
1553 struct stat src_sb;
1554 struct stat dst_sb;
1555 mode_t src_mode;
1556 mode_t dst_mode IF_LINT ( = 0);
1557 mode_t dst_mode_bits;
1558 mode_t omitted_permissions;
1559 bool restore_dst_mode = false;
1560 char *earlier_file = NULL;
1561 char *dst_backup = NULL;
1562 bool backup_succeeded = false;
1563 bool delayed_ok;
1564 bool copied_as_regular = false;
1565 bool dest_is_symlink = false;
1566 bool have_dst_lstat = false;
1568 if (x->move_mode && rename_succeeded)
1569 *rename_succeeded = false;
1571 *copy_into_self = false;
1573 if (XSTAT (x, src_name, &src_sb) != 0)
1575 error (0, errno, _("cannot stat %s"), quote (src_name));
1576 return false;
1579 src_mode = src_sb.st_mode;
1581 if (S_ISDIR (src_mode) && !x->recursive)
1583 error (0, 0, _("omitting directory %s"), quote (src_name));
1584 return false;
1587 /* Detect the case in which the same source file appears more than
1588 once on the command line and no backup option has been selected.
1589 If so, simply warn and don't copy it the second time.
1590 This check is enabled only if x->src_info is non-NULL. */
1591 if (command_line_arg)
1593 if ( ! S_ISDIR (src_sb.st_mode)
1594 && x->backup_type == no_backups
1595 && seen_file (x->src_info, src_name, &src_sb))
1597 error (0, 0, _("warning: source file %s specified more than once"),
1598 quote (src_name));
1599 return true;
1602 record_file (x->src_info, src_name, &src_sb);
1605 if (!new_dst)
1607 /* Regular files can be created by writing through symbolic
1608 links, but other files cannot. So use stat on the
1609 destination when copying a regular file, and lstat otherwise.
1610 However, if we intend to unlink or remove the destination
1611 first, use lstat, since a copy won't actually be made to the
1612 destination in that case. */
1613 bool use_stat =
1614 ((S_ISREG (src_mode)
1615 || (x->copy_as_regular
1616 && ! (S_ISDIR (src_mode) || S_ISLNK (src_mode))))
1617 && ! (x->move_mode || x->symbolic_link || x->hard_link
1618 || x->backup_type != no_backups
1619 || x->unlink_dest_before_opening));
1620 if ((use_stat
1621 ? stat (dst_name, &dst_sb)
1622 : lstat (dst_name, &dst_sb))
1623 != 0)
1625 if (errno != ENOENT)
1627 error (0, errno, _("cannot stat %s"), quote (dst_name));
1628 return false;
1630 else
1632 new_dst = true;
1635 else
1636 { /* Here, we know that dst_name exists, at least to the point
1637 that it is stat'able or lstat'able. */
1638 bool return_now;
1639 bool unlink_src;
1641 have_dst_lstat = !use_stat;
1642 if (! same_file_ok (src_name, &src_sb, dst_name, &dst_sb,
1643 x, &return_now, &unlink_src))
1645 error (0, 0, _("%s and %s are the same file"),
1646 quote_n (0, src_name), quote_n (1, dst_name));
1647 return false;
1650 if (!S_ISDIR (src_mode) && x->update)
1652 /* When preserving time stamps (but not moving within a file
1653 system), don't worry if the destination time stamp is
1654 less than the source merely because of time stamp
1655 truncation. */
1656 int options = ((x->preserve_timestamps
1657 && ! (x->move_mode
1658 && dst_sb.st_dev == src_sb.st_dev))
1659 ? UTIMECMP_TRUNCATE_SOURCE
1660 : 0);
1662 if (0 <= utimecmp (dst_name, &dst_sb, &src_sb, options))
1664 /* We're using --update and the destination is not older
1665 than the source, so do not copy or move. Pretend the
1666 rename succeeded, so the caller (if it's mv) doesn't
1667 end up removing the source file. */
1668 if (rename_succeeded)
1669 *rename_succeeded = true;
1671 /* However, we still must record that we've processed
1672 this src/dest pair, in case this source file is
1673 hard-linked to another one. In that case, we'll use
1674 the mapping information to link the corresponding
1675 destination names. */
1676 earlier_file = remember_copied (dst_name, src_sb.st_ino,
1677 src_sb.st_dev);
1678 if (earlier_file)
1680 /* Note we currently replace DST_NAME unconditionally,
1681 even if it was a newer separate file. */
1682 if (! create_hard_link (earlier_file, dst_name, true,
1683 x->verbose))
1685 goto un_backup;
1689 return true;
1693 /* When there is an existing destination file, we may end up
1694 returning early, and hence not copying/moving the file.
1695 This may be due to an interactive `negative' reply to the
1696 prompt about the existing file. It may also be due to the
1697 use of the --reply=no option.
1699 cp and mv treat -i and -f differently. */
1700 if (x->move_mode)
1702 if (abandon_move (x, dst_name, &dst_sb)
1703 || (unlink_src && unlink (src_name) == 0))
1705 /* Pretend the rename succeeded, so the caller (mv)
1706 doesn't end up removing the source file. */
1707 if (rename_succeeded)
1708 *rename_succeeded = true;
1709 if (unlink_src && x->verbose)
1710 printf (_("removed %s\n"), quote (src_name));
1711 return true;
1713 if (unlink_src)
1715 error (0, errno, _("cannot remove %s"), quote (src_name));
1716 return false;
1719 else
1721 if (! S_ISDIR (src_mode)
1722 && (x->interactive == I_ALWAYS_NO
1723 || (x->interactive == I_ASK_USER
1724 && (overwrite_prompt (dst_name, &dst_sb), 1)
1725 && ! yesno ())))
1726 return true;
1729 if (return_now)
1730 return true;
1732 if (!S_ISDIR (dst_sb.st_mode))
1734 if (S_ISDIR (src_mode))
1736 if (x->move_mode && x->backup_type != no_backups)
1738 /* Moving a directory onto an existing
1739 non-directory is ok only with --backup. */
1741 else
1743 error (0, 0,
1744 _("cannot overwrite non-directory %s with directory %s"),
1745 quote_n (0, dst_name), quote_n (1, src_name));
1746 return false;
1750 /* Don't let the user destroy their data, even if they try hard:
1751 This mv command must fail (likewise for cp):
1752 rm -rf a b c; mkdir a b c; touch a/f b/f; mv a/f b/f c
1753 Otherwise, the contents of b/f would be lost.
1754 In the case of `cp', b/f would be lost if the user simulated
1755 a move using cp and rm.
1756 Note that it works fine if you use --backup=numbered. */
1757 if (command_line_arg
1758 && x->backup_type != numbered_backups
1759 && seen_file (x->dest_info, dst_name, &dst_sb))
1761 error (0, 0,
1762 _("will not overwrite just-created %s with %s"),
1763 quote_n (0, dst_name), quote_n (1, src_name));
1764 return false;
1768 if (!S_ISDIR (src_mode))
1770 if (S_ISDIR (dst_sb.st_mode))
1772 if (x->move_mode && x->backup_type != no_backups)
1774 /* Moving a non-directory onto an existing
1775 directory is ok only with --backup. */
1777 else
1779 error (0, 0,
1780 _("cannot overwrite directory %s with non-directory"),
1781 quote (dst_name));
1782 return false;
1787 if (x->move_mode)
1789 /* Don't allow user to move a directory onto a non-directory. */
1790 if (S_ISDIR (src_sb.st_mode) && !S_ISDIR (dst_sb.st_mode)
1791 && x->backup_type == no_backups)
1793 error (0, 0,
1794 _("cannot move directory onto non-directory: %s -> %s"),
1795 quote_n (0, src_name), quote_n (0, dst_name));
1796 return false;
1800 if (x->backup_type != no_backups
1801 /* Don't try to back up a destination if the last
1802 component of src_name is "." or "..". */
1803 && ! dot_or_dotdot (last_component (src_name))
1804 /* Create a backup of each destination directory in move mode,
1805 but not in copy mode. FIXME: it might make sense to add an
1806 option to suppress backup creation also for move mode.
1807 That would let one use mv to merge new content into an
1808 existing hierarchy. */
1809 && (x->move_mode || ! S_ISDIR (dst_sb.st_mode)))
1811 char *tmp_backup = find_backup_file_name (dst_name,
1812 x->backup_type);
1814 /* Detect (and fail) when creating the backup file would
1815 destroy the source file. Before, running the commands
1816 cd /tmp; rm -f a a~; : > a; echo A > a~; cp --b=simple a~ a
1817 would leave two zero-length files: a and a~. */
1818 /* FIXME: but simply change e.g., the final a~ to `./a~'
1819 and the source will still be destroyed. */
1820 if (STREQ (tmp_backup, src_name))
1822 const char *fmt;
1823 fmt = (x->move_mode
1824 ? _("backing up %s would destroy source; %s not moved")
1825 : _("backing up %s would destroy source; %s not copied"));
1826 error (0, 0, fmt,
1827 quote_n (0, dst_name),
1828 quote_n (1, src_name));
1829 free (tmp_backup);
1830 return false;
1833 /* FIXME: use fts:
1834 Using alloca for a file name that may be arbitrarily
1835 long is not recommended. In fact, even forming such a name
1836 should be discouraged. Eventually, this code will be rewritten
1837 to use fts, so using alloca here will be less of a problem. */
1838 ASSIGN_STRDUPA (dst_backup, tmp_backup);
1839 free (tmp_backup);
1840 if (rename (dst_name, dst_backup) != 0)
1842 if (errno != ENOENT)
1844 error (0, errno, _("cannot backup %s"), quote (dst_name));
1845 return false;
1847 else
1849 dst_backup = NULL;
1852 else
1854 backup_succeeded = true;
1856 new_dst = true;
1858 else if (! S_ISDIR (dst_sb.st_mode)
1859 /* Never unlink dst_name when in move mode. */
1860 && ! x->move_mode
1861 && (x->unlink_dest_before_opening
1862 || (x->preserve_links && 1 < dst_sb.st_nlink)
1863 || (x->dereference == DEREF_NEVER
1864 && ! S_ISREG (src_sb.st_mode))
1867 if (unlink (dst_name) != 0 && errno != ENOENT)
1869 error (0, errno, _("cannot remove %s"), quote (dst_name));
1870 return false;
1872 new_dst = true;
1873 if (x->verbose)
1874 printf (_("removed %s\n"), quote (dst_name));
1879 /* Ensure we don't try to copy through a symlink that was
1880 created by a prior call to this function. */
1881 if (command_line_arg
1882 && x->dest_info
1883 && ! x->move_mode
1884 && x->backup_type == no_backups)
1886 bool lstat_ok = true;
1887 struct stat tmp_buf;
1888 struct stat *dst_lstat_sb;
1890 /* If we called lstat above, good: use that data.
1891 Otherwise, call lstat here, in case dst_name is a symlink. */
1892 if (have_dst_lstat)
1893 dst_lstat_sb = &dst_sb;
1894 else
1896 if (lstat (dst_name, &tmp_buf) == 0)
1897 dst_lstat_sb = &tmp_buf;
1898 else
1899 lstat_ok = false;
1902 /* Never copy through a symlink we've just created. */
1903 if (lstat_ok
1904 && S_ISLNK (dst_lstat_sb->st_mode)
1905 && seen_file (x->dest_info, dst_name, dst_lstat_sb))
1907 error (0, 0,
1908 _("will not copy %s through just-created symlink %s"),
1909 quote_n (0, src_name), quote_n (1, dst_name));
1910 return false;
1914 /* If the source is a directory, we don't always create the destination
1915 directory. So --verbose should not announce anything until we're
1916 sure we'll create a directory. */
1917 if (x->verbose && !S_ISDIR (src_mode))
1918 emit_verbose (src_name, dst_name, backup_succeeded ? dst_backup : NULL);
1920 /* Associate the destination file name with the source device and inode
1921 so that if we encounter a matching dev/ino pair in the source tree
1922 we can arrange to create a hard link between the corresponding names
1923 in the destination tree.
1925 When using the --link (-l) option, there is no need to take special
1926 measures, because (barring race conditions) files that are hard-linked
1927 in the source tree will also be hard-linked in the destination tree.
1929 Sometimes, when preserving links, we have to record dev/ino even
1930 though st_nlink == 1:
1931 - when in move_mode, since we may be moving a group of N hard-linked
1932 files (via two or more command line arguments) to a different
1933 partition; the links may be distributed among the command line
1934 arguments (possibly hierarchies) so that the link count of
1935 the final, once-linked source file is reduced to 1 when it is
1936 considered below. But in this case (for mv) we don't need to
1937 incur the expense of recording the dev/ino => name mapping; all we
1938 really need is a lookup, to see if the dev/ino pair has already
1939 been copied.
1940 - when using -H and processing a command line argument;
1941 that command line argument could be a symlink pointing to another
1942 command line argument. With `cp -H --preserve=link', we hard-link
1943 those two destination files.
1944 - likewise for -L except that it applies to all files, not just
1945 command line arguments.
1947 Also, with --recursive, record dev/ino of each command-line directory.
1948 We'll use that info to detect this problem: cp -R dir dir. */
1950 if (x->move_mode && src_sb.st_nlink == 1)
1952 earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev);
1954 else if (x->preserve_links
1955 && !x->hard_link
1956 && (1 < src_sb.st_nlink
1957 || (command_line_arg
1958 && x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
1959 || x->dereference == DEREF_ALWAYS))
1961 earlier_file = remember_copied (dst_name, src_sb.st_ino, src_sb.st_dev);
1963 else if (x->recursive && S_ISDIR (src_mode))
1965 if (command_line_arg)
1966 earlier_file = remember_copied (dst_name, src_sb.st_ino, src_sb.st_dev);
1967 else
1968 earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev);
1971 /* Did we copy this inode somewhere else (in this command line argument)
1972 and therefore this is a second hard link to the inode? */
1974 if (earlier_file)
1976 /* Avoid damaging the destination file system by refusing to preserve
1977 hard-linked directories (which are found at least in Netapp snapshot
1978 directories). */
1979 if (S_ISDIR (src_mode))
1981 /* If src_name and earlier_file refer to the same directory entry,
1982 then warn about copying a directory into itself. */
1983 if (same_name (src_name, earlier_file))
1985 error (0, 0, _("cannot copy a directory, %s, into itself, %s"),
1986 quote_n (0, top_level_src_name),
1987 quote_n (1, top_level_dst_name));
1988 *copy_into_self = true;
1989 goto un_backup;
1991 else if (x->dereference == DEREF_ALWAYS)
1993 /* This happens when e.g., encountering a directory for the
1994 second or subsequent time via symlinks when cp is invoked
1995 with -R and -L. E.g.,
1996 rm -rf a b c d; mkdir a b c d; ln -s ../c a; ln -s ../c b;
1997 cp -RL a b d
2000 else
2002 error (0, 0, _("will not create hard link %s to directory %s"),
2003 quote_n (0, dst_name), quote_n (1, earlier_file));
2004 goto un_backup;
2007 else
2009 if (! create_hard_link (earlier_file, dst_name, true, x->verbose))
2010 goto un_backup;
2012 return true;
2016 if (x->move_mode)
2018 if (rename (src_name, dst_name) == 0)
2020 if (x->verbose && S_ISDIR (src_mode))
2021 emit_verbose (src_name, dst_name,
2022 backup_succeeded ? dst_backup : NULL);
2024 if (rename_succeeded)
2025 *rename_succeeded = true;
2027 if (command_line_arg)
2029 /* Record destination dev/ino/name, so that if we are asked
2030 to overwrite that file again, we can detect it and fail. */
2031 /* It's fine to use the _source_ stat buffer (src_sb) to get the
2032 _destination_ dev/ino, since the rename above can't have
2033 changed those, and `mv' always uses lstat.
2034 We could limit it further by operating
2035 only on non-directories. */
2036 record_file (x->dest_info, dst_name, &src_sb);
2039 return true;
2042 /* FIXME: someday, consider what to do when moving a directory into
2043 itself but when source and destination are on different devices. */
2045 /* This happens when attempting to rename a directory to a
2046 subdirectory of itself. */
2047 if (errno == EINVAL)
2049 /* FIXME: this is a little fragile in that it relies on rename(2)
2050 failing with a specific errno value. Expect problems on
2051 non-POSIX systems. */
2052 error (0, 0, _("cannot move %s to a subdirectory of itself, %s"),
2053 quote_n (0, top_level_src_name),
2054 quote_n (1, top_level_dst_name));
2056 /* Note that there is no need to call forget_created here,
2057 (compare with the other calls in this file) since the
2058 destination directory didn't exist before. */
2060 *copy_into_self = true;
2061 /* FIXME-cleanup: Don't return true here; adjust mv.c accordingly.
2062 The only caller that uses this code (mv.c) ends up setting its
2063 exit status to nonzero when copy_into_self is nonzero. */
2064 return true;
2067 /* WARNING: there probably exist systems for which an inter-device
2068 rename fails with a value of errno not handled here.
2069 If/as those are reported, add them to the condition below.
2070 If this happens to you, please do the following and send the output
2071 to the bug-reporting address (e.g., in the output of cp --help):
2072 touch k; perl -e 'rename "k","/tmp/k" or print "$!(",$!+0,")\n"'
2073 where your current directory is on one partion and /tmp is the other.
2074 Also, please try to find the E* errno macro name corresponding to
2075 the diagnostic and parenthesized integer, and include that in your
2076 e-mail. One way to do that is to run a command like this
2077 find /usr/include/. -type f \
2078 | xargs grep 'define.*\<E[A-Z]*\>.*\<18\>' /dev/null
2079 where you'd replace `18' with the integer in parentheses that
2080 was output from the perl one-liner above.
2081 If necessary, of course, change `/tmp' to some other directory. */
2082 if (errno != EXDEV)
2084 /* There are many ways this can happen due to a race condition.
2085 When something happens between the initial XSTAT and the
2086 subsequent rename, we can get many different types of errors.
2087 For example, if the destination is initially a non-directory
2088 or non-existent, but it is created as a directory, the rename
2089 fails. If two `mv' commands try to rename the same file at
2090 about the same time, one will succeed and the other will fail.
2091 If the permissions on the directory containing the source or
2092 destination file are made too restrictive, the rename will
2093 fail. Etc. */
2094 error (0, errno,
2095 _("cannot move %s to %s"),
2096 quote_n (0, src_name), quote_n (1, dst_name));
2097 forget_created (src_sb.st_ino, src_sb.st_dev);
2098 return false;
2101 /* The rename attempt has failed. Remove any existing destination
2102 file so that a cross-device `mv' acts as if it were really using
2103 the rename syscall. */
2104 if (unlink (dst_name) != 0 && errno != ENOENT)
2106 error (0, errno,
2107 _("inter-device move failed: %s to %s; unable to remove target"),
2108 quote_n (0, src_name), quote_n (1, dst_name));
2109 forget_created (src_sb.st_ino, src_sb.st_dev);
2110 return false;
2113 new_dst = true;
2116 /* If the ownership might change, or if it is a directory (whose
2117 special mode bits may change after the directory is created),
2118 omit some permissions at first, so unauthorized users cannot nip
2119 in before the file is ready. */
2120 dst_mode_bits = (x->set_mode ? x->mode : src_mode) & CHMOD_MODE_BITS;
2121 omitted_permissions =
2122 (dst_mode_bits
2123 & (x->preserve_ownership ? S_IRWXG | S_IRWXO
2124 : S_ISDIR (src_mode) ? S_IWGRP | S_IWOTH
2125 : 0));
2127 delayed_ok = true;
2129 if (x->preserve_security_context)
2131 bool all_errors = !x->data_copy_required || x->require_preserve_context;
2132 bool some_errors = !all_errors && !x->reduce_diagnostics;
2133 security_context_t con;
2135 if (0 <= lgetfilecon (src_name, &con))
2137 if (setfscreatecon (con) < 0)
2139 if (all_errors || (some_errors && !errno_unsupported (errno)))
2140 error (0, errno,
2141 _("failed to set default file creation context to %s"),
2142 quote (con));
2143 if (x->require_preserve_context)
2145 freecon (con);
2146 return false;
2149 freecon (con);
2151 else
2153 if (all_errors || (some_errors && !errno_unsupported (errno)))
2155 error (0, errno,
2156 _("failed to get security context of %s"),
2157 quote (src_name));
2159 if (x->require_preserve_context)
2160 return false;
2164 if (S_ISDIR (src_mode))
2166 struct dir_list *dir;
2168 /* If this directory has been copied before during the
2169 recursion, there is a symbolic link to an ancestor
2170 directory of the symbolic link. It is impossible to
2171 continue to copy this, unless we've got an infinite disk. */
2173 if (is_ancestor (&src_sb, ancestors))
2175 error (0, 0, _("cannot copy cyclic symbolic link %s"),
2176 quote (src_name));
2177 goto un_backup;
2180 /* Insert the current directory in the list of parents. */
2182 dir = alloca (sizeof *dir);
2183 dir->parent = ancestors;
2184 dir->ino = src_sb.st_ino;
2185 dir->dev = src_sb.st_dev;
2187 if (new_dst || !S_ISDIR (dst_sb.st_mode))
2189 /* POSIX says mkdir's behavior is implementation-defined when
2190 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
2191 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
2192 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
2193 if (mkdir (dst_name, dst_mode_bits & ~omitted_permissions) != 0)
2195 error (0, errno, _("cannot create directory %s"),
2196 quote (dst_name));
2197 goto un_backup;
2200 /* We need search and write permissions to the new directory
2201 for writing the directory's contents. Check if these
2202 permissions are there. */
2204 if (lstat (dst_name, &dst_sb) != 0)
2206 error (0, errno, _("cannot stat %s"), quote (dst_name));
2207 goto un_backup;
2209 else if ((dst_sb.st_mode & S_IRWXU) != S_IRWXU)
2211 /* Make the new directory searchable and writable. */
2213 dst_mode = dst_sb.st_mode;
2214 restore_dst_mode = true;
2216 if (lchmod (dst_name, dst_mode | S_IRWXU) != 0)
2218 error (0, errno, _("setting permissions for %s"),
2219 quote (dst_name));
2220 goto un_backup;
2224 /* Record the created directory's inode and device numbers into
2225 the search structure, so that we can avoid copying it again.
2226 Do this only for the first directory that is created for each
2227 source command line argument. */
2228 if (!*first_dir_created_per_command_line_arg)
2230 remember_copied (dst_name, dst_sb.st_ino, dst_sb.st_dev);
2231 *first_dir_created_per_command_line_arg = true;
2234 if (x->verbose)
2235 emit_verbose (src_name, dst_name, NULL);
2237 else
2239 omitted_permissions = 0;
2242 /* Decide whether to copy the contents of the directory. */
2243 if (x->one_file_system && device != 0 && device != src_sb.st_dev)
2245 /* Here, we are crossing a file system boundary and cp's -x option
2246 is in effect: so don't copy the contents of this directory. */
2248 else
2250 /* Copy the contents of the directory. Don't just return if
2251 this fails -- otherwise, the failure to read a single file
2252 in a source directory would cause the containing destination
2253 directory not to have owner/perms set properly. */
2254 delayed_ok = copy_dir (src_name, dst_name, new_dst, &src_sb, dir, x,
2255 first_dir_created_per_command_line_arg,
2256 copy_into_self);
2259 else if (x->symbolic_link)
2261 dest_is_symlink = true;
2262 if (*src_name != '/')
2264 /* Check that DST_NAME denotes a file in the current directory. */
2265 struct stat dot_sb;
2266 struct stat dst_parent_sb;
2267 char *dst_parent;
2268 bool in_current_dir;
2270 dst_parent = dir_name (dst_name);
2272 in_current_dir = (STREQ (".", dst_parent)
2273 /* If either stat call fails, it's ok not to report
2274 the failure and say dst_name is in the current
2275 directory. Other things will fail later. */
2276 || stat (".", &dot_sb) != 0
2277 || stat (dst_parent, &dst_parent_sb) != 0
2278 || SAME_INODE (dot_sb, dst_parent_sb));
2279 free (dst_parent);
2281 if (! in_current_dir)
2283 error (0, 0,
2284 _("%s: can make relative symbolic links only in current directory"),
2285 quote (dst_name));
2286 goto un_backup;
2289 if (symlink (src_name, dst_name) != 0)
2291 error (0, errno, _("cannot create symbolic link %s to %s"),
2292 quote_n (0, dst_name), quote_n (1, src_name));
2293 goto un_backup;
2297 /* POSIX 2008 states that it is implementation-defined whether
2298 link() on a symlink creates a hard-link to the symlink, or only
2299 to the referent (effectively dereferencing the symlink) (POSIX
2300 2001 required the latter behavior, although many systems provided
2301 the former). Yet cp, invoked with `--link --no-dereference',
2302 should not follow the link. We can approximate the desired
2303 behavior by skipping this hard-link creating block and instead
2304 copying the symlink, via the `S_ISLNK'- copying code below.
2305 LINK_FOLLOWS_SYMLINKS is tri-state; if it is -1, we don't know
2306 how link() behaves, so we use the fallback case for safety.
2308 Note gnulib's linkat module, guarantees that the symlink is not
2309 dereferenced. However its emulation currently doesn't maintain
2310 timestamps or ownership so we only call it when we know the
2311 emulation will not be needed. */
2312 else if (x->hard_link
2313 && !(LINK_FOLLOWS_SYMLINKS && S_ISLNK (src_mode)
2314 && x->dereference == DEREF_NEVER))
2316 if (! create_hard_link (src_name, dst_name, false, false))
2317 goto un_backup;
2319 else if (S_ISREG (src_mode)
2320 || (x->copy_as_regular && !S_ISLNK (src_mode)))
2322 copied_as_regular = true;
2323 /* POSIX says the permission bits of the source file must be
2324 used as the 3rd argument in the open call. Historical
2325 practice passed all the source mode bits to 'open', but the extra
2326 bits were ignored, so it should be the same either way. */
2327 if (! copy_reg (src_name, dst_name, x, src_mode & S_IRWXUGO,
2328 omitted_permissions, &new_dst, &src_sb))
2329 goto un_backup;
2331 else if (S_ISFIFO (src_mode))
2333 /* Use mknod, rather than mkfifo, because the former preserves
2334 the special mode bits of a fifo on Solaris 10, while mkfifo
2335 does not. But fall back on mkfifo, because on some BSD systems,
2336 mknod always fails when asked to create a FIFO. */
2337 if (mknod (dst_name, src_mode & ~omitted_permissions, 0) != 0)
2338 if (mkfifo (dst_name, src_mode & ~S_IFIFO & ~omitted_permissions) != 0)
2340 error (0, errno, _("cannot create fifo %s"), quote (dst_name));
2341 goto un_backup;
2344 else if (S_ISBLK (src_mode) || S_ISCHR (src_mode) || S_ISSOCK (src_mode))
2346 if (mknod (dst_name, src_mode & ~omitted_permissions, src_sb.st_rdev)
2347 != 0)
2349 error (0, errno, _("cannot create special file %s"),
2350 quote (dst_name));
2351 goto un_backup;
2354 else if (S_ISLNK (src_mode))
2356 char *src_link_val = areadlink_with_size (src_name, src_sb.st_size);
2357 dest_is_symlink = true;
2358 if (src_link_val == NULL)
2360 error (0, errno, _("cannot read symbolic link %s"), quote (src_name));
2361 goto un_backup;
2364 if (symlink (src_link_val, dst_name) == 0)
2365 free (src_link_val);
2366 else
2368 int saved_errno = errno;
2369 bool same_link = false;
2370 if (x->update && !new_dst && S_ISLNK (dst_sb.st_mode)
2371 && dst_sb.st_size == strlen (src_link_val))
2373 /* See if the destination is already the desired symlink.
2374 FIXME: This behavior isn't documented, and seems wrong
2375 in some cases, e.g., if the destination symlink has the
2376 wrong ownership, permissions, or time stamps. */
2377 char *dest_link_val =
2378 areadlink_with_size (dst_name, dst_sb.st_size);
2379 if (dest_link_val && STREQ (dest_link_val, src_link_val))
2380 same_link = true;
2381 free (dest_link_val);
2383 free (src_link_val);
2385 if (! same_link)
2387 error (0, saved_errno, _("cannot create symbolic link %s"),
2388 quote (dst_name));
2389 goto un_backup;
2393 if (x->preserve_security_context)
2394 restore_default_fscreatecon_or_die ();
2396 if (x->preserve_ownership)
2398 /* Preserve the owner and group of the just-`copied'
2399 symbolic link, if possible. */
2400 if (HAVE_LCHOWN
2401 && lchown (dst_name, src_sb.st_uid, src_sb.st_gid) != 0
2402 && ! chown_failure_ok (x))
2404 error (0, errno, _("failed to preserve ownership for %s"),
2405 dst_name);
2406 goto un_backup;
2408 else
2410 /* Can't preserve ownership of symlinks.
2411 FIXME: maybe give a warning or even error for symlinks
2412 in directories with the sticky bit set -- there, not
2413 preserving owner/group is a potential security problem. */
2417 else
2419 error (0, 0, _("%s has unknown file type"), quote (src_name));
2420 goto un_backup;
2423 if (command_line_arg && x->dest_info)
2425 /* Now that the destination file is very likely to exist,
2426 add its info to the set. */
2427 struct stat sb;
2428 if (lstat (dst_name, &sb) == 0)
2429 record_file (x->dest_info, dst_name, &sb);
2432 /* If we've just created a hard-link due to cp's --link option,
2433 we're done. */
2434 if (x->hard_link && ! S_ISDIR (src_mode)
2435 && !(LINK_FOLLOWS_SYMLINKS && S_ISLNK (src_mode)
2436 && x->dereference == DEREF_NEVER))
2437 return delayed_ok;
2439 if (copied_as_regular)
2440 return delayed_ok;
2442 /* POSIX says that `cp -p' must restore the following:
2443 - permission bits
2444 - setuid, setgid bits
2445 - owner and group
2446 If it fails to restore any of those, we may give a warning but
2447 the destination must not be removed.
2448 FIXME: implement the above. */
2450 /* Adjust the times (and if possible, ownership) for the copy.
2451 chown turns off set[ug]id bits for non-root,
2452 so do the chmod last. */
2454 if (x->preserve_timestamps)
2456 struct timespec timespec[2];
2457 timespec[0] = get_stat_atime (&src_sb);
2458 timespec[1] = get_stat_mtime (&src_sb);
2460 if ((dest_is_symlink
2461 ? utimens_symlink (dst_name, timespec)
2462 : utimens (dst_name, timespec))
2463 != 0)
2465 error (0, errno, _("preserving times for %s"), quote (dst_name));
2466 if (x->require_preserve)
2467 return false;
2471 /* The operations beyond this point may dereference a symlink. */
2472 if (dest_is_symlink)
2473 return delayed_ok;
2475 /* Avoid calling chown if we know it's not necessary. */
2476 if (x->preserve_ownership
2477 && (new_dst || !SAME_OWNER_AND_GROUP (src_sb, dst_sb)))
2479 switch (set_owner (x, dst_name, -1, &src_sb, new_dst, &dst_sb))
2481 case -1:
2482 return false;
2484 case 0:
2485 src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX);
2486 break;
2490 set_author (dst_name, -1, &src_sb);
2492 if (x->preserve_xattr && ! copy_attr (src_name, -1, dst_name, -1, x)
2493 && x->require_preserve_xattr)
2494 return false;
2496 if (x->preserve_mode || x->move_mode)
2498 if (copy_acl (src_name, -1, dst_name, -1, src_mode) != 0
2499 && x->require_preserve)
2500 return false;
2502 else if (x->set_mode)
2504 if (set_acl (dst_name, -1, x->mode) != 0)
2505 return false;
2507 else
2509 if (omitted_permissions)
2511 omitted_permissions &= ~ cached_umask ();
2513 if (omitted_permissions && !restore_dst_mode)
2515 /* Permissions were deliberately omitted when the file
2516 was created due to security concerns. See whether
2517 they need to be re-added now. It'd be faster to omit
2518 the lstat, but deducing the current destination mode
2519 is tricky in the presence of implementation-defined
2520 rules for special mode bits. */
2521 if (new_dst && lstat (dst_name, &dst_sb) != 0)
2523 error (0, errno, _("cannot stat %s"), quote (dst_name));
2524 return false;
2526 dst_mode = dst_sb.st_mode;
2527 if (omitted_permissions & ~dst_mode)
2528 restore_dst_mode = true;
2532 if (restore_dst_mode)
2534 if (lchmod (dst_name, dst_mode | omitted_permissions) != 0)
2536 error (0, errno, _("preserving permissions for %s"),
2537 quote (dst_name));
2538 if (x->require_preserve)
2539 return false;
2544 return delayed_ok;
2546 un_backup:
2548 if (x->preserve_security_context)
2549 restore_default_fscreatecon_or_die ();
2551 /* We have failed to create the destination file.
2552 If we've just added a dev/ino entry via the remember_copied
2553 call above (i.e., unless we've just failed to create a hard link),
2554 remove the entry associating the source dev/ino with the
2555 destination file name, so we don't try to `preserve' a link
2556 to a file we didn't create. */
2557 if (earlier_file == NULL)
2558 forget_created (src_sb.st_ino, src_sb.st_dev);
2560 if (dst_backup)
2562 if (rename (dst_backup, dst_name) != 0)
2563 error (0, errno, _("cannot un-backup %s"), quote (dst_name));
2564 else
2566 if (x->verbose)
2567 printf (_("%s -> %s (unbackup)\n"),
2568 quote_n (0, dst_backup), quote_n (1, dst_name));
2571 return false;
2574 static bool _GL_ATTRIBUTE_PURE
2575 valid_options (const struct cp_options *co)
2577 assert (co != NULL);
2578 assert (VALID_BACKUP_TYPE (co->backup_type));
2579 assert (VALID_SPARSE_MODE (co->sparse_mode));
2580 assert (VALID_REFLINK_MODE (co->reflink_mode));
2581 assert (!(co->hard_link && co->symbolic_link));
2582 assert (!
2583 (co->reflink_mode == REFLINK_ALWAYS
2584 && co->sparse_mode != SPARSE_AUTO));
2585 return true;
2588 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
2589 any type. NONEXISTENT_DST should be true if the file DST_NAME
2590 is known not to exist (e.g., because its parent directory was just
2591 created); NONEXISTENT_DST should be false if DST_NAME might already
2592 exist. OPTIONS is ... FIXME-describe
2593 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
2594 same as) DST_NAME; otherwise, set clear it.
2595 Return true if successful. */
2597 extern bool
2598 copy (char const *src_name, char const *dst_name,
2599 bool nonexistent_dst, const struct cp_options *options,
2600 bool *copy_into_self, bool *rename_succeeded)
2602 assert (valid_options (options));
2604 /* Record the file names: they're used in case of error, when copying
2605 a directory into itself. I don't like to make these tools do *any*
2606 extra work in the common case when that work is solely to handle
2607 exceptional cases, but in this case, I don't see a way to derive the
2608 top level source and destination directory names where they're used.
2609 An alternative is to use COPY_INTO_SELF and print the diagnostic
2610 from every caller -- but I don't want to do that. */
2611 top_level_src_name = src_name;
2612 top_level_dst_name = dst_name;
2614 bool first_dir_created_per_command_line_arg = false;
2615 return copy_internal (src_name, dst_name, nonexistent_dst, 0, NULL,
2616 options, true,
2617 &first_dir_created_per_command_line_arg,
2618 copy_into_self, rename_succeeded);
2621 /* Set *X to the default options for a value of type struct cp_options. */
2623 extern void
2624 cp_options_default (struct cp_options *x)
2626 memset (x, 0, sizeof *x);
2627 #ifdef PRIV_FILE_CHOWN
2629 priv_set_t *pset = priv_allocset ();
2630 if (!pset)
2631 xalloc_die ();
2632 if (getppriv (PRIV_EFFECTIVE, pset) == 0)
2634 x->chown_privileges = priv_ismember (pset, PRIV_FILE_CHOWN);
2635 x->owner_privileges = priv_ismember (pset, PRIV_FILE_OWNER);
2637 priv_freeset (pset);
2639 #else
2640 x->chown_privileges = x->owner_privileges = (geteuid () == 0);
2641 #endif
2644 /* Return true if it's OK for chown to fail, where errno is
2645 the error number that chown failed with and X is the copying
2646 option set. */
2648 extern bool
2649 chown_failure_ok (struct cp_options const *x)
2651 /* If non-root uses -p, it's ok if we can't preserve ownership.
2652 But root probably wants to know, e.g. if NFS disallows it,
2653 or if the target system doesn't support file ownership. */
2655 return ((errno == EPERM || errno == EINVAL) && !x->chown_privileges);
2658 /* Similarly, return true if it's OK for chmod and similar operations
2659 to fail, where errno is the error number that chmod failed with and
2660 X is the copying option set. */
2662 static bool
2663 owner_failure_ok (struct cp_options const *x)
2665 return ((errno == EPERM || errno == EINVAL) && !x->owner_privileges);
2668 /* Return the user's umask, caching the result. */
2670 extern mode_t
2671 cached_umask (void)
2673 static mode_t mask = (mode_t) -1;
2674 if (mask == (mode_t) -1)
2676 mask = umask (0);
2677 umask (mask);
2679 return mask;