copy: adjust fiemap handling of sparse files
[coreutils/ericb.git] / src / copy.c
blob104652d0637af2339d111efc3d9c210fdecae5b2
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 "file-set.h"
43 #include "filemode.h"
44 #include "filenamecat.h"
45 #include "full-write.h"
46 #include "hash.h"
47 #include "hash-triple.h"
48 #include "ignore-value.h"
49 #include "quote.h"
50 #include "same.h"
51 #include "savedir.h"
52 #include "stat-time.h"
53 #include "utimecmp.h"
54 #include "utimens.h"
55 #include "write-any-file.h"
56 #include "areadlink.h"
57 #include "yesno.h"
59 #if USE_XATTR
60 # include <attr/error_context.h>
61 # include <attr/libattr.h>
62 # include <stdarg.h>
63 # include "verror.h"
64 #endif
66 #ifndef HAVE_FCHOWN
67 # define HAVE_FCHOWN false
68 # define fchown(fd, uid, gid) (-1)
69 #endif
71 #ifndef HAVE_LCHOWN
72 # define HAVE_LCHOWN false
73 # define lchown(name, uid, gid) chown (name, uid, gid)
74 #endif
76 #ifndef HAVE_MKFIFO
77 static int
78 rpl_mkfifo (char const *file, mode_t mode)
80 errno = ENOTSUP;
81 return -1;
83 # define mkfifo rpl_mkfifo
84 #endif
86 #ifndef USE_ACL
87 # define USE_ACL 0
88 #endif
90 #define SAME_OWNER(A, B) ((A).st_uid == (B).st_uid)
91 #define SAME_GROUP(A, B) ((A).st_gid == (B).st_gid)
92 #define SAME_OWNER_AND_GROUP(A, B) (SAME_OWNER (A, B) && SAME_GROUP (A, B))
94 struct dir_list
96 struct dir_list *parent;
97 ino_t ino;
98 dev_t dev;
101 /* Initial size of the cp.dest_info hash table. */
102 #define DEST_INFO_INITIAL_CAPACITY 61
104 static bool copy_internal (char const *src_name, char const *dst_name,
105 bool new_dst, dev_t device,
106 struct dir_list *ancestors,
107 const struct cp_options *x,
108 bool command_line_arg,
109 bool *first_dir_created_per_command_line_arg,
110 bool *copy_into_self,
111 bool *rename_succeeded);
112 static bool owner_failure_ok (struct cp_options const *x);
114 /* Pointers to the file names: they're used in the diagnostic that is issued
115 when we detect the user is trying to copy a directory into itself. */
116 static char const *top_level_src_name;
117 static char const *top_level_dst_name;
119 /* Set the timestamp of symlink, FILE, to TIMESPEC.
120 If this system lacks support for that, simply return 0. */
121 static inline int
122 utimens_symlink (char const *file, struct timespec const *timespec)
124 int err = lutimens (file, timespec);
125 /* When configuring on a system with new headers and libraries, and
126 running on one with a kernel that is old enough to lack the syscall,
127 utimensat fails with ENOSYS. Ignore that. */
128 if (err && errno == ENOSYS)
129 err = 0;
130 return err;
133 /* Copy the regular file open on SRC_FD/SRC_NAME to DST_FD/DST_NAME,
134 honoring the MAKE_HOLES setting and using the BUF_SIZE-byte buffer
135 BUF for temporary storage. Copy no more than MAX_N_READ bytes.
136 Return true upon successful completion;
137 print a diagnostic and return false upon error.
138 Note that for best results, BUF should be "well"-aligned.
139 BUF must have sizeof(uintptr_t)-1 bytes of additional space
140 beyond BUF[BUF_SIZE-1].
141 Set *LAST_WRITE_MADE_HOLE to true if the final operation on
142 DEST_FD introduced a hole. Set *TOTAL_N_READ to the number of
143 bytes read. */
144 static bool
145 sparse_copy (int src_fd, int dest_fd, char *buf, size_t buf_size,
146 bool make_holes,
147 char const *src_name, char const *dst_name,
148 uintmax_t max_n_read, off_t *total_n_read,
149 bool *last_write_made_hole)
151 typedef uintptr_t word;
152 *last_write_made_hole = false;
153 *total_n_read = 0;
155 while (max_n_read)
157 word *wp = NULL;
159 ssize_t n_read = read (src_fd, buf, MIN (max_n_read, buf_size));
160 if (n_read < 0)
162 if (errno == EINTR)
163 continue;
164 error (0, errno, _("reading %s"), quote (src_name));
165 return false;
167 if (n_read == 0)
168 break;
169 max_n_read -= n_read;
170 *total_n_read += n_read;
172 if (make_holes)
174 char *cp;
176 /* Sentinel to stop loop. */
177 buf[n_read] = '\1';
178 #ifdef lint
179 /* Usually, buf[n_read] is not the byte just before a "word"
180 (aka uintptr_t) boundary. In that case, the word-oriented
181 test below (*wp++ == 0) would read some uninitialized bytes
182 after the sentinel. To avoid false-positive reports about
183 this condition (e.g., from a tool like valgrind), set the
184 remaining bytes -- to any value. */
185 memset (buf + n_read + 1, 0, sizeof (word) - 1);
186 #endif
188 /* Find first nonzero *word*, or the word with the sentinel. */
190 wp = (word *) buf;
191 while (*wp++ == 0)
192 continue;
194 /* Find the first nonzero *byte*, or the sentinel. */
196 cp = (char *) (wp - 1);
197 while (*cp++ == 0)
198 continue;
200 if (cp <= buf + n_read)
201 /* Clear to indicate that a normal write is needed. */
202 wp = NULL;
203 else
205 /* We found the sentinel, so the whole input block was zero.
206 Make a hole. */
207 if (lseek (dest_fd, n_read, SEEK_CUR) < 0)
209 error (0, errno, _("cannot lseek %s"), quote (dst_name));
210 return false;
212 *last_write_made_hole = true;
216 if (!wp)
218 size_t n = n_read;
219 if (full_write (dest_fd, buf, n) != n)
221 error (0, errno, _("writing %s"), quote (dst_name));
222 return false;
224 *last_write_made_hole = false;
226 /* It is tempting to return early here upon a short read from a
227 regular file. That would save the final read syscall for each
228 file. Unfortunately that doesn't work for certain files in
229 /proc with linux kernels from at least 2.6.9 .. 2.6.29. */
233 return true;
236 /* Perform the O(1) btrfs clone operation, if possible.
237 Upon success, return 0. Otherwise, return -1 and set errno. */
238 static inline int
239 clone_file (int dest_fd, int src_fd)
241 #ifdef __linux__
242 # undef BTRFS_IOCTL_MAGIC
243 # define BTRFS_IOCTL_MAGIC 0x94
244 # undef BTRFS_IOC_CLONE
245 # define BTRFS_IOC_CLONE _IOW (BTRFS_IOCTL_MAGIC, 9, int)
246 return ioctl (dest_fd, BTRFS_IOC_CLONE, src_fd);
247 #else
248 (void) dest_fd;
249 (void) src_fd;
250 errno = ENOTSUP;
251 return -1;
252 #endif
255 /* Write N_BYTES zero bytes to file descriptor FD. Return true if successful.
256 Upon write failure, set errno and return false. */
257 static bool
258 write_zeros (int fd, uint64_t n_bytes)
260 static char *zeros;
261 static size_t nz = IO_BUFSIZE;
263 /* Attempt to use a relatively large calloc'd source buffer for
264 efficiency, but if that allocation fails, resort to a smaller
265 statically allocated one. */
266 if (zeros == NULL)
268 static char fallback[1024];
269 zeros = calloc (nz, 1);
270 if (zeros == NULL)
272 zeros = fallback;
273 nz = sizeof fallback;
277 while (n_bytes)
279 uint64_t n = MIN (nz, n_bytes);
280 if ((full_write (fd, zeros, n)) != n)
281 return false;
282 n_bytes -= n;
285 return true;
288 /* Perform an efficient extent copy, if possible. This avoids
289 the overhead of detecting holes in hole-introducing/preserving
290 copy, and thus makes copying sparse files much more efficient.
291 Upon a successful copy, return true. If the initial extent scan
292 fails, set *NORMAL_COPY_REQUIRED to true and return false.
293 Upon any other failure, set *NORMAL_COPY_REQUIRED to false and
294 return false. */
295 static bool
296 extent_copy (int src_fd, int dest_fd, char *buf, size_t buf_size,
297 off_t src_total_size, enum Sparse_type sparse_mode,
298 char const *src_name, char const *dst_name,
299 bool *require_normal_copy)
301 struct extent_scan scan;
302 off_t last_ext_start = 0;
303 uint64_t last_ext_len = 0;
305 /* Keep track of the output position.
306 We may need this at the end, for a final ftruncate. */
307 off_t dest_pos = 0;
309 extent_scan_init (src_fd, &scan);
311 *require_normal_copy = false;
312 bool wrote_hole_at_eof = true;
315 bool ok = extent_scan_read (&scan);
316 if (! ok)
318 if (scan.hit_final_extent)
319 break;
321 if (scan.initial_scan_failed)
323 *require_normal_copy = true;
324 return false;
327 error (0, errno, _("%s: failed to get extents info"),
328 quote (src_name));
329 return false;
332 unsigned int i;
333 for (i = 0; i < scan.ei_count; i++)
335 off_t ext_start = scan.ext_info[i].ext_logical;
336 uint64_t ext_len = scan.ext_info[i].ext_length;
337 uint64_t hole_size = ext_start - last_ext_start - last_ext_len;
339 if (hole_size)
341 if (lseek (src_fd, ext_start, SEEK_SET) < 0)
343 error (0, errno, _("cannot lseek %s"), quote (src_name));
344 fail:
345 extent_scan_free (&scan);
346 return false;
349 if (sparse_mode != SPARSE_NEVER)
351 if (lseek (dest_fd, ext_start, SEEK_SET) < 0)
353 error (0, errno, _("cannot lseek %s"), quote (dst_name));
354 goto fail;
357 else
359 /* When not inducing holes and when there is a hole between
360 the end of the previous extent and the beginning of the
361 current one, write zeros to the destination file. */
362 if (! write_zeros (dest_fd, hole_size))
364 error (0, errno, _("%s: write failed"), quote (dst_name));
365 goto fail;
370 last_ext_start = ext_start;
371 last_ext_len = ext_len;
373 off_t n_read;
374 if ( ! sparse_copy (src_fd, dest_fd, buf, buf_size,
375 sparse_mode == SPARSE_ALWAYS, src_name, dst_name,
376 ext_len, &n_read,
377 &wrote_hole_at_eof))
378 return false;
380 dest_pos = ext_start + n_read;
383 /* Release the space allocated to scan->ext_info. */
384 extent_scan_free (&scan);
387 while (! scan.hit_final_extent);
389 /* When the source file ends with a hole, we have to do a little more work,
390 since the above copied only up to and including the final extent.
391 In order to complete the copy, we may have to insert a hole or write
392 zeros in the destination corresponding to the source file's hole-at-EOF.
394 In addition, if the final extent was a block of zeros at EOF and we've
395 just converted them to a hole in the destination, we must call ftruncate
396 here in order to record the proper length in the destination. */
397 if ((dest_pos < src_total_size || wrote_hole_at_eof)
398 && (sparse_mode != SPARSE_NEVER
399 ? ftruncate (dest_fd, src_total_size)
400 : ! write_zeros (dest_fd, src_total_size - dest_pos)))
402 error (0, errno, _("failed to extend %s"), quote (dst_name));
403 return false;
406 return true;
409 /* FIXME: describe */
410 /* FIXME: rewrite this to use a hash table so we avoid the quadratic
411 performance hit that's probably noticeable only on trees deeper
412 than a few hundred levels. See use of active_dir_map in remove.c */
414 static bool
415 is_ancestor (const struct stat *sb, const struct dir_list *ancestors)
417 while (ancestors != 0)
419 if (ancestors->ino == sb->st_ino && ancestors->dev == sb->st_dev)
420 return true;
421 ancestors = ancestors->parent;
423 return false;
426 static bool
427 errno_unsupported (int err)
429 return err == ENOTSUP || err == ENODATA;
432 #if USE_XATTR
433 static void
434 copy_attr_error (struct error_context *ctx ATTRIBUTE_UNUSED,
435 char const *fmt, ...)
437 if (!errno_unsupported (errno))
439 int err = errno;
440 va_list ap;
442 /* use verror module to print error message */
443 va_start (ap, fmt);
444 verror (0, err, fmt, ap);
445 va_end (ap);
449 static void
450 copy_attr_allerror (struct error_context *ctx ATTRIBUTE_UNUSED,
451 char const *fmt, ...)
453 int err = errno;
454 va_list ap;
456 /* use verror module to print error message */
457 va_start (ap, fmt);
458 verror (0, err, fmt, ap);
459 va_end (ap);
462 static char const *
463 copy_attr_quote (struct error_context *ctx ATTRIBUTE_UNUSED, char const *str)
465 return quote (str);
468 static void
469 copy_attr_free (struct error_context *ctx ATTRIBUTE_UNUSED,
470 char const *str ATTRIBUTE_UNUSED)
474 /* If positive SRC_FD and DST_FD descriptors are passed,
475 then copy by fd, otherwise copy by name. */
477 static bool
478 copy_attr (char const *src_path, int src_fd,
479 char const *dst_path, int dst_fd, struct cp_options const *x)
481 int ret;
482 bool all_errors = (!x->data_copy_required || x->require_preserve_xattr);
483 bool some_errors = (!all_errors && !x->reduce_diagnostics);
484 struct error_context ctx =
486 .error = all_errors ? copy_attr_allerror : copy_attr_error,
487 .quote = copy_attr_quote,
488 .quote_free = copy_attr_free
490 if (0 <= src_fd && 0 <= dst_fd)
491 ret = attr_copy_fd (src_path, src_fd, dst_path, dst_fd, 0,
492 (all_errors || some_errors ? &ctx : NULL));
493 else
494 ret = attr_copy_file (src_path, dst_path, 0,
495 (all_errors || some_errors ? &ctx : NULL));
497 return ret == 0;
499 #else /* USE_XATTR */
501 static bool
502 copy_attr (char const *src_path ATTRIBUTE_UNUSED,
503 int src_fd ATTRIBUTE_UNUSED,
504 char const *dst_path ATTRIBUTE_UNUSED,
505 int dst_fd ATTRIBUTE_UNUSED,
506 struct cp_options const *x ATTRIBUTE_UNUSED)
508 return true;
510 #endif /* USE_XATTR */
512 /* Read the contents of the directory SRC_NAME_IN, and recursively
513 copy the contents to DST_NAME_IN. NEW_DST is true if
514 DST_NAME_IN is a directory that was created previously in the
515 recursion. SRC_SB and ANCESTORS describe SRC_NAME_IN.
516 Set *COPY_INTO_SELF if SRC_NAME_IN is a parent of
517 FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG FIXME
518 (or the same as) DST_NAME_IN; otherwise, clear it.
519 Return true if successful. */
521 static bool
522 copy_dir (char const *src_name_in, char const *dst_name_in, bool new_dst,
523 const struct stat *src_sb, struct dir_list *ancestors,
524 const struct cp_options *x,
525 bool *first_dir_created_per_command_line_arg,
526 bool *copy_into_self)
528 char *name_space;
529 char *namep;
530 struct cp_options non_command_line_options = *x;
531 bool ok = true;
533 name_space = savedir (src_name_in);
534 if (name_space == NULL)
536 /* This diagnostic is a bit vague because savedir can fail in
537 several different ways. */
538 error (0, errno, _("cannot access %s"), quote (src_name_in));
539 return false;
542 /* For cp's -H option, dereference command line arguments, but do not
543 dereference symlinks that are found via recursive traversal. */
544 if (x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
545 non_command_line_options.dereference = DEREF_NEVER;
547 namep = name_space;
548 while (*namep != '\0')
550 bool local_copy_into_self;
551 char *src_name = file_name_concat (src_name_in, namep, NULL);
552 char *dst_name = file_name_concat (dst_name_in, namep, NULL);
554 ok &= copy_internal (src_name, dst_name, new_dst, src_sb->st_dev,
555 ancestors, &non_command_line_options, false,
556 first_dir_created_per_command_line_arg,
557 &local_copy_into_self, NULL);
558 *copy_into_self |= local_copy_into_self;
560 free (dst_name);
561 free (src_name);
563 /* If we're copying into self, there's no point in continuing,
564 and in fact, that would even infloop, now that we record only
565 the first created directory per command line argument. */
566 if (local_copy_into_self)
567 break;
569 namep += strlen (namep) + 1;
571 free (name_space);
572 return ok;
575 /* Set the owner and owning group of DEST_DESC to the st_uid and
576 st_gid fields of SRC_SB. If DEST_DESC is undefined (-1), set
577 the owner and owning group of DST_NAME instead; for
578 safety prefer lchown if the system supports it since no
579 symbolic links should be involved. DEST_DESC must
580 refer to the same file as DEST_NAME if defined.
581 Upon failure to set both UID and GID, try to set only the GID.
582 NEW_DST is true if the file was newly created; otherwise,
583 DST_SB is the status of the destination.
584 Return 1 if the initial syscall succeeds, 0 if it fails but it's OK
585 not to preserve ownership, -1 otherwise. */
587 static int
588 set_owner (const struct cp_options *x, char const *dst_name, int dest_desc,
589 struct stat const *src_sb, bool new_dst,
590 struct stat const *dst_sb)
592 uid_t uid = src_sb->st_uid;
593 gid_t gid = src_sb->st_gid;
595 /* Naively changing the ownership of an already-existing file before
596 changing its permissions would create a window of vulnerability if
597 the file's old permissions are too generous for the new owner and
598 group. Avoid the window by first changing to a restrictive
599 temporary mode if necessary. */
601 if (!new_dst && (x->preserve_mode || x->move_mode || x->set_mode))
603 mode_t old_mode = dst_sb->st_mode;
604 mode_t new_mode =
605 (x->preserve_mode || x->move_mode ? src_sb->st_mode : x->mode);
606 mode_t restrictive_temp_mode = old_mode & new_mode & S_IRWXU;
608 if ((USE_ACL
609 || (old_mode & CHMOD_MODE_BITS
610 & (~new_mode | S_ISUID | S_ISGID | S_ISVTX)))
611 && qset_acl (dst_name, dest_desc, restrictive_temp_mode) != 0)
613 if (! owner_failure_ok (x))
614 error (0, errno, _("clearing permissions for %s"),
615 quote (dst_name));
616 return -x->require_preserve;
620 if (HAVE_FCHOWN && dest_desc != -1)
622 if (fchown (dest_desc, uid, gid) == 0)
623 return 1;
624 if (errno == EPERM || errno == EINVAL)
626 /* We've failed to set *both*. Now, try to set just the group
627 ID, but ignore any failure here, and don't change errno. */
628 int saved_errno = errno;
629 ignore_value (fchown (dest_desc, -1, gid));
630 errno = saved_errno;
633 else
635 if (lchown (dst_name, uid, gid) == 0)
636 return 1;
637 if (errno == EPERM || errno == EINVAL)
639 /* We've failed to set *both*. Now, try to set just the group
640 ID, but ignore any failure here, and don't change errno. */
641 int saved_errno = errno;
642 ignore_value (lchown (dst_name, -1, gid));
643 errno = saved_errno;
647 if (! chown_failure_ok (x))
649 error (0, errno, _("failed to preserve ownership for %s"),
650 quote (dst_name));
651 if (x->require_preserve)
652 return -1;
655 return 0;
658 /* Set the st_author field of DEST_DESC to the st_author field of
659 SRC_SB. If DEST_DESC is undefined (-1), set the st_author field
660 of DST_NAME instead. DEST_DESC must refer to the same file as
661 DEST_NAME if defined. */
663 static void
664 set_author (const char *dst_name, int dest_desc, const struct stat *src_sb)
666 #if HAVE_STRUCT_STAT_ST_AUTHOR
667 /* FIXME: Modify the following code so that it does not
668 follow symbolic links. */
670 /* Preserve the st_author field. */
671 file_t file = (dest_desc < 0
672 ? file_name_lookup (dst_name, 0, 0)
673 : getdport (dest_desc));
674 if (file == MACH_PORT_NULL)
675 error (0, errno, _("failed to lookup file %s"), quote (dst_name));
676 else
678 error_t err = file_chauthor (file, src_sb->st_author);
679 if (err)
680 error (0, err, _("failed to preserve authorship for %s"),
681 quote (dst_name));
682 mach_port_deallocate (mach_task_self (), file);
684 #else
685 (void) dst_name;
686 (void) dest_desc;
687 (void) src_sb;
688 #endif
691 /* Change the file mode bits of the file identified by DESC or NAME to MODE.
692 Use DESC if DESC is valid and fchmod is available, NAME otherwise. */
694 static int
695 fchmod_or_lchmod (int desc, char const *name, mode_t mode)
697 #if HAVE_FCHMOD
698 if (0 <= desc)
699 return fchmod (desc, mode);
700 #endif
701 return lchmod (name, mode);
704 /* Copy a regular file from SRC_NAME to DST_NAME.
705 If the source file contains holes, copies holes and blocks of zeros
706 in the source file as holes in the destination file.
707 (Holes are read as zeroes by the `read' system call.)
708 When creating the destination, use DST_MODE & ~OMITTED_PERMISSIONS
709 as the third argument in the call to open, adding
710 OMITTED_PERMISSIONS after copying as needed.
711 X provides many option settings.
712 Return true if successful.
713 *NEW_DST is as in copy_internal.
714 SRC_SB is the result of calling XSTAT (aka stat) on SRC_NAME. */
716 static bool
717 copy_reg (char const *src_name, char const *dst_name,
718 const struct cp_options *x,
719 mode_t dst_mode, mode_t omitted_permissions, bool *new_dst,
720 struct stat const *src_sb)
722 char *buf;
723 char *buf_alloc = NULL;
724 char *name_alloc = NULL;
725 int dest_desc;
726 int dest_errno;
727 int source_desc;
728 mode_t src_mode = src_sb->st_mode;
729 struct stat sb;
730 struct stat src_open_sb;
731 bool return_val = true;
732 bool data_copy_required = x->data_copy_required;
734 source_desc = open (src_name,
735 (O_RDONLY | O_BINARY
736 | (x->dereference == DEREF_NEVER ? O_NOFOLLOW : 0)));
737 if (source_desc < 0)
739 error (0, errno, _("cannot open %s for reading"), quote (src_name));
740 return false;
743 if (fstat (source_desc, &src_open_sb) != 0)
745 error (0, errno, _("cannot fstat %s"), quote (src_name));
746 return_val = false;
747 goto close_src_desc;
750 /* Compare the source dev/ino from the open file to the incoming,
751 saved ones obtained via a previous call to stat. */
752 if (! SAME_INODE (*src_sb, src_open_sb))
754 error (0, 0,
755 _("skipping file %s, as it was replaced while being copied"),
756 quote (src_name));
757 return_val = false;
758 goto close_src_desc;
761 /* The semantics of the following open calls are mandated
762 by the specs for both cp and mv. */
763 if (! *new_dst)
765 dest_desc = open (dst_name, O_WRONLY | O_TRUNC | O_BINARY);
766 dest_errno = errno;
768 /* When using cp --preserve=context to copy to an existing destination,
769 use the default context rather than that of the source. Why?
770 1) the src context may prohibit writing, and
771 2) because it's more consistent to use the same context
772 that is used when the destination file doesn't already exist. */
773 if (x->preserve_security_context && 0 <= dest_desc)
775 bool all_errors = (!x->data_copy_required
776 || x->require_preserve_context);
777 bool some_errors = !all_errors && !x->reduce_diagnostics;
778 security_context_t con = NULL;
780 if (getfscreatecon (&con) < 0)
782 if (all_errors || (some_errors && !errno_unsupported (errno)))
783 error (0, errno, _("failed to get file system create context"));
784 if (x->require_preserve_context)
786 return_val = false;
787 goto close_src_and_dst_desc;
791 if (con)
793 if (fsetfilecon (dest_desc, con) < 0)
795 if (all_errors || (some_errors && !errno_unsupported (errno)))
796 error (0, errno,
797 _("failed to set the security context of %s to %s"),
798 quote_n (0, dst_name), quote_n (1, con));
799 if (x->require_preserve_context)
801 return_val = false;
802 freecon (con);
803 goto close_src_and_dst_desc;
806 freecon (con);
810 if (dest_desc < 0 && x->unlink_dest_after_failed_open)
812 if (unlink (dst_name) != 0)
814 error (0, errno, _("cannot remove %s"), quote (dst_name));
815 return_val = false;
816 goto close_src_desc;
818 if (x->verbose)
819 printf (_("removed %s\n"), quote (dst_name));
821 /* Tell caller that the destination file was unlinked. */
822 *new_dst = true;
826 if (*new_dst)
828 int open_flags = O_WRONLY | O_CREAT | O_BINARY;
829 dest_desc = open (dst_name, open_flags | O_EXCL,
830 dst_mode & ~omitted_permissions);
831 dest_errno = errno;
833 /* When trying to copy through a dangling destination symlink,
834 the above open fails with EEXIST. If that happens, and
835 lstat'ing the DST_NAME shows that it is a symlink, then we
836 have a problem: trying to resolve this dangling symlink to
837 a directory/destination-entry pair is fundamentally racy,
838 so punt. If x->open_dangling_dest_symlink is set (cp sets
839 that when POSIXLY_CORRECT is set in the environment), simply
840 call open again, but without O_EXCL (potentially dangerous).
841 If not, fail with a diagnostic. These shenanigans are necessary
842 only when copying, i.e., not in move_mode. */
843 if (dest_desc < 0 && dest_errno == EEXIST && ! x->move_mode)
845 struct stat dangling_link_sb;
846 if (lstat (dst_name, &dangling_link_sb) == 0
847 && S_ISLNK (dangling_link_sb.st_mode))
849 if (x->open_dangling_dest_symlink)
851 dest_desc = open (dst_name, open_flags,
852 dst_mode & ~omitted_permissions);
853 dest_errno = errno;
855 else
857 error (0, 0, _("not writing through dangling symlink %s"),
858 quote (dst_name));
859 return_val = false;
860 goto close_src_desc;
865 /* Improve quality of diagnostic when a nonexistent dst_name
866 ends in a slash and open fails with errno == EISDIR. */
867 if (dest_desc < 0 && dest_errno == EISDIR
868 && *dst_name && dst_name[strlen (dst_name) - 1] == '/')
869 dest_errno = ENOTDIR;
871 else
872 omitted_permissions = 0;
874 if (dest_desc < 0)
876 error (0, dest_errno, _("cannot create regular file %s"),
877 quote (dst_name));
878 return_val = false;
879 goto close_src_desc;
882 if (fstat (dest_desc, &sb) != 0)
884 error (0, errno, _("cannot fstat %s"), quote (dst_name));
885 return_val = false;
886 goto close_src_and_dst_desc;
889 /* --attributes-only overrides --reflink. */
890 if (data_copy_required && x->reflink_mode)
892 bool clone_ok = clone_file (dest_desc, source_desc) == 0;
893 if (clone_ok || x->reflink_mode == REFLINK_ALWAYS)
895 if (!clone_ok)
897 error (0, errno, _("failed to clone %s"), quote (dst_name));
898 return_val = false;
899 goto close_src_and_dst_desc;
901 data_copy_required = false;
905 if (data_copy_required)
907 typedef uintptr_t word;
909 /* Choose a suitable buffer size; it may be adjusted later. */
910 size_t buf_alignment = lcm (getpagesize (), sizeof (word));
911 size_t buf_alignment_slop = sizeof (word) + buf_alignment - 1;
912 size_t buf_size = io_blksize (sb);
914 /* Deal with sparse files. */
915 bool make_holes = false;
917 if (S_ISREG (sb.st_mode))
919 /* Even with --sparse=always, try to create holes only
920 if the destination is a regular file. */
921 if (x->sparse_mode == SPARSE_ALWAYS)
922 make_holes = true;
924 #if HAVE_STRUCT_STAT_ST_BLOCKS
925 /* Use a heuristic to determine whether SRC_NAME contains any sparse
926 blocks. If the file has fewer blocks than would normally be
927 needed for a file of its size, then at least one of the blocks in
928 the file is a hole. */
929 if (x->sparse_mode == SPARSE_AUTO && S_ISREG (src_open_sb.st_mode)
930 && ST_NBLOCKS (src_open_sb) < src_open_sb.st_size / ST_NBLOCKSIZE)
931 make_holes = true;
932 #endif
935 /* If not making a sparse file, try to use a more-efficient
936 buffer size. */
937 if (! make_holes)
939 /* Compute the least common multiple of the input and output
940 buffer sizes, adjusting for outlandish values. */
941 size_t blcm_max = MIN (SIZE_MAX, SSIZE_MAX) - buf_alignment_slop;
942 size_t blcm = buffer_lcm (io_blksize (src_open_sb), buf_size,
943 blcm_max);
945 /* Do not bother with a buffer larger than the input file, plus one
946 byte to make sure the file has not grown while reading it. */
947 if (S_ISREG (src_open_sb.st_mode) && src_open_sb.st_size < buf_size)
948 buf_size = src_open_sb.st_size + 1;
950 /* However, stick with a block size that is a positive multiple of
951 blcm, overriding the above adjustments. Watch out for
952 overflow. */
953 buf_size += blcm - 1;
954 buf_size -= buf_size % blcm;
955 if (buf_size == 0 || blcm_max < buf_size)
956 buf_size = blcm;
959 /* Make a buffer with space for a sentinel at the end. */
960 buf_alloc = xmalloc (buf_size + buf_alignment_slop);
961 buf = ptr_align (buf_alloc, buf_alignment);
963 bool normal_copy_required;
964 /* Perform an efficient extent-based copy, falling back to the
965 standard copy only if the initial extent scan fails. If the
966 '--sparse=never' option is specified, write all data but use
967 any extents to read more efficiently. */
968 if (extent_copy (source_desc, dest_desc, buf, buf_size,
969 src_open_sb.st_size,
970 S_ISREG (sb.st_mode) ? x->sparse_mode : SPARSE_NEVER,
971 src_name, dst_name, &normal_copy_required))
972 goto preserve_metadata;
974 if (! normal_copy_required)
976 return_val = false;
977 goto close_src_and_dst_desc;
980 off_t n_read;
981 bool wrote_hole_at_eof;
982 if ( ! sparse_copy (source_desc, dest_desc, buf, buf_size,
983 make_holes, src_name, dst_name,
984 UINTMAX_MAX, &n_read,
985 &wrote_hole_at_eof)
986 || (wrote_hole_at_eof &&
987 ftruncate (dest_desc, n_read) < 0))
989 error (0, errno, _("failed to extend %s"), quote (dst_name));
990 return_val = false;
991 goto close_src_and_dst_desc;
995 preserve_metadata:
996 if (x->preserve_timestamps)
998 struct timespec timespec[2];
999 timespec[0] = get_stat_atime (src_sb);
1000 timespec[1] = get_stat_mtime (src_sb);
1002 if (fdutimens (dest_desc, dst_name, timespec) != 0)
1004 error (0, errno, _("preserving times for %s"), quote (dst_name));
1005 if (x->require_preserve)
1007 return_val = false;
1008 goto close_src_and_dst_desc;
1013 /* Set ownership before xattrs as changing owners will
1014 clear capabilities. */
1015 if (x->preserve_ownership && ! SAME_OWNER_AND_GROUP (*src_sb, sb))
1017 switch (set_owner (x, dst_name, dest_desc, src_sb, *new_dst, &sb))
1019 case -1:
1020 return_val = false;
1021 goto close_src_and_dst_desc;
1023 case 0:
1024 src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX);
1025 break;
1029 /* To allow copying xattrs on read-only files, temporarily chmod u+rw.
1030 This workaround is required as an inode permission check is done
1031 by xattr_permission() in fs/xattr.c of the GNU/Linux kernel tree. */
1032 if (x->preserve_xattr)
1034 bool access_changed = false;
1036 if (!(sb.st_mode & S_IWUSR) && geteuid () != 0)
1037 access_changed = fchmod_or_lchmod (dest_desc, dst_name, 0600) == 0;
1039 if (!copy_attr (src_name, source_desc, dst_name, dest_desc, x)
1040 && x->require_preserve_xattr)
1041 return_val = false;
1043 if (access_changed)
1044 fchmod_or_lchmod (dest_desc, dst_name, dst_mode & ~omitted_permissions);
1047 set_author (dst_name, dest_desc, src_sb);
1049 if (x->preserve_mode || x->move_mode)
1051 if (copy_acl (src_name, source_desc, dst_name, dest_desc, src_mode) != 0
1052 && x->require_preserve)
1053 return_val = false;
1055 else if (x->set_mode)
1057 if (set_acl (dst_name, dest_desc, x->mode) != 0)
1058 return_val = false;
1060 else if (omitted_permissions)
1062 omitted_permissions &= ~ cached_umask ();
1063 if (omitted_permissions
1064 && fchmod_or_lchmod (dest_desc, dst_name, dst_mode) != 0)
1066 error (0, errno, _("preserving permissions for %s"),
1067 quote (dst_name));
1068 if (x->require_preserve)
1069 return_val = false;
1073 close_src_and_dst_desc:
1074 if (close (dest_desc) < 0)
1076 error (0, errno, _("closing %s"), quote (dst_name));
1077 return_val = false;
1079 close_src_desc:
1080 if (close (source_desc) < 0)
1082 error (0, errno, _("closing %s"), quote (src_name));
1083 return_val = false;
1086 free (buf_alloc);
1087 free (name_alloc);
1088 return return_val;
1091 /* Return true if it's ok that the source and destination
1092 files are the `same' by some measure. The goal is to avoid
1093 making the `copy' operation remove both copies of the file
1094 in that case, while still allowing the user to e.g., move or
1095 copy a regular file onto a symlink that points to it.
1096 Try to minimize the cost of this function in the common case.
1097 Set *RETURN_NOW if we've determined that the caller has no more
1098 work to do and should return successfully, right away.
1100 Set *UNLINK_SRC if we've determined that the caller wants to do
1101 `rename (a, b)' where `a' and `b' are distinct hard links to the same
1102 file. In that case, the caller should try to unlink `a' and then return
1103 successfully. Ideally, we wouldn't have to do that, and we'd be
1104 able to rely on rename to remove the source file. However, POSIX
1105 mistakenly requires that such a rename call do *nothing* and return
1106 successfully. */
1108 static bool
1109 same_file_ok (char const *src_name, struct stat const *src_sb,
1110 char const *dst_name, struct stat const *dst_sb,
1111 const struct cp_options *x, bool *return_now, bool *unlink_src)
1113 const struct stat *src_sb_link;
1114 const struct stat *dst_sb_link;
1115 struct stat tmp_dst_sb;
1116 struct stat tmp_src_sb;
1118 bool same_link;
1119 bool same = SAME_INODE (*src_sb, *dst_sb);
1121 *return_now = false;
1122 *unlink_src = false;
1124 /* FIXME: this should (at the very least) be moved into the following
1125 if-block. More likely, it should be removed, because it inhibits
1126 making backups. But removing it will result in a change in behavior
1127 that will probably have to be documented -- and tests will have to
1128 be updated. */
1129 if (same && x->hard_link)
1131 *return_now = true;
1132 return true;
1135 if (x->dereference == DEREF_NEVER)
1137 same_link = same;
1139 /* If both the source and destination files are symlinks (and we'll
1140 know this here IFF preserving symlinks), then it's ok -- as long
1141 as they are distinct. */
1142 if (S_ISLNK (src_sb->st_mode) && S_ISLNK (dst_sb->st_mode))
1143 return ! same_name (src_name, dst_name);
1145 src_sb_link = src_sb;
1146 dst_sb_link = dst_sb;
1148 else
1150 if (!same)
1151 return true;
1153 if (lstat (dst_name, &tmp_dst_sb) != 0
1154 || lstat (src_name, &tmp_src_sb) != 0)
1155 return true;
1157 src_sb_link = &tmp_src_sb;
1158 dst_sb_link = &tmp_dst_sb;
1160 same_link = SAME_INODE (*src_sb_link, *dst_sb_link);
1162 /* If both are symlinks, then it's ok, but only if the destination
1163 will be unlinked before being opened. This is like the test
1164 above, but with the addition of the unlink_dest_before_opening
1165 conjunct because otherwise, with two symlinks to the same target,
1166 we'd end up truncating the source file. */
1167 if (S_ISLNK (src_sb_link->st_mode) && S_ISLNK (dst_sb_link->st_mode)
1168 && x->unlink_dest_before_opening)
1169 return true;
1172 /* The backup code ensures there's a copy, so it's usually ok to
1173 remove any destination file. One exception is when both
1174 source and destination are the same directory entry. In that
1175 case, moving the destination file aside (in making the backup)
1176 would also rename the source file and result in an error. */
1177 if (x->backup_type != no_backups)
1179 if (!same_link)
1181 /* In copy mode when dereferencing symlinks, if the source is a
1182 symlink and the dest is not, then backing up the destination
1183 (moving it aside) would make it a dangling symlink, and the
1184 subsequent attempt to open it in copy_reg would fail with
1185 a misleading diagnostic. Avoid that by returning zero in
1186 that case so the caller can make cp (or mv when it has to
1187 resort to reading the source file) fail now. */
1189 /* FIXME-note: even with the following kludge, we can still provoke
1190 the offending diagnostic. It's just a little harder to do :-)
1191 $ rm -f a b c; touch c; ln -s c b; ln -s b a; cp -b a b
1192 cp: cannot open `a' for reading: No such file or directory
1193 That's misleading, since a subsequent `ls' shows that `a'
1194 is still there.
1195 One solution would be to open the source file *before* moving
1196 aside the destination, but that'd involve a big rewrite. */
1197 if ( ! x->move_mode
1198 && x->dereference != DEREF_NEVER
1199 && S_ISLNK (src_sb_link->st_mode)
1200 && ! S_ISLNK (dst_sb_link->st_mode))
1201 return false;
1203 return true;
1206 return ! same_name (src_name, dst_name);
1209 #if 0
1210 /* FIXME: use or remove */
1212 /* If we're making a backup, we'll detect the problem case in
1213 copy_reg because SRC_NAME will no longer exist. Allowing
1214 the test to be deferred lets cp do some useful things.
1215 But when creating hardlinks and SRC_NAME is a symlink
1216 but DST_NAME is not we must test anyway. */
1217 if (x->hard_link
1218 || !S_ISLNK (src_sb_link->st_mode)
1219 || S_ISLNK (dst_sb_link->st_mode))
1220 return true;
1222 if (x->dereference != DEREF_NEVER)
1223 return true;
1224 #endif
1226 /* They may refer to the same file if we're in move mode and the
1227 target is a symlink. That is ok, since we remove any existing
1228 destination file before opening it -- via `rename' if they're on
1229 the same file system, via `unlink (DST_NAME)' otherwise.
1230 It's also ok if they're distinct hard links to the same file. */
1231 if (x->move_mode || x->unlink_dest_before_opening)
1233 if (S_ISLNK (dst_sb_link->st_mode))
1234 return true;
1236 if (same_link
1237 && 1 < dst_sb_link->st_nlink
1238 && ! same_name (src_name, dst_name))
1240 if (x->move_mode)
1242 *unlink_src = true;
1243 *return_now = true;
1245 return true;
1249 /* If neither is a symlink, then it's ok as long as they aren't
1250 hard links to the same file. */
1251 if (!S_ISLNK (src_sb_link->st_mode) && !S_ISLNK (dst_sb_link->st_mode))
1253 if (!SAME_INODE (*src_sb_link, *dst_sb_link))
1254 return true;
1256 /* If they are the same file, it's ok if we're making hard links. */
1257 if (x->hard_link)
1259 *return_now = true;
1260 return true;
1264 /* It's ok to remove a destination symlink. But that works only when we
1265 unlink before opening the destination and when the source and destination
1266 files are on the same partition. */
1267 if (x->unlink_dest_before_opening
1268 && S_ISLNK (dst_sb_link->st_mode))
1269 return dst_sb_link->st_dev == src_sb_link->st_dev;
1271 if (x->dereference == DEREF_NEVER)
1273 if ( ! S_ISLNK (src_sb_link->st_mode))
1274 tmp_src_sb = *src_sb_link;
1275 else if (stat (src_name, &tmp_src_sb) != 0)
1276 return true;
1278 if ( ! S_ISLNK (dst_sb_link->st_mode))
1279 tmp_dst_sb = *dst_sb_link;
1280 else if (stat (dst_name, &tmp_dst_sb) != 0)
1281 return true;
1283 if ( ! SAME_INODE (tmp_src_sb, tmp_dst_sb))
1284 return true;
1286 /* FIXME: shouldn't this be testing whether we're making symlinks? */
1287 if (x->hard_link)
1289 *return_now = true;
1290 return true;
1294 return false;
1297 /* Return true if FILE, with mode MODE, is writable in the sense of 'mv'.
1298 Always consider a symbolic link to be writable. */
1299 static bool
1300 writable_destination (char const *file, mode_t mode)
1302 return (S_ISLNK (mode)
1303 || can_write_any_file ()
1304 || euidaccess (file, W_OK) == 0);
1307 static void
1308 overwrite_prompt (char const *dst_name, struct stat const *dst_sb)
1310 if (! writable_destination (dst_name, dst_sb->st_mode))
1312 char perms[12]; /* "-rwxrwxrwx " ls-style modes. */
1313 strmode (dst_sb->st_mode, perms);
1314 perms[10] = '\0';
1315 fprintf (stderr,
1316 _("%s: try to overwrite %s, overriding mode %04lo (%s)? "),
1317 program_name, quote (dst_name),
1318 (unsigned long int) (dst_sb->st_mode & CHMOD_MODE_BITS),
1319 &perms[1]);
1321 else
1323 fprintf (stderr, _("%s: overwrite %s? "),
1324 program_name, quote (dst_name));
1328 /* Initialize the hash table implementing a set of F_triple entries
1329 corresponding to destination files. */
1330 extern void
1331 dest_info_init (struct cp_options *x)
1333 x->dest_info
1334 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
1335 NULL,
1336 triple_hash,
1337 triple_compare,
1338 triple_free);
1341 /* Initialize the hash table implementing a set of F_triple entries
1342 corresponding to source files listed on the command line. */
1343 extern void
1344 src_info_init (struct cp_options *x)
1347 /* Note that we use triple_hash_no_name here.
1348 Contrast with the use of triple_hash above.
1349 That is necessary because a source file may be specified
1350 in many different ways. We want to warn about this
1351 cp a a d/
1352 as well as this:
1353 cp a ./a d/
1355 x->src_info
1356 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
1357 NULL,
1358 triple_hash_no_name,
1359 triple_compare,
1360 triple_free);
1363 /* When effecting a move (e.g., for mv(1)), and given the name DST_NAME
1364 of the destination and a corresponding stat buffer, DST_SB, return
1365 true if the logical `move' operation should _not_ proceed.
1366 Otherwise, return false.
1367 Depending on options specified in X, this code may issue an
1368 interactive prompt asking whether it's ok to overwrite DST_NAME. */
1369 static bool
1370 abandon_move (const struct cp_options *x,
1371 char const *dst_name,
1372 struct stat const *dst_sb)
1374 assert (x->move_mode);
1375 return (x->interactive == I_ALWAYS_NO
1376 || ((x->interactive == I_ASK_USER
1377 || (x->interactive == I_UNSPECIFIED
1378 && x->stdin_tty
1379 && ! writable_destination (dst_name, dst_sb->st_mode)))
1380 && (overwrite_prompt (dst_name, dst_sb), 1)
1381 && ! yesno ()));
1384 /* Print --verbose output on standard output, e.g. `new' -> `old'.
1385 If BACKUP_DST_NAME is non-NULL, then also indicate that it is
1386 the name of a backup file. */
1387 static void
1388 emit_verbose (char const *src, char const *dst, char const *backup_dst_name)
1390 printf ("%s -> %s", quote_n (0, src), quote_n (1, dst));
1391 if (backup_dst_name)
1392 printf (_(" (backup: %s)"), quote (backup_dst_name));
1393 putchar ('\n');
1396 /* A wrapper around "setfscreatecon (NULL)" that exits upon failure. */
1397 static void
1398 restore_default_fscreatecon_or_die (void)
1400 if (setfscreatecon (NULL) != 0)
1401 error (EXIT_FAILURE, errno,
1402 _("failed to restore the default file creation context"));
1405 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
1406 any type. NEW_DST should be true if the file DST_NAME cannot
1407 exist because its parent directory was just created; NEW_DST should
1408 be false if DST_NAME might already exist. DEVICE is the device
1409 number of the parent directory, or 0 if the parent of this file is
1410 not known. ANCESTORS points to a linked, null terminated list of
1411 devices and inodes of parent directories of SRC_NAME. COMMAND_LINE_ARG
1412 is true iff SRC_NAME was specified on the command line.
1413 FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG is both input and output.
1414 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
1415 same as) DST_NAME; otherwise, clear it.
1416 Return true if successful. */
1417 static bool
1418 copy_internal (char const *src_name, char const *dst_name,
1419 bool new_dst,
1420 dev_t device,
1421 struct dir_list *ancestors,
1422 const struct cp_options *x,
1423 bool command_line_arg,
1424 bool *first_dir_created_per_command_line_arg,
1425 bool *copy_into_self,
1426 bool *rename_succeeded)
1428 struct stat src_sb;
1429 struct stat dst_sb;
1430 mode_t src_mode;
1431 mode_t dst_mode IF_LINT ( = 0);
1432 mode_t dst_mode_bits;
1433 mode_t omitted_permissions;
1434 bool restore_dst_mode = false;
1435 char *earlier_file = NULL;
1436 char *dst_backup = NULL;
1437 bool backup_succeeded = false;
1438 bool delayed_ok;
1439 bool copied_as_regular = false;
1440 bool dest_is_symlink = false;
1441 bool have_dst_lstat = false;
1443 if (x->move_mode && rename_succeeded)
1444 *rename_succeeded = false;
1446 *copy_into_self = false;
1448 if (XSTAT (x, src_name, &src_sb) != 0)
1450 error (0, errno, _("cannot stat %s"), quote (src_name));
1451 return false;
1454 src_mode = src_sb.st_mode;
1456 if (S_ISDIR (src_mode) && !x->recursive)
1458 error (0, 0, _("omitting directory %s"), quote (src_name));
1459 return false;
1462 /* Detect the case in which the same source file appears more than
1463 once on the command line and no backup option has been selected.
1464 If so, simply warn and don't copy it the second time.
1465 This check is enabled only if x->src_info is non-NULL. */
1466 if (command_line_arg)
1468 if ( ! S_ISDIR (src_sb.st_mode)
1469 && x->backup_type == no_backups
1470 && seen_file (x->src_info, src_name, &src_sb))
1472 error (0, 0, _("warning: source file %s specified more than once"),
1473 quote (src_name));
1474 return true;
1477 record_file (x->src_info, src_name, &src_sb);
1480 if (!new_dst)
1482 /* Regular files can be created by writing through symbolic
1483 links, but other files cannot. So use stat on the
1484 destination when copying a regular file, and lstat otherwise.
1485 However, if we intend to unlink or remove the destination
1486 first, use lstat, since a copy won't actually be made to the
1487 destination in that case. */
1488 bool use_stat =
1489 ((S_ISREG (src_mode)
1490 || (x->copy_as_regular
1491 && ! (S_ISDIR (src_mode) || S_ISLNK (src_mode))))
1492 && ! (x->move_mode || x->symbolic_link || x->hard_link
1493 || x->backup_type != no_backups
1494 || x->unlink_dest_before_opening));
1495 if ((use_stat
1496 ? stat (dst_name, &dst_sb)
1497 : lstat (dst_name, &dst_sb))
1498 != 0)
1500 if (errno != ENOENT)
1502 error (0, errno, _("cannot stat %s"), quote (dst_name));
1503 return false;
1505 else
1507 new_dst = true;
1510 else
1511 { /* Here, we know that dst_name exists, at least to the point
1512 that it is stat'able or lstat'able. */
1513 bool return_now;
1514 bool unlink_src;
1516 have_dst_lstat = !use_stat;
1517 if (! same_file_ok (src_name, &src_sb, dst_name, &dst_sb,
1518 x, &return_now, &unlink_src))
1520 error (0, 0, _("%s and %s are the same file"),
1521 quote_n (0, src_name), quote_n (1, dst_name));
1522 return false;
1525 if (!S_ISDIR (src_mode) && x->update)
1527 /* When preserving time stamps (but not moving within a file
1528 system), don't worry if the destination time stamp is
1529 less than the source merely because of time stamp
1530 truncation. */
1531 int options = ((x->preserve_timestamps
1532 && ! (x->move_mode
1533 && dst_sb.st_dev == src_sb.st_dev))
1534 ? UTIMECMP_TRUNCATE_SOURCE
1535 : 0);
1537 if (0 <= utimecmp (dst_name, &dst_sb, &src_sb, options))
1539 /* We're using --update and the destination is not older
1540 than the source, so do not copy or move. Pretend the
1541 rename succeeded, so the caller (if it's mv) doesn't
1542 end up removing the source file. */
1543 if (rename_succeeded)
1544 *rename_succeeded = true;
1545 return true;
1549 /* When there is an existing destination file, we may end up
1550 returning early, and hence not copying/moving the file.
1551 This may be due to an interactive `negative' reply to the
1552 prompt about the existing file. It may also be due to the
1553 use of the --reply=no option.
1555 cp and mv treat -i and -f differently. */
1556 if (x->move_mode)
1558 if (abandon_move (x, dst_name, &dst_sb)
1559 || (unlink_src && unlink (src_name) == 0))
1561 /* Pretend the rename succeeded, so the caller (mv)
1562 doesn't end up removing the source file. */
1563 if (rename_succeeded)
1564 *rename_succeeded = true;
1565 if (unlink_src && x->verbose)
1566 printf (_("removed %s\n"), quote (src_name));
1567 return true;
1569 if (unlink_src)
1571 error (0, errno, _("cannot remove %s"), quote (src_name));
1572 return false;
1575 else
1577 if (! S_ISDIR (src_mode)
1578 && (x->interactive == I_ALWAYS_NO
1579 || (x->interactive == I_ASK_USER
1580 && (overwrite_prompt (dst_name, &dst_sb), 1)
1581 && ! yesno ())))
1582 return true;
1585 if (return_now)
1586 return true;
1588 if (!S_ISDIR (dst_sb.st_mode))
1590 if (S_ISDIR (src_mode))
1592 if (x->move_mode && x->backup_type != no_backups)
1594 /* Moving a directory onto an existing
1595 non-directory is ok only with --backup. */
1597 else
1599 error (0, 0,
1600 _("cannot overwrite non-directory %s with directory %s"),
1601 quote_n (0, dst_name), quote_n (1, src_name));
1602 return false;
1606 /* Don't let the user destroy their data, even if they try hard:
1607 This mv command must fail (likewise for cp):
1608 rm -rf a b c; mkdir a b c; touch a/f b/f; mv a/f b/f c
1609 Otherwise, the contents of b/f would be lost.
1610 In the case of `cp', b/f would be lost if the user simulated
1611 a move using cp and rm.
1612 Note that it works fine if you use --backup=numbered. */
1613 if (command_line_arg
1614 && x->backup_type != numbered_backups
1615 && seen_file (x->dest_info, dst_name, &dst_sb))
1617 error (0, 0,
1618 _("will not overwrite just-created %s with %s"),
1619 quote_n (0, dst_name), quote_n (1, src_name));
1620 return false;
1624 if (!S_ISDIR (src_mode))
1626 if (S_ISDIR (dst_sb.st_mode))
1628 if (x->move_mode && x->backup_type != no_backups)
1630 /* Moving a non-directory onto an existing
1631 directory is ok only with --backup. */
1633 else
1635 error (0, 0,
1636 _("cannot overwrite directory %s with non-directory"),
1637 quote (dst_name));
1638 return false;
1643 if (x->move_mode)
1645 /* Don't allow user to move a directory onto a non-directory. */
1646 if (S_ISDIR (src_sb.st_mode) && !S_ISDIR (dst_sb.st_mode)
1647 && x->backup_type == no_backups)
1649 error (0, 0,
1650 _("cannot move directory onto non-directory: %s -> %s"),
1651 quote_n (0, src_name), quote_n (0, dst_name));
1652 return false;
1656 if (x->backup_type != no_backups
1657 /* Don't try to back up a destination if the last
1658 component of src_name is "." or "..". */
1659 && ! dot_or_dotdot (last_component (src_name))
1660 /* Create a backup of each destination directory in move mode,
1661 but not in copy mode. FIXME: it might make sense to add an
1662 option to suppress backup creation also for move mode.
1663 That would let one use mv to merge new content into an
1664 existing hierarchy. */
1665 && (x->move_mode || ! S_ISDIR (dst_sb.st_mode)))
1667 char *tmp_backup = find_backup_file_name (dst_name,
1668 x->backup_type);
1670 /* Detect (and fail) when creating the backup file would
1671 destroy the source file. Before, running the commands
1672 cd /tmp; rm -f a a~; : > a; echo A > a~; cp --b=simple a~ a
1673 would leave two zero-length files: a and a~. */
1674 /* FIXME: but simply change e.g., the final a~ to `./a~'
1675 and the source will still be destroyed. */
1676 if (STREQ (tmp_backup, src_name))
1678 const char *fmt;
1679 fmt = (x->move_mode
1680 ? _("backing up %s would destroy source; %s not moved")
1681 : _("backing up %s would destroy source; %s not copied"));
1682 error (0, 0, fmt,
1683 quote_n (0, dst_name),
1684 quote_n (1, src_name));
1685 free (tmp_backup);
1686 return false;
1689 /* FIXME: use fts:
1690 Using alloca for a file name that may be arbitrarily
1691 long is not recommended. In fact, even forming such a name
1692 should be discouraged. Eventually, this code will be rewritten
1693 to use fts, so using alloca here will be less of a problem. */
1694 ASSIGN_STRDUPA (dst_backup, tmp_backup);
1695 free (tmp_backup);
1696 if (rename (dst_name, dst_backup) != 0)
1698 if (errno != ENOENT)
1700 error (0, errno, _("cannot backup %s"), quote (dst_name));
1701 return false;
1703 else
1705 dst_backup = NULL;
1708 else
1710 backup_succeeded = true;
1712 new_dst = true;
1714 else if (! S_ISDIR (dst_sb.st_mode)
1715 /* Never unlink dst_name when in move mode. */
1716 && ! x->move_mode
1717 && (x->unlink_dest_before_opening
1718 || (x->preserve_links && 1 < dst_sb.st_nlink)
1719 || (x->dereference == DEREF_NEVER
1720 && ! S_ISREG (src_sb.st_mode))
1723 if (unlink (dst_name) != 0 && errno != ENOENT)
1725 error (0, errno, _("cannot remove %s"), quote (dst_name));
1726 return false;
1728 new_dst = true;
1729 if (x->verbose)
1730 printf (_("removed %s\n"), quote (dst_name));
1735 /* Ensure we don't try to copy through a symlink that was
1736 created by a prior call to this function. */
1737 if (command_line_arg
1738 && x->dest_info
1739 && ! x->move_mode
1740 && x->backup_type == no_backups)
1742 bool lstat_ok = true;
1743 struct stat tmp_buf;
1744 struct stat *dst_lstat_sb;
1746 /* If we called lstat above, good: use that data.
1747 Otherwise, call lstat here, in case dst_name is a symlink. */
1748 if (have_dst_lstat)
1749 dst_lstat_sb = &dst_sb;
1750 else
1752 if (lstat (dst_name, &tmp_buf) == 0)
1753 dst_lstat_sb = &tmp_buf;
1754 else
1755 lstat_ok = false;
1758 /* Never copy through a symlink we've just created. */
1759 if (lstat_ok
1760 && S_ISLNK (dst_lstat_sb->st_mode)
1761 && seen_file (x->dest_info, dst_name, dst_lstat_sb))
1763 error (0, 0,
1764 _("will not copy %s through just-created symlink %s"),
1765 quote_n (0, src_name), quote_n (1, dst_name));
1766 return false;
1770 /* If the source is a directory, we don't always create the destination
1771 directory. So --verbose should not announce anything until we're
1772 sure we'll create a directory. */
1773 if (x->verbose && !S_ISDIR (src_mode))
1774 emit_verbose (src_name, dst_name, backup_succeeded ? dst_backup : NULL);
1776 /* Associate the destination file name with the source device and inode
1777 so that if we encounter a matching dev/ino pair in the source tree
1778 we can arrange to create a hard link between the corresponding names
1779 in the destination tree.
1781 When using the --link (-l) option, there is no need to take special
1782 measures, because (barring race conditions) files that are hard-linked
1783 in the source tree will also be hard-linked in the destination tree.
1785 Sometimes, when preserving links, we have to record dev/ino even
1786 though st_nlink == 1:
1787 - when in move_mode, since we may be moving a group of N hard-linked
1788 files (via two or more command line arguments) to a different
1789 partition; the links may be distributed among the command line
1790 arguments (possibly hierarchies) so that the link count of
1791 the final, once-linked source file is reduced to 1 when it is
1792 considered below. But in this case (for mv) we don't need to
1793 incur the expense of recording the dev/ino => name mapping; all we
1794 really need is a lookup, to see if the dev/ino pair has already
1795 been copied.
1796 - when using -H and processing a command line argument;
1797 that command line argument could be a symlink pointing to another
1798 command line argument. With `cp -H --preserve=link', we hard-link
1799 those two destination files.
1800 - likewise for -L except that it applies to all files, not just
1801 command line arguments.
1803 Also, with --recursive, record dev/ino of each command-line directory.
1804 We'll use that info to detect this problem: cp -R dir dir. */
1806 if (x->move_mode && src_sb.st_nlink == 1)
1808 earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev);
1810 else if (x->preserve_links
1811 && !x->hard_link
1812 && (1 < src_sb.st_nlink
1813 || (command_line_arg
1814 && x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
1815 || x->dereference == DEREF_ALWAYS))
1817 earlier_file = remember_copied (dst_name, src_sb.st_ino, src_sb.st_dev);
1819 else if (x->recursive && S_ISDIR (src_mode))
1821 if (command_line_arg)
1822 earlier_file = remember_copied (dst_name, src_sb.st_ino, src_sb.st_dev);
1823 else
1824 earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev);
1827 /* Did we copy this inode somewhere else (in this command line argument)
1828 and therefore this is a second hard link to the inode? */
1830 if (earlier_file)
1832 /* Avoid damaging the destination file system by refusing to preserve
1833 hard-linked directories (which are found at least in Netapp snapshot
1834 directories). */
1835 if (S_ISDIR (src_mode))
1837 /* If src_name and earlier_file refer to the same directory entry,
1838 then warn about copying a directory into itself. */
1839 if (same_name (src_name, earlier_file))
1841 error (0, 0, _("cannot copy a directory, %s, into itself, %s"),
1842 quote_n (0, top_level_src_name),
1843 quote_n (1, top_level_dst_name));
1844 *copy_into_self = true;
1845 goto un_backup;
1847 else if (x->dereference == DEREF_ALWAYS)
1849 /* This happens when e.g., encountering a directory for the
1850 second or subsequent time via symlinks when cp is invoked
1851 with -R and -L. E.g.,
1852 rm -rf a b c d; mkdir a b c d; ln -s ../c a; ln -s ../c b;
1853 cp -RL a b d
1856 else
1858 error (0, 0, _("will not create hard link %s to directory %s"),
1859 quote_n (0, dst_name), quote_n (1, earlier_file));
1860 goto un_backup;
1863 else
1865 /* We want to guarantee that symlinks are not followed. */
1866 bool link_failed = (linkat (AT_FDCWD, earlier_file, AT_FDCWD,
1867 dst_name, 0) != 0);
1869 /* If the link failed because of an existing destination,
1870 remove that file and then call link again. */
1871 if (link_failed && errno == EEXIST)
1873 if (unlink (dst_name) != 0)
1875 error (0, errno, _("cannot remove %s"), quote (dst_name));
1876 goto un_backup;
1878 if (x->verbose)
1879 printf (_("removed %s\n"), quote (dst_name));
1880 link_failed = (linkat (AT_FDCWD, earlier_file, AT_FDCWD,
1881 dst_name, 0) != 0);
1884 if (link_failed)
1886 error (0, errno, _("cannot create hard link %s to %s"),
1887 quote_n (0, dst_name), quote_n (1, earlier_file));
1888 goto un_backup;
1891 return true;
1895 if (x->move_mode)
1897 if (rename (src_name, dst_name) == 0)
1899 if (x->verbose && S_ISDIR (src_mode))
1900 emit_verbose (src_name, dst_name,
1901 backup_succeeded ? dst_backup : NULL);
1903 if (rename_succeeded)
1904 *rename_succeeded = true;
1906 if (command_line_arg)
1908 /* Record destination dev/ino/name, so that if we are asked
1909 to overwrite that file again, we can detect it and fail. */
1910 /* It's fine to use the _source_ stat buffer (src_sb) to get the
1911 _destination_ dev/ino, since the rename above can't have
1912 changed those, and `mv' always uses lstat.
1913 We could limit it further by operating
1914 only on non-directories. */
1915 record_file (x->dest_info, dst_name, &src_sb);
1918 return true;
1921 /* FIXME: someday, consider what to do when moving a directory into
1922 itself but when source and destination are on different devices. */
1924 /* This happens when attempting to rename a directory to a
1925 subdirectory of itself. */
1926 if (errno == EINVAL)
1928 /* FIXME: this is a little fragile in that it relies on rename(2)
1929 failing with a specific errno value. Expect problems on
1930 non-POSIX systems. */
1931 error (0, 0, _("cannot move %s to a subdirectory of itself, %s"),
1932 quote_n (0, top_level_src_name),
1933 quote_n (1, top_level_dst_name));
1935 /* Note that there is no need to call forget_created here,
1936 (compare with the other calls in this file) since the
1937 destination directory didn't exist before. */
1939 *copy_into_self = true;
1940 /* FIXME-cleanup: Don't return true here; adjust mv.c accordingly.
1941 The only caller that uses this code (mv.c) ends up setting its
1942 exit status to nonzero when copy_into_self is nonzero. */
1943 return true;
1946 /* WARNING: there probably exist systems for which an inter-device
1947 rename fails with a value of errno not handled here.
1948 If/as those are reported, add them to the condition below.
1949 If this happens to you, please do the following and send the output
1950 to the bug-reporting address (e.g., in the output of cp --help):
1951 touch k; perl -e 'rename "k","/tmp/k" or print "$!(",$!+0,")\n"'
1952 where your current directory is on one partion and /tmp is the other.
1953 Also, please try to find the E* errno macro name corresponding to
1954 the diagnostic and parenthesized integer, and include that in your
1955 e-mail. One way to do that is to run a command like this
1956 find /usr/include/. -type f \
1957 | xargs grep 'define.*\<E[A-Z]*\>.*\<18\>' /dev/null
1958 where you'd replace `18' with the integer in parentheses that
1959 was output from the perl one-liner above.
1960 If necessary, of course, change `/tmp' to some other directory. */
1961 if (errno != EXDEV)
1963 /* There are many ways this can happen due to a race condition.
1964 When something happens between the initial XSTAT and the
1965 subsequent rename, we can get many different types of errors.
1966 For example, if the destination is initially a non-directory
1967 or non-existent, but it is created as a directory, the rename
1968 fails. If two `mv' commands try to rename the same file at
1969 about the same time, one will succeed and the other will fail.
1970 If the permissions on the directory containing the source or
1971 destination file are made too restrictive, the rename will
1972 fail. Etc. */
1973 error (0, errno,
1974 _("cannot move %s to %s"),
1975 quote_n (0, src_name), quote_n (1, dst_name));
1976 forget_created (src_sb.st_ino, src_sb.st_dev);
1977 return false;
1980 /* The rename attempt has failed. Remove any existing destination
1981 file so that a cross-device `mv' acts as if it were really using
1982 the rename syscall. */
1983 if (unlink (dst_name) != 0 && errno != ENOENT)
1985 error (0, errno,
1986 _("inter-device move failed: %s to %s; unable to remove target"),
1987 quote_n (0, src_name), quote_n (1, dst_name));
1988 forget_created (src_sb.st_ino, src_sb.st_dev);
1989 return false;
1992 new_dst = true;
1995 /* If the ownership might change, or if it is a directory (whose
1996 special mode bits may change after the directory is created),
1997 omit some permissions at first, so unauthorized users cannot nip
1998 in before the file is ready. */
1999 dst_mode_bits = (x->set_mode ? x->mode : src_mode) & CHMOD_MODE_BITS;
2000 omitted_permissions =
2001 (dst_mode_bits
2002 & (x->preserve_ownership ? S_IRWXG | S_IRWXO
2003 : S_ISDIR (src_mode) ? S_IWGRP | S_IWOTH
2004 : 0));
2006 delayed_ok = true;
2008 if (x->preserve_security_context)
2010 bool all_errors = !x->data_copy_required || x->require_preserve_context;
2011 bool some_errors = !all_errors && !x->reduce_diagnostics;
2012 security_context_t con;
2014 if (0 <= lgetfilecon (src_name, &con))
2016 if (setfscreatecon (con) < 0)
2018 if (all_errors || (some_errors && !errno_unsupported (errno)))
2019 error (0, errno,
2020 _("failed to set default file creation context to %s"),
2021 quote (con));
2022 if (x->require_preserve_context)
2024 freecon (con);
2025 return false;
2028 freecon (con);
2030 else
2032 if (all_errors || (some_errors && !errno_unsupported (errno)))
2034 error (0, errno,
2035 _("failed to get security context of %s"),
2036 quote (src_name));
2038 if (x->require_preserve_context)
2039 return false;
2043 if (S_ISDIR (src_mode))
2045 struct dir_list *dir;
2047 /* If this directory has been copied before during the
2048 recursion, there is a symbolic link to an ancestor
2049 directory of the symbolic link. It is impossible to
2050 continue to copy this, unless we've got an infinite disk. */
2052 if (is_ancestor (&src_sb, ancestors))
2054 error (0, 0, _("cannot copy cyclic symbolic link %s"),
2055 quote (src_name));
2056 goto un_backup;
2059 /* Insert the current directory in the list of parents. */
2061 dir = alloca (sizeof *dir);
2062 dir->parent = ancestors;
2063 dir->ino = src_sb.st_ino;
2064 dir->dev = src_sb.st_dev;
2066 if (new_dst || !S_ISDIR (dst_sb.st_mode))
2068 /* POSIX says mkdir's behavior is implementation-defined when
2069 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
2070 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
2071 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
2072 if (mkdir (dst_name, dst_mode_bits & ~omitted_permissions) != 0)
2074 error (0, errno, _("cannot create directory %s"),
2075 quote (dst_name));
2076 goto un_backup;
2079 /* We need search and write permissions to the new directory
2080 for writing the directory's contents. Check if these
2081 permissions are there. */
2083 if (lstat (dst_name, &dst_sb) != 0)
2085 error (0, errno, _("cannot stat %s"), quote (dst_name));
2086 goto un_backup;
2088 else if ((dst_sb.st_mode & S_IRWXU) != S_IRWXU)
2090 /* Make the new directory searchable and writable. */
2092 dst_mode = dst_sb.st_mode;
2093 restore_dst_mode = true;
2095 if (lchmod (dst_name, dst_mode | S_IRWXU) != 0)
2097 error (0, errno, _("setting permissions for %s"),
2098 quote (dst_name));
2099 goto un_backup;
2103 /* Record the created directory's inode and device numbers into
2104 the search structure, so that we can avoid copying it again.
2105 Do this only for the first directory that is created for each
2106 source command line argument. */
2107 if (!*first_dir_created_per_command_line_arg)
2109 remember_copied (dst_name, dst_sb.st_ino, dst_sb.st_dev);
2110 *first_dir_created_per_command_line_arg = true;
2113 if (x->verbose)
2114 emit_verbose (src_name, dst_name, NULL);
2117 /* Decide whether to copy the contents of the directory. */
2118 if (x->one_file_system && device != 0 && device != src_sb.st_dev)
2120 /* Here, we are crossing a file system boundary and cp's -x option
2121 is in effect: so don't copy the contents of this directory. */
2123 else
2125 /* Copy the contents of the directory. Don't just return if
2126 this fails -- otherwise, the failure to read a single file
2127 in a source directory would cause the containing destination
2128 directory not to have owner/perms set properly. */
2129 delayed_ok = copy_dir (src_name, dst_name, new_dst, &src_sb, dir, x,
2130 first_dir_created_per_command_line_arg,
2131 copy_into_self);
2134 else if (x->symbolic_link)
2136 dest_is_symlink = true;
2137 if (*src_name != '/')
2139 /* Check that DST_NAME denotes a file in the current directory. */
2140 struct stat dot_sb;
2141 struct stat dst_parent_sb;
2142 char *dst_parent;
2143 bool in_current_dir;
2145 dst_parent = dir_name (dst_name);
2147 in_current_dir = (STREQ (".", dst_parent)
2148 /* If either stat call fails, it's ok not to report
2149 the failure and say dst_name is in the current
2150 directory. Other things will fail later. */
2151 || stat (".", &dot_sb) != 0
2152 || stat (dst_parent, &dst_parent_sb) != 0
2153 || SAME_INODE (dot_sb, dst_parent_sb));
2154 free (dst_parent);
2156 if (! in_current_dir)
2158 error (0, 0,
2159 _("%s: can make relative symbolic links only in current directory"),
2160 quote (dst_name));
2161 goto un_backup;
2164 if (symlink (src_name, dst_name) != 0)
2166 error (0, errno, _("cannot create symbolic link %s to %s"),
2167 quote_n (0, dst_name), quote_n (1, src_name));
2168 goto un_backup;
2172 /* cp, invoked with `--link --no-dereference', should not follow the
2173 link; we guarantee this with gnulib's linkat module (on systems
2174 where link(2) follows the link, gnulib creates a symlink with
2175 identical contents, which is good enough for our purposes). */
2176 else if (x->hard_link
2177 && (!S_ISLNK (src_mode)
2178 || x->dereference != DEREF_NEVER))
2180 if (linkat (AT_FDCWD, src_name, AT_FDCWD, dst_name, 0))
2182 error (0, errno, _("cannot create link %s"), quote (dst_name));
2183 goto un_backup;
2186 else if (S_ISREG (src_mode)
2187 || (x->copy_as_regular && !S_ISLNK (src_mode)))
2189 copied_as_regular = true;
2190 /* POSIX says the permission bits of the source file must be
2191 used as the 3rd argument in the open call. Historical
2192 practice passed all the source mode bits to 'open', but the extra
2193 bits were ignored, so it should be the same either way. */
2194 if (! copy_reg (src_name, dst_name, x, src_mode & S_IRWXUGO,
2195 omitted_permissions, &new_dst, &src_sb))
2196 goto un_backup;
2198 else if (S_ISFIFO (src_mode))
2200 /* Use mknod, rather than mkfifo, because the former preserves
2201 the special mode bits of a fifo on Solaris 10, while mkfifo
2202 does not. But fall back on mkfifo, because on some BSD systems,
2203 mknod always fails when asked to create a FIFO. */
2204 if (mknod (dst_name, src_mode & ~omitted_permissions, 0) != 0)
2205 if (mkfifo (dst_name, src_mode & ~S_IFIFO & ~omitted_permissions) != 0)
2207 error (0, errno, _("cannot create fifo %s"), quote (dst_name));
2208 goto un_backup;
2211 else if (S_ISBLK (src_mode) || S_ISCHR (src_mode) || S_ISSOCK (src_mode))
2213 if (mknod (dst_name, src_mode & ~omitted_permissions, src_sb.st_rdev)
2214 != 0)
2216 error (0, errno, _("cannot create special file %s"),
2217 quote (dst_name));
2218 goto un_backup;
2221 else if (S_ISLNK (src_mode))
2223 char *src_link_val = areadlink_with_size (src_name, src_sb.st_size);
2224 dest_is_symlink = true;
2225 if (src_link_val == NULL)
2227 error (0, errno, _("cannot read symbolic link %s"), quote (src_name));
2228 goto un_backup;
2231 if (symlink (src_link_val, dst_name) == 0)
2232 free (src_link_val);
2233 else
2235 int saved_errno = errno;
2236 bool same_link = false;
2237 if (x->update && !new_dst && S_ISLNK (dst_sb.st_mode)
2238 && dst_sb.st_size == strlen (src_link_val))
2240 /* See if the destination is already the desired symlink.
2241 FIXME: This behavior isn't documented, and seems wrong
2242 in some cases, e.g., if the destination symlink has the
2243 wrong ownership, permissions, or time stamps. */
2244 char *dest_link_val =
2245 areadlink_with_size (dst_name, dst_sb.st_size);
2246 if (dest_link_val && STREQ (dest_link_val, src_link_val))
2247 same_link = true;
2248 free (dest_link_val);
2250 free (src_link_val);
2252 if (! same_link)
2254 error (0, saved_errno, _("cannot create symbolic link %s"),
2255 quote (dst_name));
2256 goto un_backup;
2260 if (x->preserve_security_context)
2261 restore_default_fscreatecon_or_die ();
2263 if (x->preserve_ownership)
2265 /* Preserve the owner and group of the just-`copied'
2266 symbolic link, if possible. */
2267 if (HAVE_LCHOWN
2268 && lchown (dst_name, src_sb.st_uid, src_sb.st_gid) != 0
2269 && ! chown_failure_ok (x))
2271 error (0, errno, _("failed to preserve ownership for %s"),
2272 dst_name);
2273 goto un_backup;
2275 else
2277 /* Can't preserve ownership of symlinks.
2278 FIXME: maybe give a warning or even error for symlinks
2279 in directories with the sticky bit set -- there, not
2280 preserving owner/group is a potential security problem. */
2284 else
2286 error (0, 0, _("%s has unknown file type"), quote (src_name));
2287 goto un_backup;
2290 if (command_line_arg && x->dest_info)
2292 /* Now that the destination file is very likely to exist,
2293 add its info to the set. */
2294 struct stat sb;
2295 if (lstat (dst_name, &sb) == 0)
2296 record_file (x->dest_info, dst_name, &sb);
2299 /* If we've just created a hard-link due to cp's --link option,
2300 we're done. */
2301 if (x->hard_link && ! S_ISDIR (src_mode))
2302 return delayed_ok;
2304 if (copied_as_regular)
2305 return delayed_ok;
2307 /* POSIX says that `cp -p' must restore the following:
2308 - permission bits
2309 - setuid, setgid bits
2310 - owner and group
2311 If it fails to restore any of those, we may give a warning but
2312 the destination must not be removed.
2313 FIXME: implement the above. */
2315 /* Adjust the times (and if possible, ownership) for the copy.
2316 chown turns off set[ug]id bits for non-root,
2317 so do the chmod last. */
2319 if (x->preserve_timestamps)
2321 struct timespec timespec[2];
2322 timespec[0] = get_stat_atime (&src_sb);
2323 timespec[1] = get_stat_mtime (&src_sb);
2325 if ((dest_is_symlink
2326 ? utimens_symlink (dst_name, timespec)
2327 : utimens (dst_name, timespec))
2328 != 0)
2330 error (0, errno, _("preserving times for %s"), quote (dst_name));
2331 if (x->require_preserve)
2332 return false;
2336 /* The operations beyond this point may dereference a symlink. */
2337 if (dest_is_symlink)
2338 return delayed_ok;
2340 /* Avoid calling chown if we know it's not necessary. */
2341 if (x->preserve_ownership
2342 && (new_dst || !SAME_OWNER_AND_GROUP (src_sb, dst_sb)))
2344 switch (set_owner (x, dst_name, -1, &src_sb, new_dst, &dst_sb))
2346 case -1:
2347 return false;
2349 case 0:
2350 src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX);
2351 break;
2355 set_author (dst_name, -1, &src_sb);
2357 if (x->preserve_xattr && ! copy_attr (src_name, -1, dst_name, -1, x)
2358 && x->require_preserve_xattr)
2359 return false;
2361 if (x->preserve_mode || x->move_mode)
2363 if (copy_acl (src_name, -1, dst_name, -1, src_mode) != 0
2364 && x->require_preserve)
2365 return false;
2367 else if (x->set_mode)
2369 if (set_acl (dst_name, -1, x->mode) != 0)
2370 return false;
2372 else
2374 if (omitted_permissions)
2376 omitted_permissions &= ~ cached_umask ();
2378 if (omitted_permissions && !restore_dst_mode)
2380 /* Permissions were deliberately omitted when the file
2381 was created due to security concerns. See whether
2382 they need to be re-added now. It'd be faster to omit
2383 the lstat, but deducing the current destination mode
2384 is tricky in the presence of implementation-defined
2385 rules for special mode bits. */
2386 if (new_dst && lstat (dst_name, &dst_sb) != 0)
2388 error (0, errno, _("cannot stat %s"), quote (dst_name));
2389 return false;
2391 dst_mode = dst_sb.st_mode;
2392 if (omitted_permissions & ~dst_mode)
2393 restore_dst_mode = true;
2397 if (restore_dst_mode)
2399 if (lchmod (dst_name, dst_mode | omitted_permissions) != 0)
2401 error (0, errno, _("preserving permissions for %s"),
2402 quote (dst_name));
2403 if (x->require_preserve)
2404 return false;
2409 return delayed_ok;
2411 un_backup:
2413 if (x->preserve_security_context)
2414 restore_default_fscreatecon_or_die ();
2416 /* We have failed to create the destination file.
2417 If we've just added a dev/ino entry via the remember_copied
2418 call above (i.e., unless we've just failed to create a hard link),
2419 remove the entry associating the source dev/ino with the
2420 destination file name, so we don't try to `preserve' a link
2421 to a file we didn't create. */
2422 if (earlier_file == NULL)
2423 forget_created (src_sb.st_ino, src_sb.st_dev);
2425 if (dst_backup)
2427 if (rename (dst_backup, dst_name) != 0)
2428 error (0, errno, _("cannot un-backup %s"), quote (dst_name));
2429 else
2431 if (x->verbose)
2432 printf (_("%s -> %s (unbackup)\n"),
2433 quote_n (0, dst_backup), quote_n (1, dst_name));
2436 return false;
2439 static bool
2440 valid_options (const struct cp_options *co)
2442 assert (co != NULL);
2443 assert (VALID_BACKUP_TYPE (co->backup_type));
2444 assert (VALID_SPARSE_MODE (co->sparse_mode));
2445 assert (VALID_REFLINK_MODE (co->reflink_mode));
2446 assert (!(co->hard_link && co->symbolic_link));
2447 assert (!
2448 (co->reflink_mode == REFLINK_ALWAYS
2449 && co->sparse_mode != SPARSE_AUTO));
2450 return true;
2453 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
2454 any type. NONEXISTENT_DST should be true if the file DST_NAME
2455 is known not to exist (e.g., because its parent directory was just
2456 created); NONEXISTENT_DST should be false if DST_NAME might already
2457 exist. OPTIONS is ... FIXME-describe
2458 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
2459 same as) DST_NAME; otherwise, set clear it.
2460 Return true if successful. */
2462 extern bool
2463 copy (char const *src_name, char const *dst_name,
2464 bool nonexistent_dst, const struct cp_options *options,
2465 bool *copy_into_self, bool *rename_succeeded)
2467 assert (valid_options (options));
2469 /* Record the file names: they're used in case of error, when copying
2470 a directory into itself. I don't like to make these tools do *any*
2471 extra work in the common case when that work is solely to handle
2472 exceptional cases, but in this case, I don't see a way to derive the
2473 top level source and destination directory names where they're used.
2474 An alternative is to use COPY_INTO_SELF and print the diagnostic
2475 from every caller -- but I don't want to do that. */
2476 top_level_src_name = src_name;
2477 top_level_dst_name = dst_name;
2479 bool first_dir_created_per_command_line_arg = false;
2480 return copy_internal (src_name, dst_name, nonexistent_dst, 0, NULL,
2481 options, true,
2482 &first_dir_created_per_command_line_arg,
2483 copy_into_self, rename_succeeded);
2486 /* Set *X to the default options for a value of type struct cp_options. */
2488 extern void
2489 cp_options_default (struct cp_options *x)
2491 memset (x, 0, sizeof *x);
2492 #ifdef PRIV_FILE_CHOWN
2494 priv_set_t *pset = priv_allocset ();
2495 if (!pset)
2496 xalloc_die ();
2497 if (getppriv (PRIV_EFFECTIVE, pset) == 0)
2499 x->chown_privileges = priv_ismember (pset, PRIV_FILE_CHOWN);
2500 x->owner_privileges = priv_ismember (pset, PRIV_FILE_OWNER);
2502 priv_freeset (pset);
2504 #else
2505 x->chown_privileges = x->owner_privileges = (geteuid () == 0);
2506 #endif
2509 /* Return true if it's OK for chown to fail, where errno is
2510 the error number that chown failed with and X is the copying
2511 option set. */
2513 extern bool
2514 chown_failure_ok (struct cp_options const *x)
2516 /* If non-root uses -p, it's ok if we can't preserve ownership.
2517 But root probably wants to know, e.g. if NFS disallows it,
2518 or if the target system doesn't support file ownership. */
2520 return ((errno == EPERM || errno == EINVAL) && !x->chown_privileges);
2523 /* Similarly, return true if it's OK for chmod and similar operations
2524 to fail, where errno is the error number that chmod failed with and
2525 X is the copying option set. */
2527 static bool
2528 owner_failure_ok (struct cp_options const *x)
2530 return ((errno == EPERM || errno == EINVAL) && !x->owner_privileges);
2533 /* Return the user's umask, caching the result. */
2535 extern mode_t
2536 cached_umask (void)
2538 static mode_t mask = (mode_t) -1;
2539 if (mask == (mode_t) -1)
2541 mask = umask (0);
2542 umask (mask);
2544 return mask;