build: update gnulib submodule to latest
[coreutils/ericb.git] / src / copy.c
blob9b53127c4556fd7a8341d4660b012804f08abef1
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 "quote.h"
51 #include "same.h"
52 #include "savedir.h"
53 #include "stat-time.h"
54 #include "utimecmp.h"
55 #include "utimens.h"
56 #include "write-any-file.h"
57 #include "areadlink.h"
58 #include "yesno.h"
60 #if USE_XATTR
61 # include <attr/error_context.h>
62 # include <attr/libattr.h>
63 # include <stdarg.h>
64 # include "verror.h"
65 #endif
67 #ifndef HAVE_FCHOWN
68 # define HAVE_FCHOWN false
69 # define fchown(fd, uid, gid) (-1)
70 #endif
72 #ifndef HAVE_LCHOWN
73 # define HAVE_LCHOWN false
74 # define lchown(name, uid, gid) chown (name, uid, gid)
75 #endif
77 #ifndef HAVE_MKFIFO
78 static int
79 rpl_mkfifo (char const *file, mode_t mode)
81 errno = ENOTSUP;
82 return -1;
84 # define mkfifo rpl_mkfifo
85 #endif
87 #ifndef USE_ACL
88 # define USE_ACL 0
89 #endif
91 #define SAME_OWNER(A, B) ((A).st_uid == (B).st_uid)
92 #define SAME_GROUP(A, B) ((A).st_gid == (B).st_gid)
93 #define SAME_OWNER_AND_GROUP(A, B) (SAME_OWNER (A, B) && SAME_GROUP (A, B))
95 struct dir_list
97 struct dir_list *parent;
98 ino_t ino;
99 dev_t dev;
102 /* Initial size of the cp.dest_info hash table. */
103 #define DEST_INFO_INITIAL_CAPACITY 61
105 static bool copy_internal (char const *src_name, char const *dst_name,
106 bool new_dst, dev_t device,
107 struct dir_list *ancestors,
108 const struct cp_options *x,
109 bool command_line_arg,
110 bool *first_dir_created_per_command_line_arg,
111 bool *copy_into_self,
112 bool *rename_succeeded);
113 static bool owner_failure_ok (struct cp_options const *x);
115 /* Pointers to the file names: they're used in the diagnostic that is issued
116 when we detect the user is trying to copy a directory into itself. */
117 static char const *top_level_src_name;
118 static char const *top_level_dst_name;
120 /* Set the timestamp of symlink, FILE, to TIMESPEC.
121 If this system lacks support for that, simply return 0. */
122 static inline int
123 utimens_symlink (char const *file, struct timespec const *timespec)
125 int err = lutimens (file, timespec);
126 /* When configuring on a system with new headers and libraries, and
127 running on one with a kernel that is old enough to lack the syscall,
128 utimensat fails with ENOSYS. Ignore that. */
129 if (err && errno == ENOSYS)
130 err = 0;
131 return err;
134 /* Copy the regular file open on SRC_FD/SRC_NAME to DST_FD/DST_NAME,
135 honoring the MAKE_HOLES setting and using the BUF_SIZE-byte buffer
136 BUF for temporary storage. Copy no more than MAX_N_READ bytes.
137 Return true upon successful completion;
138 print a diagnostic and return false upon error.
139 Note that for best results, BUF should be "well"-aligned.
140 BUF must have sizeof(uintptr_t)-1 bytes of additional space
141 beyond BUF[BUF_SIZE-1].
142 Set *LAST_WRITE_MADE_HOLE to true if the final operation on
143 DEST_FD introduced a hole. Set *TOTAL_N_READ to the number of
144 bytes read. */
145 static bool
146 sparse_copy (int src_fd, int dest_fd, char *buf, size_t buf_size,
147 bool make_holes,
148 char const *src_name, char const *dst_name,
149 uintmax_t max_n_read, off_t *total_n_read,
150 bool *last_write_made_hole)
152 typedef uintptr_t word;
153 *last_write_made_hole = false;
154 *total_n_read = 0;
156 while (max_n_read)
158 word *wp = NULL;
160 ssize_t n_read = read (src_fd, buf, MIN (max_n_read, buf_size));
161 if (n_read < 0)
163 if (errno == EINTR)
164 continue;
165 error (0, errno, _("reading %s"), quote (src_name));
166 return false;
168 if (n_read == 0)
169 break;
170 max_n_read -= n_read;
171 *total_n_read += n_read;
173 if (make_holes)
175 char *cp;
177 /* Sentinel to stop loop. */
178 buf[n_read] = '\1';
179 #ifdef lint
180 /* Usually, buf[n_read] is not the byte just before a "word"
181 (aka uintptr_t) boundary. In that case, the word-oriented
182 test below (*wp++ == 0) would read some uninitialized bytes
183 after the sentinel. To avoid false-positive reports about
184 this condition (e.g., from a tool like valgrind), set the
185 remaining bytes -- to any value. */
186 memset (buf + n_read + 1, 0, sizeof (word) - 1);
187 #endif
189 /* Find first nonzero *word*, or the word with the sentinel. */
191 wp = (word *) buf;
192 while (*wp++ == 0)
193 continue;
195 /* Find the first nonzero *byte*, or the sentinel. */
197 cp = (char *) (wp - 1);
198 while (*cp++ == 0)
199 continue;
201 if (cp <= buf + n_read)
202 /* Clear to indicate that a normal write is needed. */
203 wp = NULL;
204 else
206 /* We found the sentinel, so the whole input block was zero.
207 Make a hole. */
208 if (lseek (dest_fd, n_read, SEEK_CUR) < 0)
210 error (0, errno, _("cannot lseek %s"), quote (dst_name));
211 return false;
213 *last_write_made_hole = true;
217 if (!wp)
219 size_t n = n_read;
220 if (full_write (dest_fd, buf, n) != n)
222 error (0, errno, _("writing %s"), quote (dst_name));
223 return false;
225 *last_write_made_hole = false;
227 /* It is tempting to return early here upon a short read from a
228 regular file. That would save the final read syscall for each
229 file. Unfortunately that doesn't work for certain files in
230 /proc with linux kernels from at least 2.6.9 .. 2.6.29. */
234 return true;
237 /* Perform the O(1) btrfs clone operation, if possible.
238 Upon success, return 0. Otherwise, return -1 and set errno. */
239 static inline int
240 clone_file (int dest_fd, int src_fd)
242 #ifdef __linux__
243 # undef BTRFS_IOCTL_MAGIC
244 # define BTRFS_IOCTL_MAGIC 0x94
245 # undef BTRFS_IOC_CLONE
246 # define BTRFS_IOC_CLONE _IOW (BTRFS_IOCTL_MAGIC, 9, int)
247 return ioctl (dest_fd, BTRFS_IOC_CLONE, src_fd);
248 #else
249 (void) dest_fd;
250 (void) src_fd;
251 errno = ENOTSUP;
252 return -1;
253 #endif
256 /* Write N_BYTES zero bytes to file descriptor FD. Return true if successful.
257 Upon write failure, set errno and return false. */
258 static bool
259 write_zeros (int fd, uint64_t n_bytes)
261 static char *zeros;
262 static size_t nz = IO_BUFSIZE;
264 /* Attempt to use a relatively large calloc'd source buffer for
265 efficiency, but if that allocation fails, resort to a smaller
266 statically allocated one. */
267 if (zeros == NULL)
269 static char fallback[1024];
270 zeros = calloc (nz, 1);
271 if (zeros == NULL)
273 zeros = fallback;
274 nz = sizeof fallback;
278 while (n_bytes)
280 uint64_t n = MIN (nz, n_bytes);
281 if ((full_write (fd, zeros, n)) != n)
282 return false;
283 n_bytes -= n;
286 return true;
289 /* Perform an efficient extent copy, if possible. This avoids
290 the overhead of detecting holes in hole-introducing/preserving
291 copy, and thus makes copying sparse files much more efficient.
292 Upon a successful copy, return true. If the initial extent scan
293 fails, set *NORMAL_COPY_REQUIRED to true and return false.
294 Upon any other failure, set *NORMAL_COPY_REQUIRED to false and
295 return false. */
296 static bool
297 extent_copy (int src_fd, int dest_fd, char *buf, size_t buf_size,
298 off_t src_total_size, enum Sparse_type sparse_mode,
299 char const *src_name, char const *dst_name,
300 bool *require_normal_copy)
302 struct extent_scan scan;
303 off_t last_ext_start = 0;
304 uint64_t last_ext_len = 0;
306 /* Keep track of the output position.
307 We may need this at the end, for a final ftruncate. */
308 off_t dest_pos = 0;
310 extent_scan_init (src_fd, &scan);
312 *require_normal_copy = false;
313 bool wrote_hole_at_eof = true;
316 bool ok = extent_scan_read (&scan);
317 if (! ok)
319 if (scan.hit_final_extent)
320 break;
322 if (scan.initial_scan_failed)
324 *require_normal_copy = true;
325 return false;
328 error (0, errno, _("%s: failed to get extents info"),
329 quote (src_name));
330 return false;
333 unsigned int i;
334 bool empty_extent = false;
335 for (i = 0; i < scan.ei_count || empty_extent; i++)
337 off_t ext_start;
338 uint64_t ext_len;
339 uint64_t hole_size;
341 if (i < scan.ei_count)
343 ext_start = scan.ext_info[i].ext_logical;
344 ext_len = scan.ext_info[i].ext_length;
346 else /* empty extent at EOF. */
348 i--;
349 ext_start = last_ext_start + scan.ext_info[i].ext_length;
350 ext_len = 0;
353 hole_size = ext_start - last_ext_start - last_ext_len;
355 wrote_hole_at_eof = false;
357 if (hole_size)
359 if (lseek (src_fd, ext_start, SEEK_SET) < 0)
361 error (0, errno, _("cannot lseek %s"), quote (src_name));
362 fail:
363 extent_scan_free (&scan);
364 return false;
367 if ((empty_extent && sparse_mode == SPARSE_ALWAYS)
368 || (!empty_extent && sparse_mode != SPARSE_NEVER))
370 if (lseek (dest_fd, ext_start, SEEK_SET) < 0)
372 error (0, errno, _("cannot lseek %s"), quote (dst_name));
373 goto fail;
375 wrote_hole_at_eof = true;
377 else
379 /* When not inducing holes and when there is a hole between
380 the end of the previous extent and the beginning of the
381 current one, write zeros to the destination file. */
382 off_t nzeros = hole_size;
383 if (empty_extent)
384 nzeros = MIN (src_total_size - dest_pos, hole_size);
386 if (! write_zeros (dest_fd, nzeros))
388 error (0, errno, _("%s: write failed"), quote (dst_name));
389 goto fail;
392 dest_pos = MIN (src_total_size, ext_start);
396 last_ext_start = ext_start;
398 /* Treat an unwritten but allocated extent much like a hole.
399 I.E. don't read, but don't convert to a hole in the destination,
400 unless SPARSE_ALWAYS. */
401 if (scan.ext_info[i].ext_flags & FIEMAP_EXTENT_UNWRITTEN)
403 empty_extent = true;
404 last_ext_len = 0;
405 if (ext_len == 0) /* The last extent is empty and processed. */
406 empty_extent = false;
408 else
410 off_t n_read;
411 empty_extent = false;
412 last_ext_len = ext_len;
414 if ( ! sparse_copy (src_fd, dest_fd, buf, buf_size,
415 sparse_mode == SPARSE_ALWAYS,
416 src_name, dst_name, ext_len, &n_read,
417 &wrote_hole_at_eof))
418 goto fail;
420 dest_pos = ext_start + n_read;
423 /* If the file ends with unwritten extents not accounted for in the
424 size, then skip processing them, and the associated redundant
425 read() calls which will always return 0. We will need to
426 remove this when we add fallocate() so that we can maintain
427 extents beyond the apparent size. */
428 if (dest_pos == src_total_size)
430 scan.hit_final_extent = true;
431 break;
435 /* Release the space allocated to scan->ext_info. */
436 extent_scan_free (&scan);
439 while (! scan.hit_final_extent);
441 /* When the source file ends with a hole, we have to do a little more work,
442 since the above copied only up to and including the final extent.
443 In order to complete the copy, we may have to insert a hole or write
444 zeros in the destination corresponding to the source file's hole-at-EOF.
446 In addition, if the final extent was a block of zeros at EOF and we've
447 just converted them to a hole in the destination, we must call ftruncate
448 here in order to record the proper length in the destination. */
449 if ((dest_pos < src_total_size || wrote_hole_at_eof)
450 && (sparse_mode != SPARSE_NEVER
451 ? ftruncate (dest_fd, src_total_size)
452 : ! write_zeros (dest_fd, src_total_size - dest_pos)))
454 error (0, errno, _("failed to extend %s"), quote (dst_name));
455 return false;
458 return true;
461 /* FIXME: describe */
462 /* FIXME: rewrite this to use a hash table so we avoid the quadratic
463 performance hit that's probably noticeable only on trees deeper
464 than a few hundred levels. See use of active_dir_map in remove.c */
466 static bool
467 is_ancestor (const struct stat *sb, const struct dir_list *ancestors)
469 while (ancestors != 0)
471 if (ancestors->ino == sb->st_ino && ancestors->dev == sb->st_dev)
472 return true;
473 ancestors = ancestors->parent;
475 return false;
478 static bool
479 errno_unsupported (int err)
481 return err == ENOTSUP || err == ENODATA;
484 #if USE_XATTR
485 static void
486 copy_attr_error (struct error_context *ctx ATTRIBUTE_UNUSED,
487 char const *fmt, ...)
489 if (!errno_unsupported (errno))
491 int err = errno;
492 va_list ap;
494 /* use verror module to print error message */
495 va_start (ap, fmt);
496 verror (0, err, fmt, ap);
497 va_end (ap);
501 static void
502 copy_attr_allerror (struct error_context *ctx ATTRIBUTE_UNUSED,
503 char const *fmt, ...)
505 int err = errno;
506 va_list ap;
508 /* use verror module to print error message */
509 va_start (ap, fmt);
510 verror (0, err, fmt, ap);
511 va_end (ap);
514 static char const *
515 copy_attr_quote (struct error_context *ctx ATTRIBUTE_UNUSED, char const *str)
517 return quote (str);
520 static void
521 copy_attr_free (struct error_context *ctx ATTRIBUTE_UNUSED,
522 char const *str ATTRIBUTE_UNUSED)
526 /* If positive SRC_FD and DST_FD descriptors are passed,
527 then copy by fd, otherwise copy by name. */
529 static bool
530 copy_attr (char const *src_path, int src_fd,
531 char const *dst_path, int dst_fd, struct cp_options const *x)
533 int ret;
534 bool all_errors = (!x->data_copy_required || x->require_preserve_xattr);
535 bool some_errors = (!all_errors && !x->reduce_diagnostics);
536 struct error_context ctx =
538 .error = all_errors ? copy_attr_allerror : copy_attr_error,
539 .quote = copy_attr_quote,
540 .quote_free = copy_attr_free
542 if (0 <= src_fd && 0 <= dst_fd)
543 ret = attr_copy_fd (src_path, src_fd, dst_path, dst_fd, 0,
544 (all_errors || some_errors ? &ctx : NULL));
545 else
546 ret = attr_copy_file (src_path, dst_path, 0,
547 (all_errors || some_errors ? &ctx : NULL));
549 return ret == 0;
551 #else /* USE_XATTR */
553 static bool
554 copy_attr (char const *src_path ATTRIBUTE_UNUSED,
555 int src_fd ATTRIBUTE_UNUSED,
556 char const *dst_path ATTRIBUTE_UNUSED,
557 int dst_fd ATTRIBUTE_UNUSED,
558 struct cp_options const *x ATTRIBUTE_UNUSED)
560 return true;
562 #endif /* USE_XATTR */
564 /* Read the contents of the directory SRC_NAME_IN, and recursively
565 copy the contents to DST_NAME_IN. NEW_DST is true if
566 DST_NAME_IN is a directory that was created previously in the
567 recursion. SRC_SB and ANCESTORS describe SRC_NAME_IN.
568 Set *COPY_INTO_SELF if SRC_NAME_IN is a parent of
569 (or the same as) DST_NAME_IN; otherwise, clear it.
570 Propagate *FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG from
571 caller to each invocation of copy_internal. Be careful to
572 pass the address of a temporary, and to update
573 *FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG only upon completion.
574 Return true if successful. */
576 static bool
577 copy_dir (char const *src_name_in, char const *dst_name_in, bool new_dst,
578 const struct stat *src_sb, struct dir_list *ancestors,
579 const struct cp_options *x,
580 bool *first_dir_created_per_command_line_arg,
581 bool *copy_into_self)
583 char *name_space;
584 char *namep;
585 struct cp_options non_command_line_options = *x;
586 bool ok = true;
588 name_space = savedir (src_name_in);
589 if (name_space == NULL)
591 /* This diagnostic is a bit vague because savedir can fail in
592 several different ways. */
593 error (0, errno, _("cannot access %s"), quote (src_name_in));
594 return false;
597 /* For cp's -H option, dereference command line arguments, but do not
598 dereference symlinks that are found via recursive traversal. */
599 if (x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
600 non_command_line_options.dereference = DEREF_NEVER;
602 bool new_first_dir_created = false;
603 namep = name_space;
604 while (*namep != '\0')
606 bool local_copy_into_self;
607 char *src_name = file_name_concat (src_name_in, namep, NULL);
608 char *dst_name = file_name_concat (dst_name_in, namep, NULL);
609 bool first_dir_created = *first_dir_created_per_command_line_arg;
611 ok &= copy_internal (src_name, dst_name, new_dst, src_sb->st_dev,
612 ancestors, &non_command_line_options, false,
613 &first_dir_created,
614 &local_copy_into_self, NULL);
615 *copy_into_self |= local_copy_into_self;
617 free (dst_name);
618 free (src_name);
620 /* If we're copying into self, there's no point in continuing,
621 and in fact, that would even infloop, now that we record only
622 the first created directory per command line argument. */
623 if (local_copy_into_self)
624 break;
626 new_first_dir_created |= first_dir_created;
627 namep += strlen (namep) + 1;
629 free (name_space);
630 *first_dir_created_per_command_line_arg = new_first_dir_created;
632 return ok;
635 /* Set the owner and owning group of DEST_DESC to the st_uid and
636 st_gid fields of SRC_SB. If DEST_DESC is undefined (-1), set
637 the owner and owning group of DST_NAME instead; for
638 safety prefer lchown if the system supports it since no
639 symbolic links should be involved. DEST_DESC must
640 refer to the same file as DEST_NAME if defined.
641 Upon failure to set both UID and GID, try to set only the GID.
642 NEW_DST is true if the file was newly created; otherwise,
643 DST_SB is the status of the destination.
644 Return 1 if the initial syscall succeeds, 0 if it fails but it's OK
645 not to preserve ownership, -1 otherwise. */
647 static int
648 set_owner (const struct cp_options *x, char const *dst_name, int dest_desc,
649 struct stat const *src_sb, bool new_dst,
650 struct stat const *dst_sb)
652 uid_t uid = src_sb->st_uid;
653 gid_t gid = src_sb->st_gid;
655 /* Naively changing the ownership of an already-existing file before
656 changing its permissions would create a window of vulnerability if
657 the file's old permissions are too generous for the new owner and
658 group. Avoid the window by first changing to a restrictive
659 temporary mode if necessary. */
661 if (!new_dst && (x->preserve_mode || x->move_mode || x->set_mode))
663 mode_t old_mode = dst_sb->st_mode;
664 mode_t new_mode =
665 (x->preserve_mode || x->move_mode ? src_sb->st_mode : x->mode);
666 mode_t restrictive_temp_mode = old_mode & new_mode & S_IRWXU;
668 if ((USE_ACL
669 || (old_mode & CHMOD_MODE_BITS
670 & (~new_mode | S_ISUID | S_ISGID | S_ISVTX)))
671 && qset_acl (dst_name, dest_desc, restrictive_temp_mode) != 0)
673 if (! owner_failure_ok (x))
674 error (0, errno, _("clearing permissions for %s"),
675 quote (dst_name));
676 return -x->require_preserve;
680 if (HAVE_FCHOWN && dest_desc != -1)
682 if (fchown (dest_desc, uid, gid) == 0)
683 return 1;
684 if (errno == EPERM || errno == EINVAL)
686 /* We've failed to set *both*. Now, try to set just the group
687 ID, but ignore any failure here, and don't change errno. */
688 int saved_errno = errno;
689 ignore_value (fchown (dest_desc, -1, gid));
690 errno = saved_errno;
693 else
695 if (lchown (dst_name, uid, gid) == 0)
696 return 1;
697 if (errno == EPERM || errno == EINVAL)
699 /* We've failed to set *both*. Now, try to set just the group
700 ID, but ignore any failure here, and don't change errno. */
701 int saved_errno = errno;
702 ignore_value (lchown (dst_name, -1, gid));
703 errno = saved_errno;
707 if (! chown_failure_ok (x))
709 error (0, errno, _("failed to preserve ownership for %s"),
710 quote (dst_name));
711 if (x->require_preserve)
712 return -1;
715 return 0;
718 /* Set the st_author field of DEST_DESC to the st_author field of
719 SRC_SB. If DEST_DESC is undefined (-1), set the st_author field
720 of DST_NAME instead. DEST_DESC must refer to the same file as
721 DEST_NAME if defined. */
723 static void
724 set_author (const char *dst_name, int dest_desc, const struct stat *src_sb)
726 #if HAVE_STRUCT_STAT_ST_AUTHOR
727 /* FIXME: Modify the following code so that it does not
728 follow symbolic links. */
730 /* Preserve the st_author field. */
731 file_t file = (dest_desc < 0
732 ? file_name_lookup (dst_name, 0, 0)
733 : getdport (dest_desc));
734 if (file == MACH_PORT_NULL)
735 error (0, errno, _("failed to lookup file %s"), quote (dst_name));
736 else
738 error_t err = file_chauthor (file, src_sb->st_author);
739 if (err)
740 error (0, err, _("failed to preserve authorship for %s"),
741 quote (dst_name));
742 mach_port_deallocate (mach_task_self (), file);
744 #else
745 (void) dst_name;
746 (void) dest_desc;
747 (void) src_sb;
748 #endif
751 /* Change the file mode bits of the file identified by DESC or NAME to MODE.
752 Use DESC if DESC is valid and fchmod is available, NAME otherwise. */
754 static int
755 fchmod_or_lchmod (int desc, char const *name, mode_t mode)
757 #if HAVE_FCHMOD
758 if (0 <= desc)
759 return fchmod (desc, mode);
760 #endif
761 return lchmod (name, mode);
764 /* Copy a regular file from SRC_NAME to DST_NAME.
765 If the source file contains holes, copies holes and blocks of zeros
766 in the source file as holes in the destination file.
767 (Holes are read as zeroes by the `read' system call.)
768 When creating the destination, use DST_MODE & ~OMITTED_PERMISSIONS
769 as the third argument in the call to open, adding
770 OMITTED_PERMISSIONS after copying as needed.
771 X provides many option settings.
772 Return true if successful.
773 *NEW_DST is as in copy_internal.
774 SRC_SB is the result of calling XSTAT (aka stat) on SRC_NAME. */
776 static bool
777 copy_reg (char const *src_name, char const *dst_name,
778 const struct cp_options *x,
779 mode_t dst_mode, mode_t omitted_permissions, bool *new_dst,
780 struct stat const *src_sb)
782 char *buf;
783 char *buf_alloc = NULL;
784 char *name_alloc = NULL;
785 int dest_desc;
786 int dest_errno;
787 int source_desc;
788 mode_t src_mode = src_sb->st_mode;
789 struct stat sb;
790 struct stat src_open_sb;
791 bool return_val = true;
792 bool data_copy_required = x->data_copy_required;
794 source_desc = open (src_name,
795 (O_RDONLY | O_BINARY
796 | (x->dereference == DEREF_NEVER ? O_NOFOLLOW : 0)));
797 if (source_desc < 0)
799 error (0, errno, _("cannot open %s for reading"), quote (src_name));
800 return false;
803 if (fstat (source_desc, &src_open_sb) != 0)
805 error (0, errno, _("cannot fstat %s"), quote (src_name));
806 return_val = false;
807 goto close_src_desc;
810 /* Compare the source dev/ino from the open file to the incoming,
811 saved ones obtained via a previous call to stat. */
812 if (! SAME_INODE (*src_sb, src_open_sb))
814 error (0, 0,
815 _("skipping file %s, as it was replaced while being copied"),
816 quote (src_name));
817 return_val = false;
818 goto close_src_desc;
821 /* The semantics of the following open calls are mandated
822 by the specs for both cp and mv. */
823 if (! *new_dst)
825 dest_desc = open (dst_name, O_WRONLY | O_TRUNC | O_BINARY);
826 dest_errno = errno;
828 /* When using cp --preserve=context to copy to an existing destination,
829 use the default context rather than that of the source. Why?
830 1) the src context may prohibit writing, and
831 2) because it's more consistent to use the same context
832 that is used when the destination file doesn't already exist. */
833 if (x->preserve_security_context && 0 <= dest_desc)
835 bool all_errors = (!x->data_copy_required
836 || x->require_preserve_context);
837 bool some_errors = !all_errors && !x->reduce_diagnostics;
838 security_context_t con = NULL;
840 if (getfscreatecon (&con) < 0)
842 if (all_errors || (some_errors && !errno_unsupported (errno)))
843 error (0, errno, _("failed to get file system create context"));
844 if (x->require_preserve_context)
846 return_val = false;
847 goto close_src_and_dst_desc;
851 if (con)
853 if (fsetfilecon (dest_desc, con) < 0)
855 if (all_errors || (some_errors && !errno_unsupported (errno)))
856 error (0, errno,
857 _("failed to set the security context of %s to %s"),
858 quote_n (0, dst_name), quote_n (1, con));
859 if (x->require_preserve_context)
861 return_val = false;
862 freecon (con);
863 goto close_src_and_dst_desc;
866 freecon (con);
870 if (dest_desc < 0 && x->unlink_dest_after_failed_open)
872 if (unlink (dst_name) != 0)
874 error (0, errno, _("cannot remove %s"), quote (dst_name));
875 return_val = false;
876 goto close_src_desc;
878 if (x->verbose)
879 printf (_("removed %s\n"), quote (dst_name));
881 /* Tell caller that the destination file was unlinked. */
882 *new_dst = true;
886 if (*new_dst)
888 int open_flags = O_WRONLY | O_CREAT | O_BINARY;
889 dest_desc = open (dst_name, open_flags | O_EXCL,
890 dst_mode & ~omitted_permissions);
891 dest_errno = errno;
893 /* When trying to copy through a dangling destination symlink,
894 the above open fails with EEXIST. If that happens, and
895 lstat'ing the DST_NAME shows that it is a symlink, then we
896 have a problem: trying to resolve this dangling symlink to
897 a directory/destination-entry pair is fundamentally racy,
898 so punt. If x->open_dangling_dest_symlink is set (cp sets
899 that when POSIXLY_CORRECT is set in the environment), simply
900 call open again, but without O_EXCL (potentially dangerous).
901 If not, fail with a diagnostic. These shenanigans are necessary
902 only when copying, i.e., not in move_mode. */
903 if (dest_desc < 0 && dest_errno == EEXIST && ! x->move_mode)
905 struct stat dangling_link_sb;
906 if (lstat (dst_name, &dangling_link_sb) == 0
907 && S_ISLNK (dangling_link_sb.st_mode))
909 if (x->open_dangling_dest_symlink)
911 dest_desc = open (dst_name, open_flags,
912 dst_mode & ~omitted_permissions);
913 dest_errno = errno;
915 else
917 error (0, 0, _("not writing through dangling symlink %s"),
918 quote (dst_name));
919 return_val = false;
920 goto close_src_desc;
925 /* Improve quality of diagnostic when a nonexistent dst_name
926 ends in a slash and open fails with errno == EISDIR. */
927 if (dest_desc < 0 && dest_errno == EISDIR
928 && *dst_name && dst_name[strlen (dst_name) - 1] == '/')
929 dest_errno = ENOTDIR;
931 else
932 omitted_permissions = 0;
934 if (dest_desc < 0)
936 error (0, dest_errno, _("cannot create regular file %s"),
937 quote (dst_name));
938 return_val = false;
939 goto close_src_desc;
942 if (fstat (dest_desc, &sb) != 0)
944 error (0, errno, _("cannot fstat %s"), quote (dst_name));
945 return_val = false;
946 goto close_src_and_dst_desc;
949 /* --attributes-only overrides --reflink. */
950 if (data_copy_required && x->reflink_mode)
952 bool clone_ok = clone_file (dest_desc, source_desc) == 0;
953 if (clone_ok || x->reflink_mode == REFLINK_ALWAYS)
955 if (!clone_ok)
957 error (0, errno, _("failed to clone %s"), quote (dst_name));
958 return_val = false;
959 goto close_src_and_dst_desc;
961 data_copy_required = false;
965 if (data_copy_required)
967 typedef uintptr_t word;
969 /* Choose a suitable buffer size; it may be adjusted later. */
970 size_t buf_alignment = lcm (getpagesize (), sizeof (word));
971 size_t buf_alignment_slop = sizeof (word) + buf_alignment - 1;
972 size_t buf_size = io_blksize (sb);
974 /* Deal with sparse files. */
975 bool make_holes = false;
977 if (S_ISREG (sb.st_mode))
979 /* Even with --sparse=always, try to create holes only
980 if the destination is a regular file. */
981 if (x->sparse_mode == SPARSE_ALWAYS)
982 make_holes = true;
984 #if HAVE_STRUCT_STAT_ST_BLOCKS
985 /* Use a heuristic to determine whether SRC_NAME contains any sparse
986 blocks. If the file has fewer blocks than would normally be
987 needed for a file of its size, then at least one of the blocks in
988 the file is a hole. */
989 if (x->sparse_mode == SPARSE_AUTO && S_ISREG (src_open_sb.st_mode)
990 && ST_NBLOCKS (src_open_sb) < src_open_sb.st_size / ST_NBLOCKSIZE)
991 make_holes = true;
992 #endif
995 /* If not making a sparse file, try to use a more-efficient
996 buffer size. */
997 if (! make_holes)
999 /* Compute the least common multiple of the input and output
1000 buffer sizes, adjusting for outlandish values. */
1001 size_t blcm_max = MIN (SIZE_MAX, SSIZE_MAX) - buf_alignment_slop;
1002 size_t blcm = buffer_lcm (io_blksize (src_open_sb), buf_size,
1003 blcm_max);
1005 /* Do not bother with a buffer larger than the input file, plus one
1006 byte to make sure the file has not grown while reading it. */
1007 if (S_ISREG (src_open_sb.st_mode) && src_open_sb.st_size < buf_size)
1008 buf_size = src_open_sb.st_size + 1;
1010 /* However, stick with a block size that is a positive multiple of
1011 blcm, overriding the above adjustments. Watch out for
1012 overflow. */
1013 buf_size += blcm - 1;
1014 buf_size -= buf_size % blcm;
1015 if (buf_size == 0 || blcm_max < buf_size)
1016 buf_size = blcm;
1019 /* Make a buffer with space for a sentinel at the end. */
1020 buf_alloc = xmalloc (buf_size + buf_alignment_slop);
1021 buf = ptr_align (buf_alloc, buf_alignment);
1023 bool normal_copy_required;
1024 /* Perform an efficient extent-based copy, falling back to the
1025 standard copy only if the initial extent scan fails. If the
1026 '--sparse=never' option is specified, write all data but use
1027 any extents to read more efficiently. */
1028 if (extent_copy (source_desc, dest_desc, buf, buf_size,
1029 src_open_sb.st_size,
1030 S_ISREG (sb.st_mode) ? x->sparse_mode : SPARSE_NEVER,
1031 src_name, dst_name, &normal_copy_required))
1032 goto preserve_metadata;
1034 if (! normal_copy_required)
1036 return_val = false;
1037 goto close_src_and_dst_desc;
1040 off_t n_read;
1041 bool wrote_hole_at_eof;
1042 if ( ! sparse_copy (source_desc, dest_desc, buf, buf_size,
1043 make_holes, src_name, dst_name,
1044 UINTMAX_MAX, &n_read,
1045 &wrote_hole_at_eof)
1046 || (wrote_hole_at_eof &&
1047 ftruncate (dest_desc, n_read) < 0))
1049 error (0, errno, _("failed to extend %s"), quote (dst_name));
1050 return_val = false;
1051 goto close_src_and_dst_desc;
1055 preserve_metadata:
1056 if (x->preserve_timestamps)
1058 struct timespec timespec[2];
1059 timespec[0] = get_stat_atime (src_sb);
1060 timespec[1] = get_stat_mtime (src_sb);
1062 if (fdutimens (dest_desc, dst_name, timespec) != 0)
1064 error (0, errno, _("preserving times for %s"), quote (dst_name));
1065 if (x->require_preserve)
1067 return_val = false;
1068 goto close_src_and_dst_desc;
1073 /* Set ownership before xattrs as changing owners will
1074 clear capabilities. */
1075 if (x->preserve_ownership && ! SAME_OWNER_AND_GROUP (*src_sb, sb))
1077 switch (set_owner (x, dst_name, dest_desc, src_sb, *new_dst, &sb))
1079 case -1:
1080 return_val = false;
1081 goto close_src_and_dst_desc;
1083 case 0:
1084 src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX);
1085 break;
1089 /* To allow copying xattrs on read-only files, temporarily chmod u+rw.
1090 This workaround is required as an inode permission check is done
1091 by xattr_permission() in fs/xattr.c of the GNU/Linux kernel tree. */
1092 if (x->preserve_xattr)
1094 bool access_changed = false;
1096 if (!(sb.st_mode & S_IWUSR) && geteuid () != 0)
1097 access_changed = fchmod_or_lchmod (dest_desc, dst_name, 0600) == 0;
1099 if (!copy_attr (src_name, source_desc, dst_name, dest_desc, x)
1100 && x->require_preserve_xattr)
1101 return_val = false;
1103 if (access_changed)
1104 fchmod_or_lchmod (dest_desc, dst_name, dst_mode & ~omitted_permissions);
1107 set_author (dst_name, dest_desc, src_sb);
1109 if (x->preserve_mode || x->move_mode)
1111 if (copy_acl (src_name, source_desc, dst_name, dest_desc, src_mode) != 0
1112 && x->require_preserve)
1113 return_val = false;
1115 else if (x->set_mode)
1117 if (set_acl (dst_name, dest_desc, x->mode) != 0)
1118 return_val = false;
1120 else if (omitted_permissions)
1122 omitted_permissions &= ~ cached_umask ();
1123 if (omitted_permissions
1124 && fchmod_or_lchmod (dest_desc, dst_name, dst_mode) != 0)
1126 error (0, errno, _("preserving permissions for %s"),
1127 quote (dst_name));
1128 if (x->require_preserve)
1129 return_val = false;
1133 close_src_and_dst_desc:
1134 if (close (dest_desc) < 0)
1136 error (0, errno, _("closing %s"), quote (dst_name));
1137 return_val = false;
1139 close_src_desc:
1140 if (close (source_desc) < 0)
1142 error (0, errno, _("closing %s"), quote (src_name));
1143 return_val = false;
1146 free (buf_alloc);
1147 free (name_alloc);
1148 return return_val;
1151 /* Return true if it's ok that the source and destination
1152 files are the `same' by some measure. The goal is to avoid
1153 making the `copy' operation remove both copies of the file
1154 in that case, while still allowing the user to e.g., move or
1155 copy a regular file onto a symlink that points to it.
1156 Try to minimize the cost of this function in the common case.
1157 Set *RETURN_NOW if we've determined that the caller has no more
1158 work to do and should return successfully, right away.
1160 Set *UNLINK_SRC if we've determined that the caller wants to do
1161 `rename (a, b)' where `a' and `b' are distinct hard links to the same
1162 file. In that case, the caller should try to unlink `a' and then return
1163 successfully. Ideally, we wouldn't have to do that, and we'd be
1164 able to rely on rename to remove the source file. However, POSIX
1165 mistakenly requires that such a rename call do *nothing* and return
1166 successfully. */
1168 static bool
1169 same_file_ok (char const *src_name, struct stat const *src_sb,
1170 char const *dst_name, struct stat const *dst_sb,
1171 const struct cp_options *x, bool *return_now, bool *unlink_src)
1173 const struct stat *src_sb_link;
1174 const struct stat *dst_sb_link;
1175 struct stat tmp_dst_sb;
1176 struct stat tmp_src_sb;
1178 bool same_link;
1179 bool same = SAME_INODE (*src_sb, *dst_sb);
1181 *return_now = false;
1182 *unlink_src = false;
1184 /* FIXME: this should (at the very least) be moved into the following
1185 if-block. More likely, it should be removed, because it inhibits
1186 making backups. But removing it will result in a change in behavior
1187 that will probably have to be documented -- and tests will have to
1188 be updated. */
1189 if (same && x->hard_link)
1191 *return_now = true;
1192 return true;
1195 if (x->dereference == DEREF_NEVER)
1197 same_link = same;
1199 /* If both the source and destination files are symlinks (and we'll
1200 know this here IFF preserving symlinks), then it's ok -- as long
1201 as they are distinct. */
1202 if (S_ISLNK (src_sb->st_mode) && S_ISLNK (dst_sb->st_mode))
1203 return ! same_name (src_name, dst_name);
1205 src_sb_link = src_sb;
1206 dst_sb_link = dst_sb;
1208 else
1210 if (!same)
1211 return true;
1213 if (lstat (dst_name, &tmp_dst_sb) != 0
1214 || lstat (src_name, &tmp_src_sb) != 0)
1215 return true;
1217 src_sb_link = &tmp_src_sb;
1218 dst_sb_link = &tmp_dst_sb;
1220 same_link = SAME_INODE (*src_sb_link, *dst_sb_link);
1222 /* If both are symlinks, then it's ok, but only if the destination
1223 will be unlinked before being opened. This is like the test
1224 above, but with the addition of the unlink_dest_before_opening
1225 conjunct because otherwise, with two symlinks to the same target,
1226 we'd end up truncating the source file. */
1227 if (S_ISLNK (src_sb_link->st_mode) && S_ISLNK (dst_sb_link->st_mode)
1228 && x->unlink_dest_before_opening)
1229 return true;
1232 /* The backup code ensures there's a copy, so it's usually ok to
1233 remove any destination file. One exception is when both
1234 source and destination are the same directory entry. In that
1235 case, moving the destination file aside (in making the backup)
1236 would also rename the source file and result in an error. */
1237 if (x->backup_type != no_backups)
1239 if (!same_link)
1241 /* In copy mode when dereferencing symlinks, if the source is a
1242 symlink and the dest is not, then backing up the destination
1243 (moving it aside) would make it a dangling symlink, and the
1244 subsequent attempt to open it in copy_reg would fail with
1245 a misleading diagnostic. Avoid that by returning zero in
1246 that case so the caller can make cp (or mv when it has to
1247 resort to reading the source file) fail now. */
1249 /* FIXME-note: even with the following kludge, we can still provoke
1250 the offending diagnostic. It's just a little harder to do :-)
1251 $ rm -f a b c; touch c; ln -s c b; ln -s b a; cp -b a b
1252 cp: cannot open `a' for reading: No such file or directory
1253 That's misleading, since a subsequent `ls' shows that `a'
1254 is still there.
1255 One solution would be to open the source file *before* moving
1256 aside the destination, but that'd involve a big rewrite. */
1257 if ( ! x->move_mode
1258 && x->dereference != DEREF_NEVER
1259 && S_ISLNK (src_sb_link->st_mode)
1260 && ! S_ISLNK (dst_sb_link->st_mode))
1261 return false;
1263 return true;
1266 return ! same_name (src_name, dst_name);
1269 #if 0
1270 /* FIXME: use or remove */
1272 /* If we're making a backup, we'll detect the problem case in
1273 copy_reg because SRC_NAME will no longer exist. Allowing
1274 the test to be deferred lets cp do some useful things.
1275 But when creating hardlinks and SRC_NAME is a symlink
1276 but DST_NAME is not we must test anyway. */
1277 if (x->hard_link
1278 || !S_ISLNK (src_sb_link->st_mode)
1279 || S_ISLNK (dst_sb_link->st_mode))
1280 return true;
1282 if (x->dereference != DEREF_NEVER)
1283 return true;
1284 #endif
1286 /* They may refer to the same file if we're in move mode and the
1287 target is a symlink. That is ok, since we remove any existing
1288 destination file before opening it -- via `rename' if they're on
1289 the same file system, via `unlink (DST_NAME)' otherwise.
1290 It's also ok if they're distinct hard links to the same file. */
1291 if (x->move_mode || x->unlink_dest_before_opening)
1293 if (S_ISLNK (dst_sb_link->st_mode))
1294 return true;
1296 if (same_link
1297 && 1 < dst_sb_link->st_nlink
1298 && ! same_name (src_name, dst_name))
1300 if (x->move_mode)
1302 *unlink_src = true;
1303 *return_now = true;
1305 return true;
1309 /* If neither is a symlink, then it's ok as long as they aren't
1310 hard links to the same file. */
1311 if (!S_ISLNK (src_sb_link->st_mode) && !S_ISLNK (dst_sb_link->st_mode))
1313 if (!SAME_INODE (*src_sb_link, *dst_sb_link))
1314 return true;
1316 /* If they are the same file, it's ok if we're making hard links. */
1317 if (x->hard_link)
1319 *return_now = true;
1320 return true;
1324 /* It's ok to remove a destination symlink. But that works only when we
1325 unlink before opening the destination and when the source and destination
1326 files are on the same partition. */
1327 if (x->unlink_dest_before_opening
1328 && S_ISLNK (dst_sb_link->st_mode))
1329 return dst_sb_link->st_dev == src_sb_link->st_dev;
1331 if (x->dereference == DEREF_NEVER)
1333 if ( ! S_ISLNK (src_sb_link->st_mode))
1334 tmp_src_sb = *src_sb_link;
1335 else if (stat (src_name, &tmp_src_sb) != 0)
1336 return true;
1338 if ( ! S_ISLNK (dst_sb_link->st_mode))
1339 tmp_dst_sb = *dst_sb_link;
1340 else if (stat (dst_name, &tmp_dst_sb) != 0)
1341 return true;
1343 if ( ! SAME_INODE (tmp_src_sb, tmp_dst_sb))
1344 return true;
1346 /* FIXME: shouldn't this be testing whether we're making symlinks? */
1347 if (x->hard_link)
1349 *return_now = true;
1350 return true;
1354 return false;
1357 /* Return true if FILE, with mode MODE, is writable in the sense of 'mv'.
1358 Always consider a symbolic link to be writable. */
1359 static bool
1360 writable_destination (char const *file, mode_t mode)
1362 return (S_ISLNK (mode)
1363 || can_write_any_file ()
1364 || euidaccess (file, W_OK) == 0);
1367 static void
1368 overwrite_prompt (char const *dst_name, struct stat const *dst_sb)
1370 if (! writable_destination (dst_name, dst_sb->st_mode))
1372 char perms[12]; /* "-rwxrwxrwx " ls-style modes. */
1373 strmode (dst_sb->st_mode, perms);
1374 perms[10] = '\0';
1375 fprintf (stderr,
1376 _("%s: try to overwrite %s, overriding mode %04lo (%s)? "),
1377 program_name, quote (dst_name),
1378 (unsigned long int) (dst_sb->st_mode & CHMOD_MODE_BITS),
1379 &perms[1]);
1381 else
1383 fprintf (stderr, _("%s: overwrite %s? "),
1384 program_name, quote (dst_name));
1388 /* Initialize the hash table implementing a set of F_triple entries
1389 corresponding to destination files. */
1390 extern void
1391 dest_info_init (struct cp_options *x)
1393 x->dest_info
1394 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
1395 NULL,
1396 triple_hash,
1397 triple_compare,
1398 triple_free);
1401 /* Initialize the hash table implementing a set of F_triple entries
1402 corresponding to source files listed on the command line. */
1403 extern void
1404 src_info_init (struct cp_options *x)
1407 /* Note that we use triple_hash_no_name here.
1408 Contrast with the use of triple_hash above.
1409 That is necessary because a source file may be specified
1410 in many different ways. We want to warn about this
1411 cp a a d/
1412 as well as this:
1413 cp a ./a d/
1415 x->src_info
1416 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
1417 NULL,
1418 triple_hash_no_name,
1419 triple_compare,
1420 triple_free);
1423 /* When effecting a move (e.g., for mv(1)), and given the name DST_NAME
1424 of the destination and a corresponding stat buffer, DST_SB, return
1425 true if the logical `move' operation should _not_ proceed.
1426 Otherwise, return false.
1427 Depending on options specified in X, this code may issue an
1428 interactive prompt asking whether it's ok to overwrite DST_NAME. */
1429 static bool
1430 abandon_move (const struct cp_options *x,
1431 char const *dst_name,
1432 struct stat const *dst_sb)
1434 assert (x->move_mode);
1435 return (x->interactive == I_ALWAYS_NO
1436 || ((x->interactive == I_ASK_USER
1437 || (x->interactive == I_UNSPECIFIED
1438 && x->stdin_tty
1439 && ! writable_destination (dst_name, dst_sb->st_mode)))
1440 && (overwrite_prompt (dst_name, dst_sb), 1)
1441 && ! yesno ()));
1444 /* Print --verbose output on standard output, e.g. `new' -> `old'.
1445 If BACKUP_DST_NAME is non-NULL, then also indicate that it is
1446 the name of a backup file. */
1447 static void
1448 emit_verbose (char const *src, char const *dst, char const *backup_dst_name)
1450 printf ("%s -> %s", quote_n (0, src), quote_n (1, dst));
1451 if (backup_dst_name)
1452 printf (_(" (backup: %s)"), quote (backup_dst_name));
1453 putchar ('\n');
1456 /* A wrapper around "setfscreatecon (NULL)" that exits upon failure. */
1457 static void
1458 restore_default_fscreatecon_or_die (void)
1460 if (setfscreatecon (NULL) != 0)
1461 error (EXIT_FAILURE, errno,
1462 _("failed to restore the default file creation context"));
1465 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
1466 any type. NEW_DST should be true if the file DST_NAME cannot
1467 exist because its parent directory was just created; NEW_DST should
1468 be false if DST_NAME might already exist. DEVICE is the device
1469 number of the parent directory, or 0 if the parent of this file is
1470 not known. ANCESTORS points to a linked, null terminated list of
1471 devices and inodes of parent directories of SRC_NAME. COMMAND_LINE_ARG
1472 is true iff SRC_NAME was specified on the command line.
1473 FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG is both input and output.
1474 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
1475 same as) DST_NAME; otherwise, clear it.
1476 Return true if successful. */
1477 static bool
1478 copy_internal (char const *src_name, char const *dst_name,
1479 bool new_dst,
1480 dev_t device,
1481 struct dir_list *ancestors,
1482 const struct cp_options *x,
1483 bool command_line_arg,
1484 bool *first_dir_created_per_command_line_arg,
1485 bool *copy_into_self,
1486 bool *rename_succeeded)
1488 struct stat src_sb;
1489 struct stat dst_sb;
1490 mode_t src_mode;
1491 mode_t dst_mode IF_LINT ( = 0);
1492 mode_t dst_mode_bits;
1493 mode_t omitted_permissions;
1494 bool restore_dst_mode = false;
1495 char *earlier_file = NULL;
1496 char *dst_backup = NULL;
1497 bool backup_succeeded = false;
1498 bool delayed_ok;
1499 bool copied_as_regular = false;
1500 bool dest_is_symlink = false;
1501 bool have_dst_lstat = false;
1503 if (x->move_mode && rename_succeeded)
1504 *rename_succeeded = false;
1506 *copy_into_self = false;
1508 if (XSTAT (x, src_name, &src_sb) != 0)
1510 error (0, errno, _("cannot stat %s"), quote (src_name));
1511 return false;
1514 src_mode = src_sb.st_mode;
1516 if (S_ISDIR (src_mode) && !x->recursive)
1518 error (0, 0, _("omitting directory %s"), quote (src_name));
1519 return false;
1522 /* Detect the case in which the same source file appears more than
1523 once on the command line and no backup option has been selected.
1524 If so, simply warn and don't copy it the second time.
1525 This check is enabled only if x->src_info is non-NULL. */
1526 if (command_line_arg)
1528 if ( ! S_ISDIR (src_sb.st_mode)
1529 && x->backup_type == no_backups
1530 && seen_file (x->src_info, src_name, &src_sb))
1532 error (0, 0, _("warning: source file %s specified more than once"),
1533 quote (src_name));
1534 return true;
1537 record_file (x->src_info, src_name, &src_sb);
1540 if (!new_dst)
1542 /* Regular files can be created by writing through symbolic
1543 links, but other files cannot. So use stat on the
1544 destination when copying a regular file, and lstat otherwise.
1545 However, if we intend to unlink or remove the destination
1546 first, use lstat, since a copy won't actually be made to the
1547 destination in that case. */
1548 bool use_stat =
1549 ((S_ISREG (src_mode)
1550 || (x->copy_as_regular
1551 && ! (S_ISDIR (src_mode) || S_ISLNK (src_mode))))
1552 && ! (x->move_mode || x->symbolic_link || x->hard_link
1553 || x->backup_type != no_backups
1554 || x->unlink_dest_before_opening));
1555 if ((use_stat
1556 ? stat (dst_name, &dst_sb)
1557 : lstat (dst_name, &dst_sb))
1558 != 0)
1560 if (errno != ENOENT)
1562 error (0, errno, _("cannot stat %s"), quote (dst_name));
1563 return false;
1565 else
1567 new_dst = true;
1570 else
1571 { /* Here, we know that dst_name exists, at least to the point
1572 that it is stat'able or lstat'able. */
1573 bool return_now;
1574 bool unlink_src;
1576 have_dst_lstat = !use_stat;
1577 if (! same_file_ok (src_name, &src_sb, dst_name, &dst_sb,
1578 x, &return_now, &unlink_src))
1580 error (0, 0, _("%s and %s are the same file"),
1581 quote_n (0, src_name), quote_n (1, dst_name));
1582 return false;
1585 if (!S_ISDIR (src_mode) && x->update)
1587 /* When preserving time stamps (but not moving within a file
1588 system), don't worry if the destination time stamp is
1589 less than the source merely because of time stamp
1590 truncation. */
1591 int options = ((x->preserve_timestamps
1592 && ! (x->move_mode
1593 && dst_sb.st_dev == src_sb.st_dev))
1594 ? UTIMECMP_TRUNCATE_SOURCE
1595 : 0);
1597 if (0 <= utimecmp (dst_name, &dst_sb, &src_sb, options))
1599 /* We're using --update and the destination is not older
1600 than the source, so do not copy or move. Pretend the
1601 rename succeeded, so the caller (if it's mv) doesn't
1602 end up removing the source file. */
1603 if (rename_succeeded)
1604 *rename_succeeded = true;
1605 return true;
1609 /* When there is an existing destination file, we may end up
1610 returning early, and hence not copying/moving the file.
1611 This may be due to an interactive `negative' reply to the
1612 prompt about the existing file. It may also be due to the
1613 use of the --reply=no option.
1615 cp and mv treat -i and -f differently. */
1616 if (x->move_mode)
1618 if (abandon_move (x, dst_name, &dst_sb)
1619 || (unlink_src && unlink (src_name) == 0))
1621 /* Pretend the rename succeeded, so the caller (mv)
1622 doesn't end up removing the source file. */
1623 if (rename_succeeded)
1624 *rename_succeeded = true;
1625 if (unlink_src && x->verbose)
1626 printf (_("removed %s\n"), quote (src_name));
1627 return true;
1629 if (unlink_src)
1631 error (0, errno, _("cannot remove %s"), quote (src_name));
1632 return false;
1635 else
1637 if (! S_ISDIR (src_mode)
1638 && (x->interactive == I_ALWAYS_NO
1639 || (x->interactive == I_ASK_USER
1640 && (overwrite_prompt (dst_name, &dst_sb), 1)
1641 && ! yesno ())))
1642 return true;
1645 if (return_now)
1646 return true;
1648 if (!S_ISDIR (dst_sb.st_mode))
1650 if (S_ISDIR (src_mode))
1652 if (x->move_mode && x->backup_type != no_backups)
1654 /* Moving a directory onto an existing
1655 non-directory is ok only with --backup. */
1657 else
1659 error (0, 0,
1660 _("cannot overwrite non-directory %s with directory %s"),
1661 quote_n (0, dst_name), quote_n (1, src_name));
1662 return false;
1666 /* Don't let the user destroy their data, even if they try hard:
1667 This mv command must fail (likewise for cp):
1668 rm -rf a b c; mkdir a b c; touch a/f b/f; mv a/f b/f c
1669 Otherwise, the contents of b/f would be lost.
1670 In the case of `cp', b/f would be lost if the user simulated
1671 a move using cp and rm.
1672 Note that it works fine if you use --backup=numbered. */
1673 if (command_line_arg
1674 && x->backup_type != numbered_backups
1675 && seen_file (x->dest_info, dst_name, &dst_sb))
1677 error (0, 0,
1678 _("will not overwrite just-created %s with %s"),
1679 quote_n (0, dst_name), quote_n (1, src_name));
1680 return false;
1684 if (!S_ISDIR (src_mode))
1686 if (S_ISDIR (dst_sb.st_mode))
1688 if (x->move_mode && x->backup_type != no_backups)
1690 /* Moving a non-directory onto an existing
1691 directory is ok only with --backup. */
1693 else
1695 error (0, 0,
1696 _("cannot overwrite directory %s with non-directory"),
1697 quote (dst_name));
1698 return false;
1703 if (x->move_mode)
1705 /* Don't allow user to move a directory onto a non-directory. */
1706 if (S_ISDIR (src_sb.st_mode) && !S_ISDIR (dst_sb.st_mode)
1707 && x->backup_type == no_backups)
1709 error (0, 0,
1710 _("cannot move directory onto non-directory: %s -> %s"),
1711 quote_n (0, src_name), quote_n (0, dst_name));
1712 return false;
1716 if (x->backup_type != no_backups
1717 /* Don't try to back up a destination if the last
1718 component of src_name is "." or "..". */
1719 && ! dot_or_dotdot (last_component (src_name))
1720 /* Create a backup of each destination directory in move mode,
1721 but not in copy mode. FIXME: it might make sense to add an
1722 option to suppress backup creation also for move mode.
1723 That would let one use mv to merge new content into an
1724 existing hierarchy. */
1725 && (x->move_mode || ! S_ISDIR (dst_sb.st_mode)))
1727 char *tmp_backup = find_backup_file_name (dst_name,
1728 x->backup_type);
1730 /* Detect (and fail) when creating the backup file would
1731 destroy the source file. Before, running the commands
1732 cd /tmp; rm -f a a~; : > a; echo A > a~; cp --b=simple a~ a
1733 would leave two zero-length files: a and a~. */
1734 /* FIXME: but simply change e.g., the final a~ to `./a~'
1735 and the source will still be destroyed. */
1736 if (STREQ (tmp_backup, src_name))
1738 const char *fmt;
1739 fmt = (x->move_mode
1740 ? _("backing up %s would destroy source; %s not moved")
1741 : _("backing up %s would destroy source; %s not copied"));
1742 error (0, 0, fmt,
1743 quote_n (0, dst_name),
1744 quote_n (1, src_name));
1745 free (tmp_backup);
1746 return false;
1749 /* FIXME: use fts:
1750 Using alloca for a file name that may be arbitrarily
1751 long is not recommended. In fact, even forming such a name
1752 should be discouraged. Eventually, this code will be rewritten
1753 to use fts, so using alloca here will be less of a problem. */
1754 ASSIGN_STRDUPA (dst_backup, tmp_backup);
1755 free (tmp_backup);
1756 if (rename (dst_name, dst_backup) != 0)
1758 if (errno != ENOENT)
1760 error (0, errno, _("cannot backup %s"), quote (dst_name));
1761 return false;
1763 else
1765 dst_backup = NULL;
1768 else
1770 backup_succeeded = true;
1772 new_dst = true;
1774 else if (! S_ISDIR (dst_sb.st_mode)
1775 /* Never unlink dst_name when in move mode. */
1776 && ! x->move_mode
1777 && (x->unlink_dest_before_opening
1778 || (x->preserve_links && 1 < dst_sb.st_nlink)
1779 || (x->dereference == DEREF_NEVER
1780 && ! S_ISREG (src_sb.st_mode))
1783 if (unlink (dst_name) != 0 && errno != ENOENT)
1785 error (0, errno, _("cannot remove %s"), quote (dst_name));
1786 return false;
1788 new_dst = true;
1789 if (x->verbose)
1790 printf (_("removed %s\n"), quote (dst_name));
1795 /* Ensure we don't try to copy through a symlink that was
1796 created by a prior call to this function. */
1797 if (command_line_arg
1798 && x->dest_info
1799 && ! x->move_mode
1800 && x->backup_type == no_backups)
1802 bool lstat_ok = true;
1803 struct stat tmp_buf;
1804 struct stat *dst_lstat_sb;
1806 /* If we called lstat above, good: use that data.
1807 Otherwise, call lstat here, in case dst_name is a symlink. */
1808 if (have_dst_lstat)
1809 dst_lstat_sb = &dst_sb;
1810 else
1812 if (lstat (dst_name, &tmp_buf) == 0)
1813 dst_lstat_sb = &tmp_buf;
1814 else
1815 lstat_ok = false;
1818 /* Never copy through a symlink we've just created. */
1819 if (lstat_ok
1820 && S_ISLNK (dst_lstat_sb->st_mode)
1821 && seen_file (x->dest_info, dst_name, dst_lstat_sb))
1823 error (0, 0,
1824 _("will not copy %s through just-created symlink %s"),
1825 quote_n (0, src_name), quote_n (1, dst_name));
1826 return false;
1830 /* If the source is a directory, we don't always create the destination
1831 directory. So --verbose should not announce anything until we're
1832 sure we'll create a directory. */
1833 if (x->verbose && !S_ISDIR (src_mode))
1834 emit_verbose (src_name, dst_name, backup_succeeded ? dst_backup : NULL);
1836 /* Associate the destination file name with the source device and inode
1837 so that if we encounter a matching dev/ino pair in the source tree
1838 we can arrange to create a hard link between the corresponding names
1839 in the destination tree.
1841 When using the --link (-l) option, there is no need to take special
1842 measures, because (barring race conditions) files that are hard-linked
1843 in the source tree will also be hard-linked in the destination tree.
1845 Sometimes, when preserving links, we have to record dev/ino even
1846 though st_nlink == 1:
1847 - when in move_mode, since we may be moving a group of N hard-linked
1848 files (via two or more command line arguments) to a different
1849 partition; the links may be distributed among the command line
1850 arguments (possibly hierarchies) so that the link count of
1851 the final, once-linked source file is reduced to 1 when it is
1852 considered below. But in this case (for mv) we don't need to
1853 incur the expense of recording the dev/ino => name mapping; all we
1854 really need is a lookup, to see if the dev/ino pair has already
1855 been copied.
1856 - when using -H and processing a command line argument;
1857 that command line argument could be a symlink pointing to another
1858 command line argument. With `cp -H --preserve=link', we hard-link
1859 those two destination files.
1860 - likewise for -L except that it applies to all files, not just
1861 command line arguments.
1863 Also, with --recursive, record dev/ino of each command-line directory.
1864 We'll use that info to detect this problem: cp -R dir dir. */
1866 if (x->move_mode && src_sb.st_nlink == 1)
1868 earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev);
1870 else if (x->preserve_links
1871 && !x->hard_link
1872 && (1 < src_sb.st_nlink
1873 || (command_line_arg
1874 && x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
1875 || x->dereference == DEREF_ALWAYS))
1877 earlier_file = remember_copied (dst_name, src_sb.st_ino, src_sb.st_dev);
1879 else if (x->recursive && S_ISDIR (src_mode))
1881 if (command_line_arg)
1882 earlier_file = remember_copied (dst_name, src_sb.st_ino, src_sb.st_dev);
1883 else
1884 earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev);
1887 /* Did we copy this inode somewhere else (in this command line argument)
1888 and therefore this is a second hard link to the inode? */
1890 if (earlier_file)
1892 /* Avoid damaging the destination file system by refusing to preserve
1893 hard-linked directories (which are found at least in Netapp snapshot
1894 directories). */
1895 if (S_ISDIR (src_mode))
1897 /* If src_name and earlier_file refer to the same directory entry,
1898 then warn about copying a directory into itself. */
1899 if (same_name (src_name, earlier_file))
1901 error (0, 0, _("cannot copy a directory, %s, into itself, %s"),
1902 quote_n (0, top_level_src_name),
1903 quote_n (1, top_level_dst_name));
1904 *copy_into_self = true;
1905 goto un_backup;
1907 else if (x->dereference == DEREF_ALWAYS)
1909 /* This happens when e.g., encountering a directory for the
1910 second or subsequent time via symlinks when cp is invoked
1911 with -R and -L. E.g.,
1912 rm -rf a b c d; mkdir a b c d; ln -s ../c a; ln -s ../c b;
1913 cp -RL a b d
1916 else
1918 error (0, 0, _("will not create hard link %s to directory %s"),
1919 quote_n (0, dst_name), quote_n (1, earlier_file));
1920 goto un_backup;
1923 else
1925 /* We want to guarantee that symlinks are not followed. */
1926 bool link_failed = (linkat (AT_FDCWD, earlier_file, AT_FDCWD,
1927 dst_name, 0) != 0);
1929 /* If the link failed because of an existing destination,
1930 remove that file and then call link again. */
1931 if (link_failed && errno == EEXIST)
1933 if (unlink (dst_name) != 0)
1935 error (0, errno, _("cannot remove %s"), quote (dst_name));
1936 goto un_backup;
1938 if (x->verbose)
1939 printf (_("removed %s\n"), quote (dst_name));
1940 link_failed = (linkat (AT_FDCWD, earlier_file, AT_FDCWD,
1941 dst_name, 0) != 0);
1944 if (link_failed)
1946 error (0, errno, _("cannot create hard link %s to %s"),
1947 quote_n (0, dst_name), quote_n (1, earlier_file));
1948 goto un_backup;
1951 return true;
1955 if (x->move_mode)
1957 if (rename (src_name, dst_name) == 0)
1959 if (x->verbose && S_ISDIR (src_mode))
1960 emit_verbose (src_name, dst_name,
1961 backup_succeeded ? dst_backup : NULL);
1963 if (rename_succeeded)
1964 *rename_succeeded = true;
1966 if (command_line_arg)
1968 /* Record destination dev/ino/name, so that if we are asked
1969 to overwrite that file again, we can detect it and fail. */
1970 /* It's fine to use the _source_ stat buffer (src_sb) to get the
1971 _destination_ dev/ino, since the rename above can't have
1972 changed those, and `mv' always uses lstat.
1973 We could limit it further by operating
1974 only on non-directories. */
1975 record_file (x->dest_info, dst_name, &src_sb);
1978 return true;
1981 /* FIXME: someday, consider what to do when moving a directory into
1982 itself but when source and destination are on different devices. */
1984 /* This happens when attempting to rename a directory to a
1985 subdirectory of itself. */
1986 if (errno == EINVAL)
1988 /* FIXME: this is a little fragile in that it relies on rename(2)
1989 failing with a specific errno value. Expect problems on
1990 non-POSIX systems. */
1991 error (0, 0, _("cannot move %s to a subdirectory of itself, %s"),
1992 quote_n (0, top_level_src_name),
1993 quote_n (1, top_level_dst_name));
1995 /* Note that there is no need to call forget_created here,
1996 (compare with the other calls in this file) since the
1997 destination directory didn't exist before. */
1999 *copy_into_self = true;
2000 /* FIXME-cleanup: Don't return true here; adjust mv.c accordingly.
2001 The only caller that uses this code (mv.c) ends up setting its
2002 exit status to nonzero when copy_into_self is nonzero. */
2003 return true;
2006 /* WARNING: there probably exist systems for which an inter-device
2007 rename fails with a value of errno not handled here.
2008 If/as those are reported, add them to the condition below.
2009 If this happens to you, please do the following and send the output
2010 to the bug-reporting address (e.g., in the output of cp --help):
2011 touch k; perl -e 'rename "k","/tmp/k" or print "$!(",$!+0,")\n"'
2012 where your current directory is on one partion and /tmp is the other.
2013 Also, please try to find the E* errno macro name corresponding to
2014 the diagnostic and parenthesized integer, and include that in your
2015 e-mail. One way to do that is to run a command like this
2016 find /usr/include/. -type f \
2017 | xargs grep 'define.*\<E[A-Z]*\>.*\<18\>' /dev/null
2018 where you'd replace `18' with the integer in parentheses that
2019 was output from the perl one-liner above.
2020 If necessary, of course, change `/tmp' to some other directory. */
2021 if (errno != EXDEV)
2023 /* There are many ways this can happen due to a race condition.
2024 When something happens between the initial XSTAT and the
2025 subsequent rename, we can get many different types of errors.
2026 For example, if the destination is initially a non-directory
2027 or non-existent, but it is created as a directory, the rename
2028 fails. If two `mv' commands try to rename the same file at
2029 about the same time, one will succeed and the other will fail.
2030 If the permissions on the directory containing the source or
2031 destination file are made too restrictive, the rename will
2032 fail. Etc. */
2033 error (0, errno,
2034 _("cannot move %s to %s"),
2035 quote_n (0, src_name), quote_n (1, dst_name));
2036 forget_created (src_sb.st_ino, src_sb.st_dev);
2037 return false;
2040 /* The rename attempt has failed. Remove any existing destination
2041 file so that a cross-device `mv' acts as if it were really using
2042 the rename syscall. */
2043 if (unlink (dst_name) != 0 && errno != ENOENT)
2045 error (0, errno,
2046 _("inter-device move failed: %s to %s; unable to remove target"),
2047 quote_n (0, src_name), quote_n (1, dst_name));
2048 forget_created (src_sb.st_ino, src_sb.st_dev);
2049 return false;
2052 new_dst = true;
2055 /* If the ownership might change, or if it is a directory (whose
2056 special mode bits may change after the directory is created),
2057 omit some permissions at first, so unauthorized users cannot nip
2058 in before the file is ready. */
2059 dst_mode_bits = (x->set_mode ? x->mode : src_mode) & CHMOD_MODE_BITS;
2060 omitted_permissions =
2061 (dst_mode_bits
2062 & (x->preserve_ownership ? S_IRWXG | S_IRWXO
2063 : S_ISDIR (src_mode) ? S_IWGRP | S_IWOTH
2064 : 0));
2066 delayed_ok = true;
2068 if (x->preserve_security_context)
2070 bool all_errors = !x->data_copy_required || x->require_preserve_context;
2071 bool some_errors = !all_errors && !x->reduce_diagnostics;
2072 security_context_t con;
2074 if (0 <= lgetfilecon (src_name, &con))
2076 if (setfscreatecon (con) < 0)
2078 if (all_errors || (some_errors && !errno_unsupported (errno)))
2079 error (0, errno,
2080 _("failed to set default file creation context to %s"),
2081 quote (con));
2082 if (x->require_preserve_context)
2084 freecon (con);
2085 return false;
2088 freecon (con);
2090 else
2092 if (all_errors || (some_errors && !errno_unsupported (errno)))
2094 error (0, errno,
2095 _("failed to get security context of %s"),
2096 quote (src_name));
2098 if (x->require_preserve_context)
2099 return false;
2103 if (S_ISDIR (src_mode))
2105 struct dir_list *dir;
2107 /* If this directory has been copied before during the
2108 recursion, there is a symbolic link to an ancestor
2109 directory of the symbolic link. It is impossible to
2110 continue to copy this, unless we've got an infinite disk. */
2112 if (is_ancestor (&src_sb, ancestors))
2114 error (0, 0, _("cannot copy cyclic symbolic link %s"),
2115 quote (src_name));
2116 goto un_backup;
2119 /* Insert the current directory in the list of parents. */
2121 dir = alloca (sizeof *dir);
2122 dir->parent = ancestors;
2123 dir->ino = src_sb.st_ino;
2124 dir->dev = src_sb.st_dev;
2126 if (new_dst || !S_ISDIR (dst_sb.st_mode))
2128 /* POSIX says mkdir's behavior is implementation-defined when
2129 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
2130 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
2131 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
2132 if (mkdir (dst_name, dst_mode_bits & ~omitted_permissions) != 0)
2134 error (0, errno, _("cannot create directory %s"),
2135 quote (dst_name));
2136 goto un_backup;
2139 /* We need search and write permissions to the new directory
2140 for writing the directory's contents. Check if these
2141 permissions are there. */
2143 if (lstat (dst_name, &dst_sb) != 0)
2145 error (0, errno, _("cannot stat %s"), quote (dst_name));
2146 goto un_backup;
2148 else if ((dst_sb.st_mode & S_IRWXU) != S_IRWXU)
2150 /* Make the new directory searchable and writable. */
2152 dst_mode = dst_sb.st_mode;
2153 restore_dst_mode = true;
2155 if (lchmod (dst_name, dst_mode | S_IRWXU) != 0)
2157 error (0, errno, _("setting permissions for %s"),
2158 quote (dst_name));
2159 goto un_backup;
2163 /* Record the created directory's inode and device numbers into
2164 the search structure, so that we can avoid copying it again.
2165 Do this only for the first directory that is created for each
2166 source command line argument. */
2167 if (!*first_dir_created_per_command_line_arg)
2169 remember_copied (dst_name, dst_sb.st_ino, dst_sb.st_dev);
2170 *first_dir_created_per_command_line_arg = true;
2173 if (x->verbose)
2174 emit_verbose (src_name, dst_name, NULL);
2177 /* Decide whether to copy the contents of the directory. */
2178 if (x->one_file_system && device != 0 && device != src_sb.st_dev)
2180 /* Here, we are crossing a file system boundary and cp's -x option
2181 is in effect: so don't copy the contents of this directory. */
2183 else
2185 /* Copy the contents of the directory. Don't just return if
2186 this fails -- otherwise, the failure to read a single file
2187 in a source directory would cause the containing destination
2188 directory not to have owner/perms set properly. */
2189 delayed_ok = copy_dir (src_name, dst_name, new_dst, &src_sb, dir, x,
2190 first_dir_created_per_command_line_arg,
2191 copy_into_self);
2194 else if (x->symbolic_link)
2196 dest_is_symlink = true;
2197 if (*src_name != '/')
2199 /* Check that DST_NAME denotes a file in the current directory. */
2200 struct stat dot_sb;
2201 struct stat dst_parent_sb;
2202 char *dst_parent;
2203 bool in_current_dir;
2205 dst_parent = dir_name (dst_name);
2207 in_current_dir = (STREQ (".", dst_parent)
2208 /* If either stat call fails, it's ok not to report
2209 the failure and say dst_name is in the current
2210 directory. Other things will fail later. */
2211 || stat (".", &dot_sb) != 0
2212 || stat (dst_parent, &dst_parent_sb) != 0
2213 || SAME_INODE (dot_sb, dst_parent_sb));
2214 free (dst_parent);
2216 if (! in_current_dir)
2218 error (0, 0,
2219 _("%s: can make relative symbolic links only in current directory"),
2220 quote (dst_name));
2221 goto un_backup;
2224 if (symlink (src_name, dst_name) != 0)
2226 error (0, errno, _("cannot create symbolic link %s to %s"),
2227 quote_n (0, dst_name), quote_n (1, src_name));
2228 goto un_backup;
2232 /* POSIX 2008 states that it is implementation-defined whether
2233 link() on a symlink creates a hard-link to the symlink, or only
2234 to the referent (effectively dereferencing the symlink) (POSIX
2235 2001 required the latter behavior, although many systems provided
2236 the former). Yet cp, invoked with `--link --no-dereference',
2237 should not follow the link. We can approximate the desired
2238 behavior by skipping this hard-link creating block and instead
2239 copying the symlink, via the `S_ISLNK'- copying code below.
2240 LINK_FOLLOWS_SYMLINKS is tri-state; if it is -1, we don't know
2241 how link() behaves, so we use the fallback case for safety.
2243 Note gnulib's linkat module, guarantees that the symlink is not
2244 dereferenced. However its emulation currently doesn't maintain
2245 timestamps or ownership so we only call it when we know the
2246 emulation will not be needed. */
2247 else if (x->hard_link
2248 && !(LINK_FOLLOWS_SYMLINKS && S_ISLNK (src_mode)
2249 && x->dereference == DEREF_NEVER))
2251 if (linkat (AT_FDCWD, src_name, AT_FDCWD, dst_name, 0))
2253 error (0, errno, _("cannot create link %s"), quote (dst_name));
2254 goto un_backup;
2257 else if (S_ISREG (src_mode)
2258 || (x->copy_as_regular && !S_ISLNK (src_mode)))
2260 copied_as_regular = true;
2261 /* POSIX says the permission bits of the source file must be
2262 used as the 3rd argument in the open call. Historical
2263 practice passed all the source mode bits to 'open', but the extra
2264 bits were ignored, so it should be the same either way. */
2265 if (! copy_reg (src_name, dst_name, x, src_mode & S_IRWXUGO,
2266 omitted_permissions, &new_dst, &src_sb))
2267 goto un_backup;
2269 else if (S_ISFIFO (src_mode))
2271 /* Use mknod, rather than mkfifo, because the former preserves
2272 the special mode bits of a fifo on Solaris 10, while mkfifo
2273 does not. But fall back on mkfifo, because on some BSD systems,
2274 mknod always fails when asked to create a FIFO. */
2275 if (mknod (dst_name, src_mode & ~omitted_permissions, 0) != 0)
2276 if (mkfifo (dst_name, src_mode & ~S_IFIFO & ~omitted_permissions) != 0)
2278 error (0, errno, _("cannot create fifo %s"), quote (dst_name));
2279 goto un_backup;
2282 else if (S_ISBLK (src_mode) || S_ISCHR (src_mode) || S_ISSOCK (src_mode))
2284 if (mknod (dst_name, src_mode & ~omitted_permissions, src_sb.st_rdev)
2285 != 0)
2287 error (0, errno, _("cannot create special file %s"),
2288 quote (dst_name));
2289 goto un_backup;
2292 else if (S_ISLNK (src_mode))
2294 char *src_link_val = areadlink_with_size (src_name, src_sb.st_size);
2295 dest_is_symlink = true;
2296 if (src_link_val == NULL)
2298 error (0, errno, _("cannot read symbolic link %s"), quote (src_name));
2299 goto un_backup;
2302 if (symlink (src_link_val, dst_name) == 0)
2303 free (src_link_val);
2304 else
2306 int saved_errno = errno;
2307 bool same_link = false;
2308 if (x->update && !new_dst && S_ISLNK (dst_sb.st_mode)
2309 && dst_sb.st_size == strlen (src_link_val))
2311 /* See if the destination is already the desired symlink.
2312 FIXME: This behavior isn't documented, and seems wrong
2313 in some cases, e.g., if the destination symlink has the
2314 wrong ownership, permissions, or time stamps. */
2315 char *dest_link_val =
2316 areadlink_with_size (dst_name, dst_sb.st_size);
2317 if (dest_link_val && STREQ (dest_link_val, src_link_val))
2318 same_link = true;
2319 free (dest_link_val);
2321 free (src_link_val);
2323 if (! same_link)
2325 error (0, saved_errno, _("cannot create symbolic link %s"),
2326 quote (dst_name));
2327 goto un_backup;
2331 if (x->preserve_security_context)
2332 restore_default_fscreatecon_or_die ();
2334 if (x->preserve_ownership)
2336 /* Preserve the owner and group of the just-`copied'
2337 symbolic link, if possible. */
2338 if (HAVE_LCHOWN
2339 && lchown (dst_name, src_sb.st_uid, src_sb.st_gid) != 0
2340 && ! chown_failure_ok (x))
2342 error (0, errno, _("failed to preserve ownership for %s"),
2343 dst_name);
2344 goto un_backup;
2346 else
2348 /* Can't preserve ownership of symlinks.
2349 FIXME: maybe give a warning or even error for symlinks
2350 in directories with the sticky bit set -- there, not
2351 preserving owner/group is a potential security problem. */
2355 else
2357 error (0, 0, _("%s has unknown file type"), quote (src_name));
2358 goto un_backup;
2361 if (command_line_arg && x->dest_info)
2363 /* Now that the destination file is very likely to exist,
2364 add its info to the set. */
2365 struct stat sb;
2366 if (lstat (dst_name, &sb) == 0)
2367 record_file (x->dest_info, dst_name, &sb);
2370 /* If we've just created a hard-link due to cp's --link option,
2371 we're done. */
2372 if (x->hard_link && ! S_ISDIR (src_mode)
2373 && !(LINK_FOLLOWS_SYMLINKS && S_ISLNK (src_mode)
2374 && x->dereference == DEREF_NEVER))
2375 return delayed_ok;
2377 if (copied_as_regular)
2378 return delayed_ok;
2380 /* POSIX says that `cp -p' must restore the following:
2381 - permission bits
2382 - setuid, setgid bits
2383 - owner and group
2384 If it fails to restore any of those, we may give a warning but
2385 the destination must not be removed.
2386 FIXME: implement the above. */
2388 /* Adjust the times (and if possible, ownership) for the copy.
2389 chown turns off set[ug]id bits for non-root,
2390 so do the chmod last. */
2392 if (x->preserve_timestamps)
2394 struct timespec timespec[2];
2395 timespec[0] = get_stat_atime (&src_sb);
2396 timespec[1] = get_stat_mtime (&src_sb);
2398 if ((dest_is_symlink
2399 ? utimens_symlink (dst_name, timespec)
2400 : utimens (dst_name, timespec))
2401 != 0)
2403 error (0, errno, _("preserving times for %s"), quote (dst_name));
2404 if (x->require_preserve)
2405 return false;
2409 /* The operations beyond this point may dereference a symlink. */
2410 if (dest_is_symlink)
2411 return delayed_ok;
2413 /* Avoid calling chown if we know it's not necessary. */
2414 if (x->preserve_ownership
2415 && (new_dst || !SAME_OWNER_AND_GROUP (src_sb, dst_sb)))
2417 switch (set_owner (x, dst_name, -1, &src_sb, new_dst, &dst_sb))
2419 case -1:
2420 return false;
2422 case 0:
2423 src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX);
2424 break;
2428 set_author (dst_name, -1, &src_sb);
2430 if (x->preserve_xattr && ! copy_attr (src_name, -1, dst_name, -1, x)
2431 && x->require_preserve_xattr)
2432 return false;
2434 if (x->preserve_mode || x->move_mode)
2436 if (copy_acl (src_name, -1, dst_name, -1, src_mode) != 0
2437 && x->require_preserve)
2438 return false;
2440 else if (x->set_mode)
2442 if (set_acl (dst_name, -1, x->mode) != 0)
2443 return false;
2445 else
2447 if (omitted_permissions)
2449 omitted_permissions &= ~ cached_umask ();
2451 if (omitted_permissions && !restore_dst_mode)
2453 /* Permissions were deliberately omitted when the file
2454 was created due to security concerns. See whether
2455 they need to be re-added now. It'd be faster to omit
2456 the lstat, but deducing the current destination mode
2457 is tricky in the presence of implementation-defined
2458 rules for special mode bits. */
2459 if (new_dst && lstat (dst_name, &dst_sb) != 0)
2461 error (0, errno, _("cannot stat %s"), quote (dst_name));
2462 return false;
2464 dst_mode = dst_sb.st_mode;
2465 if (omitted_permissions & ~dst_mode)
2466 restore_dst_mode = true;
2470 if (restore_dst_mode)
2472 if (lchmod (dst_name, dst_mode | omitted_permissions) != 0)
2474 error (0, errno, _("preserving permissions for %s"),
2475 quote (dst_name));
2476 if (x->require_preserve)
2477 return false;
2482 return delayed_ok;
2484 un_backup:
2486 if (x->preserve_security_context)
2487 restore_default_fscreatecon_or_die ();
2489 /* We have failed to create the destination file.
2490 If we've just added a dev/ino entry via the remember_copied
2491 call above (i.e., unless we've just failed to create a hard link),
2492 remove the entry associating the source dev/ino with the
2493 destination file name, so we don't try to `preserve' a link
2494 to a file we didn't create. */
2495 if (earlier_file == NULL)
2496 forget_created (src_sb.st_ino, src_sb.st_dev);
2498 if (dst_backup)
2500 if (rename (dst_backup, dst_name) != 0)
2501 error (0, errno, _("cannot un-backup %s"), quote (dst_name));
2502 else
2504 if (x->verbose)
2505 printf (_("%s -> %s (unbackup)\n"),
2506 quote_n (0, dst_backup), quote_n (1, dst_name));
2509 return false;
2512 static bool
2513 valid_options (const struct cp_options *co)
2515 assert (co != NULL);
2516 assert (VALID_BACKUP_TYPE (co->backup_type));
2517 assert (VALID_SPARSE_MODE (co->sparse_mode));
2518 assert (VALID_REFLINK_MODE (co->reflink_mode));
2519 assert (!(co->hard_link && co->symbolic_link));
2520 assert (!
2521 (co->reflink_mode == REFLINK_ALWAYS
2522 && co->sparse_mode != SPARSE_AUTO));
2523 return true;
2526 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
2527 any type. NONEXISTENT_DST should be true if the file DST_NAME
2528 is known not to exist (e.g., because its parent directory was just
2529 created); NONEXISTENT_DST should be false if DST_NAME might already
2530 exist. OPTIONS is ... FIXME-describe
2531 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
2532 same as) DST_NAME; otherwise, set clear it.
2533 Return true if successful. */
2535 extern bool
2536 copy (char const *src_name, char const *dst_name,
2537 bool nonexistent_dst, const struct cp_options *options,
2538 bool *copy_into_self, bool *rename_succeeded)
2540 assert (valid_options (options));
2542 /* Record the file names: they're used in case of error, when copying
2543 a directory into itself. I don't like to make these tools do *any*
2544 extra work in the common case when that work is solely to handle
2545 exceptional cases, but in this case, I don't see a way to derive the
2546 top level source and destination directory names where they're used.
2547 An alternative is to use COPY_INTO_SELF and print the diagnostic
2548 from every caller -- but I don't want to do that. */
2549 top_level_src_name = src_name;
2550 top_level_dst_name = dst_name;
2552 bool first_dir_created_per_command_line_arg = false;
2553 return copy_internal (src_name, dst_name, nonexistent_dst, 0, NULL,
2554 options, true,
2555 &first_dir_created_per_command_line_arg,
2556 copy_into_self, rename_succeeded);
2559 /* Set *X to the default options for a value of type struct cp_options. */
2561 extern void
2562 cp_options_default (struct cp_options *x)
2564 memset (x, 0, sizeof *x);
2565 #ifdef PRIV_FILE_CHOWN
2567 priv_set_t *pset = priv_allocset ();
2568 if (!pset)
2569 xalloc_die ();
2570 if (getppriv (PRIV_EFFECTIVE, pset) == 0)
2572 x->chown_privileges = priv_ismember (pset, PRIV_FILE_CHOWN);
2573 x->owner_privileges = priv_ismember (pset, PRIV_FILE_OWNER);
2575 priv_freeset (pset);
2577 #else
2578 x->chown_privileges = x->owner_privileges = (geteuid () == 0);
2579 #endif
2582 /* Return true if it's OK for chown to fail, where errno is
2583 the error number that chown failed with and X is the copying
2584 option set. */
2586 extern bool
2587 chown_failure_ok (struct cp_options const *x)
2589 /* If non-root uses -p, it's ok if we can't preserve ownership.
2590 But root probably wants to know, e.g. if NFS disallows it,
2591 or if the target system doesn't support file ownership. */
2593 return ((errno == EPERM || errno == EINVAL) && !x->chown_privileges);
2596 /* Similarly, return true if it's OK for chmod and similar operations
2597 to fail, where errno is the error number that chmod failed with and
2598 X is the copying option set. */
2600 static bool
2601 owner_failure_ok (struct cp_options const *x)
2603 return ((errno == EPERM || errno == EINVAL) && !x->owner_privileges);
2606 /* Return the user's umask, caching the result. */
2608 extern mode_t
2609 cached_umask (void)
2611 static mode_t mask = (mode_t) -1;
2612 if (mask == (mode_t) -1)
2614 mask = umask (0);
2615 umask (mask);
2617 return mask;