cp/mv: add xattr support
[coreutils.git] / src / copy.c
blob85d1fea13e0d67858c6a7d4c6f9609bf3f4f5e64
1 /* copy.c -- core functions for copying files and directories
2 Copyright (C) 89, 90, 91, 1995-2009 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 /* Extracted from cp.c and librarified by Jim Meyering. */
19 #include <config.h>
20 #include <stdio.h>
21 #include <assert.h>
22 #include <sys/types.h>
23 #include <selinux/selinux.h>
25 #if HAVE_HURD_H
26 # include <hurd.h>
27 #endif
28 #if HAVE_PRIV_H
29 # include <priv.h>
30 #endif
32 #include "system.h"
33 #include "acl.h"
34 #include "backupfile.h"
35 #include "buffer-lcm.h"
36 #include "copy.h"
37 #include "cp-hash.h"
38 #include "error.h"
39 #include "fcntl--.h"
40 #include "file-set.h"
41 #include "filemode.h"
42 #include "filenamecat.h"
43 #include "full-write.h"
44 #include "hash.h"
45 #include "hash-triple.h"
46 #include "ignore-value.h"
47 #include "quote.h"
48 #include "same.h"
49 #include "savedir.h"
50 #include "stat-time.h"
51 #include "utimecmp.h"
52 #include "utimens.h"
53 #include "write-any-file.h"
54 #include "areadlink.h"
55 #include "yesno.h"
57 #if USE_XATTR
58 # include <attr/error_context.h>
59 # include <attr/libattr.h>
60 # include <stdarg.h>
61 # include "verror.h"
62 #endif
64 #ifndef HAVE_FCHOWN
65 # define HAVE_FCHOWN false
66 # define fchown(fd, uid, gid) (-1)
67 #endif
69 #ifndef HAVE_LCHOWN
70 # define HAVE_LCHOWN false
71 # define lchown(name, uid, gid) chown (name, uid, gid)
72 #endif
74 #ifndef HAVE_MKFIFO
75 static int
76 rpl_mkfifo (char const *file, mode_t mode)
78 errno = ENOTSUP;
79 return -1;
81 # define mkfifo rpl_mkfifo
82 #endif
84 #ifndef USE_ACL
85 # define USE_ACL 0
86 #endif
88 #define SAME_OWNER(A, B) ((A).st_uid == (B).st_uid)
89 #define SAME_GROUP(A, B) ((A).st_gid == (B).st_gid)
90 #define SAME_OWNER_AND_GROUP(A, B) (SAME_OWNER (A, B) && SAME_GROUP (A, B))
92 struct dir_list
94 struct dir_list *parent;
95 ino_t ino;
96 dev_t dev;
99 /* Initial size of the cp.dest_info hash table. */
100 #define DEST_INFO_INITIAL_CAPACITY 61
102 static bool copy_internal (char const *src_name, char const *dst_name,
103 bool new_dst, dev_t device,
104 struct dir_list *ancestors,
105 const struct cp_options *x,
106 bool command_line_arg,
107 bool *copy_into_self,
108 bool *rename_succeeded);
109 static bool owner_failure_ok (struct cp_options const *x);
111 /* Pointers to the file names: they're used in the diagnostic that is issued
112 when we detect the user is trying to copy a directory into itself. */
113 static char const *top_level_src_name;
114 static char const *top_level_dst_name;
116 /* FIXME: describe */
117 /* FIXME: rewrite this to use a hash table so we avoid the quadratic
118 performance hit that's probably noticeable only on trees deeper
119 than a few hundred levels. See use of active_dir_map in remove.c */
121 static bool
122 is_ancestor (const struct stat *sb, const struct dir_list *ancestors)
124 while (ancestors != 0)
126 if (ancestors->ino == sb->st_ino && ancestors->dev == sb->st_dev)
127 return true;
128 ancestors = ancestors->parent;
130 return false;
133 #if USE_XATTR
134 static void
135 copy_attr_error (struct error_context *ctx ATTRIBUTE_UNUSED,
136 char const *fmt, ...)
138 int err = errno;
139 va_list ap;
141 /* use verror module to print error message */
142 va_start (ap, fmt);
143 verror (0, err, fmt, ap);
144 va_end (ap);
147 static char const *
148 copy_attr_quote (struct error_context *ctx ATTRIBUTE_UNUSED, char const *str)
150 return quote (str);
153 static void
154 copy_attr_free (struct error_context *ctx ATTRIBUTE_UNUSED,
155 char const *str ATTRIBUTE_UNUSED)
159 static bool
160 copy_attr_by_fd (char const *src_path, int src_fd,
161 char const *dst_path, int dst_fd)
163 struct error_context ctx =
165 .error = copy_attr_error,
166 .quote = copy_attr_quote,
167 .quote_free = copy_attr_free
169 return 0 == attr_copy_fd (src_path, src_fd, dst_path, dst_fd, 0, &ctx);
172 static bool
173 copy_attr_by_name (char const *src_path, char const *dst_path)
175 struct error_context ctx =
177 .error = copy_attr_error,
178 .quote = copy_attr_quote,
179 .quote_free = copy_attr_free
181 return 0 == attr_copy_file (src_path, dst_path, 0, &ctx);
183 #else /* USE_XATTR */
185 static bool
186 copy_attr_by_fd (char const *src_path, int src_fd,
187 char const *dst_path, int dst_fd)
189 return true;
192 static bool
193 copy_attr_by_name (char const *src_path, char const *dst_path)
195 return true;
197 #endif /* USE_XATTR */
199 /* Read the contents of the directory SRC_NAME_IN, and recursively
200 copy the contents to DST_NAME_IN. NEW_DST is true if
201 DST_NAME_IN is a directory that was created previously in the
202 recursion. SRC_SB and ANCESTORS describe SRC_NAME_IN.
203 Set *COPY_INTO_SELF if SRC_NAME_IN is a parent of
204 (or the same as) DST_NAME_IN; otherwise, clear it.
205 Return true if successful. */
207 static bool
208 copy_dir (char const *src_name_in, char const *dst_name_in, bool new_dst,
209 const struct stat *src_sb, struct dir_list *ancestors,
210 const struct cp_options *x, bool *copy_into_self)
212 char *name_space;
213 char *namep;
214 struct cp_options non_command_line_options = *x;
215 bool ok = true;
217 name_space = savedir (src_name_in);
218 if (name_space == NULL)
220 /* This diagnostic is a bit vague because savedir can fail in
221 several different ways. */
222 error (0, errno, _("cannot access %s"), quote (src_name_in));
223 return false;
226 /* For cp's -H option, dereference command line arguments, but do not
227 dereference symlinks that are found via recursive traversal. */
228 if (x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
229 non_command_line_options.dereference = DEREF_NEVER;
231 namep = name_space;
232 while (*namep != '\0')
234 bool local_copy_into_self;
235 char *src_name = file_name_concat (src_name_in, namep, NULL);
236 char *dst_name = file_name_concat (dst_name_in, namep, NULL);
238 ok &= copy_internal (src_name, dst_name, new_dst, src_sb->st_dev,
239 ancestors, &non_command_line_options, false,
240 &local_copy_into_self, NULL);
241 *copy_into_self |= local_copy_into_self;
243 free (dst_name);
244 free (src_name);
246 namep += strlen (namep) + 1;
248 free (name_space);
249 return ok;
252 /* Set the owner and owning group of DEST_DESC to the st_uid and
253 st_gid fields of SRC_SB. If DEST_DESC is undefined (-1), set
254 the owner and owning group of DST_NAME instead; for
255 safety prefer lchown if the system supports it since no
256 symbolic links should be involved. DEST_DESC must
257 refer to the same file as DEST_NAME if defined.
258 Upon failure to set both UID and GID, try to set only the GID.
259 NEW_DST is true if the file was newly created; otherwise,
260 DST_SB is the status of the destination.
261 Return 1 if the initial syscall succeeds, 0 if it fails but it's OK
262 not to preserve ownership, -1 otherwise. */
264 static int
265 set_owner (const struct cp_options *x, char const *dst_name, int dest_desc,
266 struct stat const *src_sb, bool new_dst,
267 struct stat const *dst_sb)
269 uid_t uid = src_sb->st_uid;
270 gid_t gid = src_sb->st_gid;
272 /* Naively changing the ownership of an already-existing file before
273 changing its permissions would create a window of vulnerability if
274 the file's old permissions are too generous for the new owner and
275 group. Avoid the window by first changing to a restrictive
276 temporary mode if necessary. */
278 if (!new_dst & (x->preserve_mode | x->move_mode | x->set_mode))
280 mode_t old_mode = dst_sb->st_mode;
281 mode_t new_mode =
282 (x->preserve_mode | x->move_mode ? src_sb->st_mode : x->mode);
283 mode_t restrictive_temp_mode = old_mode & new_mode & S_IRWXU;
285 if ((USE_ACL
286 || (old_mode & CHMOD_MODE_BITS
287 & (~new_mode | S_ISUID | S_ISGID | S_ISVTX)))
288 && qset_acl (dst_name, dest_desc, restrictive_temp_mode) != 0)
290 if (! owner_failure_ok (x))
291 error (0, errno, _("clearing permissions for %s"), quote (dst_name));
292 return -x->require_preserve;
296 if (HAVE_FCHOWN && dest_desc != -1)
298 if (fchown (dest_desc, uid, gid) == 0)
299 return 1;
300 if (errno == EPERM || errno == EINVAL)
302 /* We've failed to set *both*. Now, try to set just the group
303 ID, but ignore any failure here, and don't change errno. */
304 int saved_errno = errno;
305 ignore_value (fchown (dest_desc, -1, gid));
306 errno = saved_errno;
309 else
311 if (lchown (dst_name, uid, gid) == 0)
312 return 1;
313 if (errno == EPERM || errno == EINVAL)
315 /* We've failed to set *both*. Now, try to set just the group
316 ID, but ignore any failure here, and don't change errno. */
317 int saved_errno = errno;
318 ignore_value (lchown (dst_name, -1, gid));
319 errno = saved_errno;
323 if (! chown_failure_ok (x))
325 error (0, errno, _("failed to preserve ownership for %s"),
326 quote (dst_name));
327 if (x->require_preserve)
328 return -1;
331 return 0;
334 /* Set the st_author field of DEST_DESC to the st_author field of
335 SRC_SB. If DEST_DESC is undefined (-1), set the st_author field
336 of DST_NAME instead. DEST_DESC must refer to the same file as
337 DEST_NAME if defined. */
339 static void
340 set_author (const char *dst_name, int dest_desc, const struct stat *src_sb)
342 #if HAVE_STRUCT_STAT_ST_AUTHOR
343 /* FIXME: Modify the following code so that it does not
344 follow symbolic links. */
346 /* Preserve the st_author field. */
347 file_t file = (dest_desc < 0
348 ? file_name_lookup (dst_name, 0, 0)
349 : getdport (dest_desc));
350 if (file == MACH_PORT_NULL)
351 error (0, errno, _("failed to lookup file %s"), quote (dst_name));
352 else
354 error_t err = file_chauthor (file, src_sb->st_author);
355 if (err)
356 error (0, err, _("failed to preserve authorship for %s"),
357 quote (dst_name));
358 mach_port_deallocate (mach_task_self (), file);
360 #else
361 (void) dst_name;
362 (void) dest_desc;
363 (void) src_sb;
364 #endif
367 /* Change the file mode bits of the file identified by DESC or NAME to MODE.
368 Use DESC if DESC is valid and fchmod is available, NAME otherwise. */
370 static int
371 fchmod_or_lchmod (int desc, char const *name, mode_t mode)
373 #if HAVE_FCHMOD
374 if (0 <= desc)
375 return fchmod (desc, mode);
376 #endif
377 return lchmod (name, mode);
380 /* Copy a regular file from SRC_NAME to DST_NAME.
381 If the source file contains holes, copies holes and blocks of zeros
382 in the source file as holes in the destination file.
383 (Holes are read as zeroes by the `read' system call.)
384 When creating the destination, use DST_MODE & ~OMITTED_PERMISSIONS
385 as the third argument in the call to open, adding
386 OMITTED_PERMISSIONS after copying as needed.
387 X provides many option settings.
388 Return true if successful.
389 *NEW_DST is as in copy_internal.
390 SRC_SB is the result of calling XSTAT (aka stat) on SRC_NAME. */
392 static bool
393 copy_reg (char const *src_name, char const *dst_name,
394 const struct cp_options *x,
395 mode_t dst_mode, mode_t omitted_permissions, bool *new_dst,
396 struct stat const *src_sb)
398 char *buf;
399 char *buf_alloc = NULL;
400 char *name_alloc = NULL;
401 int dest_desc;
402 int dest_errno;
403 int source_desc;
404 mode_t src_mode = src_sb->st_mode;
405 struct stat sb;
406 struct stat src_open_sb;
407 bool return_val = true;
409 source_desc = open (src_name,
410 (O_RDONLY | O_BINARY
411 | (x->dereference == DEREF_NEVER ? O_NOFOLLOW : 0)));
412 if (source_desc < 0)
414 error (0, errno, _("cannot open %s for reading"), quote (src_name));
415 return false;
418 if (fstat (source_desc, &src_open_sb) != 0)
420 error (0, errno, _("cannot fstat %s"), quote (src_name));
421 return_val = false;
422 goto close_src_desc;
425 /* Compare the source dev/ino from the open file to the incoming,
426 saved ones obtained via a previous call to stat. */
427 if (! SAME_INODE (*src_sb, src_open_sb))
429 error (0, 0,
430 _("skipping file %s, as it was replaced while being copied"),
431 quote (src_name));
432 return_val = false;
433 goto close_src_desc;
436 /* The semantics of the following open calls are mandated
437 by the specs for both cp and mv. */
438 if (! *new_dst)
440 dest_desc = open (dst_name, O_WRONLY | O_TRUNC | O_BINARY);
441 dest_errno = errno;
443 /* When using cp --preserve=context to copy to an existing destination,
444 use the default context rather than that of the source. Why?
445 1) the src context may prohibit writing, and
446 2) because it's more consistent to use the same context
447 that is used when the destination file doesn't already exist. */
448 if (x->preserve_security_context && 0 <= dest_desc)
450 security_context_t con = NULL;
451 if (getfscreatecon (&con) < 0)
453 error (0, errno, _("failed to get file system create context"));
454 if (x->require_preserve_context)
456 return_val = false;
457 goto close_src_and_dst_desc;
461 if (con)
463 if (fsetfilecon (dest_desc, con) < 0)
465 error (0, errno,
466 _("failed to set the security context of %s to %s"),
467 quote_n (0, dst_name), quote_n (1, con));
468 if (x->require_preserve_context)
470 return_val = false;
471 freecon (con);
472 goto close_src_and_dst_desc;
475 freecon(con);
479 if (dest_desc < 0 && x->unlink_dest_after_failed_open)
481 if (unlink (dst_name) != 0)
483 error (0, errno, _("cannot remove %s"), quote (dst_name));
484 return_val = false;
485 goto close_src_desc;
487 if (x->verbose)
488 printf (_("removed %s\n"), quote (dst_name));
490 /* Tell caller that the destination file was unlinked. */
491 *new_dst = true;
495 if (*new_dst)
497 int open_flags = O_WRONLY | O_CREAT | O_BINARY;
498 dest_desc = open (dst_name, open_flags | O_EXCL ,
499 dst_mode & ~omitted_permissions);
500 dest_errno = errno;
502 /* When trying to copy through a dangling destination symlink,
503 the above open fails with EEXIST. If that happens, and
504 lstat'ing the DST_NAME shows that it is a symlink, then we
505 have a problem: trying to resolve this dangling symlink to
506 a directory/destination-entry pair is fundamentally racy,
507 so punt. If POSIXLY_CORRECT is set, simply call open again,
508 but without O_EXCL (potentially dangerous). If not, fail
509 with a diagnostic. These shenanigans are necessary only
510 when copying, i.e., not in move_mode. */
511 if (dest_desc < 0 && dest_errno == EEXIST && ! x->move_mode)
513 struct stat dangling_link_sb;
514 if (lstat (dst_name, &dangling_link_sb) == 0
515 && S_ISLNK (dangling_link_sb.st_mode))
517 if (x->open_dangling_dest_symlink)
519 dest_desc = open (dst_name, open_flags,
520 dst_mode & ~omitted_permissions);
521 dest_errno = errno;
523 else
525 error (0, 0, _("not writing through dangling symlink %s"),
526 quote (dst_name));
527 return_val = false;
528 goto close_src_desc;
533 else
534 omitted_permissions = 0;
536 if (dest_desc < 0)
538 error (0, dest_errno, _("cannot create regular file %s"),
539 quote (dst_name));
540 return_val = false;
541 goto close_src_desc;
544 if (fstat (dest_desc, &sb) != 0)
546 error (0, errno, _("cannot fstat %s"), quote (dst_name));
547 return_val = false;
548 goto close_src_and_dst_desc;
552 typedef uintptr_t word;
553 off_t n_read_total = 0;
555 /* Choose a suitable buffer size; it may be adjusted later. */
556 size_t buf_alignment = lcm (getpagesize (), sizeof (word));
557 size_t buf_alignment_slop = sizeof (word) + buf_alignment - 1;
558 size_t buf_size = ST_BLKSIZE (sb);
560 /* Deal with sparse files. */
561 bool last_write_made_hole = false;
562 bool make_holes = false;
564 if (S_ISREG (sb.st_mode))
566 /* Even with --sparse=always, try to create holes only
567 if the destination is a regular file. */
568 if (x->sparse_mode == SPARSE_ALWAYS)
569 make_holes = true;
571 #if HAVE_STRUCT_STAT_ST_BLOCKS
572 /* Use a heuristic to determine whether SRC_NAME contains any sparse
573 blocks. If the file has fewer blocks than would normally be
574 needed for a file of its size, then at least one of the blocks in
575 the file is a hole. */
576 if (x->sparse_mode == SPARSE_AUTO && S_ISREG (src_open_sb.st_mode)
577 && ST_NBLOCKS (src_open_sb) < src_open_sb.st_size / ST_NBLOCKSIZE)
578 make_holes = true;
579 #endif
582 /* If not making a sparse file, try to use a more-efficient
583 buffer size. */
584 if (! make_holes)
586 /* These days there's no point ever messing with buffers smaller
587 than 8 KiB. It would be nice to configure SMALL_BUF_SIZE
588 dynamically for this host and pair of files, but there doesn't
589 seem to be a good way to get readahead info portably. */
590 enum { SMALL_BUF_SIZE = 8 * 1024 };
592 /* Compute the least common multiple of the input and output
593 buffer sizes, adjusting for outlandish values. */
594 size_t blcm_max = MIN (SIZE_MAX, SSIZE_MAX) - buf_alignment_slop;
595 size_t blcm = buffer_lcm (ST_BLKSIZE (src_open_sb), buf_size,
596 blcm_max);
598 /* Do not use a block size that is too small. */
599 buf_size = MAX (SMALL_BUF_SIZE, blcm);
601 /* Do not bother with a buffer larger than the input file, plus one
602 byte to make sure the file has not grown while reading it. */
603 if (S_ISREG (src_open_sb.st_mode) && src_open_sb.st_size < buf_size)
604 buf_size = src_open_sb.st_size + 1;
606 /* However, stick with a block size that is a positive multiple of
607 blcm, overriding the above adjustments. Watch out for
608 overflow. */
609 buf_size += blcm - 1;
610 buf_size -= buf_size % blcm;
611 if (buf_size == 0 || blcm_max < buf_size)
612 buf_size = blcm;
615 /* Make a buffer with space for a sentinel at the end. */
616 buf_alloc = xmalloc (buf_size + buf_alignment_slop);
617 buf = ptr_align (buf_alloc, buf_alignment);
619 for (;;)
621 word *wp = NULL;
623 ssize_t n_read = read (source_desc, buf, buf_size);
624 if (n_read < 0)
626 #ifdef EINTR
627 if (errno == EINTR)
628 continue;
629 #endif
630 error (0, errno, _("reading %s"), quote (src_name));
631 return_val = false;
632 goto close_src_and_dst_desc;
634 if (n_read == 0)
635 break;
637 n_read_total += n_read;
639 if (make_holes)
641 char *cp;
643 /* Sentinel to stop loop. */
644 buf[n_read] = '\1';
645 #ifdef lint
646 /* Usually, buf[n_read] is not the byte just before a "word"
647 (aka uintptr_t) boundary. In that case, the word-oriented
648 test below (*wp++ == 0) would read some uninitialized bytes
649 after the sentinel. To avoid false-positive reports about
650 this condition (e.g., from a tool like valgrind), set the
651 remaining bytes -- to any value. */
652 memset (buf + n_read + 1, 0, sizeof (word) - 1);
653 #endif
655 /* Find first nonzero *word*, or the word with the sentinel. */
657 wp = (word *) buf;
658 while (*wp++ == 0)
659 continue;
661 /* Find the first nonzero *byte*, or the sentinel. */
663 cp = (char *) (wp - 1);
664 while (*cp++ == 0)
665 continue;
667 if (cp <= buf + n_read)
668 /* Clear to indicate that a normal write is needed. */
669 wp = NULL;
670 else
672 /* We found the sentinel, so the whole input block was zero.
673 Make a hole. */
674 if (lseek (dest_desc, n_read, SEEK_CUR) < 0)
676 error (0, errno, _("cannot lseek %s"), quote (dst_name));
677 return_val = false;
678 goto close_src_and_dst_desc;
680 last_write_made_hole = true;
684 if (!wp)
686 size_t n = n_read;
687 if (full_write (dest_desc, buf, n) != n)
689 error (0, errno, _("writing %s"), quote (dst_name));
690 return_val = false;
691 goto close_src_and_dst_desc;
693 last_write_made_hole = false;
695 /* A short read on a regular file means EOF. */
696 if (n_read != buf_size && S_ISREG (src_open_sb.st_mode))
697 break;
701 /* If the file ends with a `hole', we need to do something to record
702 the length of the file. On modern systems, calling ftruncate does
703 the job. On systems without native ftruncate support, we have to
704 write a byte at the ending position. Otherwise the kernel would
705 truncate the file at the end of the last write operation. */
707 if (last_write_made_hole)
709 if (HAVE_FTRUNCATE
710 ? /* ftruncate sets the file size,
711 so there is no need for a write. */
712 ftruncate (dest_desc, n_read_total) < 0
713 : /* Seek backwards one character and write a null. */
714 (lseek (dest_desc, (off_t) -1, SEEK_CUR) < 0L
715 || full_write (dest_desc, "", 1) != 1))
717 error (0, errno, _("writing %s"), quote (dst_name));
718 return_val = false;
719 goto close_src_and_dst_desc;
724 if (x->preserve_timestamps)
726 struct timespec timespec[2];
727 timespec[0] = get_stat_atime (src_sb);
728 timespec[1] = get_stat_mtime (src_sb);
730 if (gl_futimens (dest_desc, dst_name, timespec) != 0)
732 error (0, errno, _("preserving times for %s"), quote (dst_name));
733 if (x->require_preserve)
735 return_val = false;
736 goto close_src_and_dst_desc;
741 if (x->preserve_ownership && ! SAME_OWNER_AND_GROUP (*src_sb, sb))
743 switch (set_owner (x, dst_name, dest_desc, src_sb, *new_dst, &sb))
745 case -1:
746 return_val = false;
747 goto close_src_and_dst_desc;
749 case 0:
750 src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX);
751 break;
755 set_author (dst_name, dest_desc, src_sb);
757 if (x->preserve_xattr && ! copy_attr_by_fd (src_name, source_desc,
758 dst_name, dest_desc)
759 && x->require_preserve_xattr)
760 return false;
762 if (x->preserve_mode || x->move_mode)
764 if (copy_acl (src_name, source_desc, dst_name, dest_desc, src_mode) != 0
765 && x->require_preserve)
766 return_val = false;
768 else if (x->set_mode)
770 if (set_acl (dst_name, dest_desc, x->mode) != 0)
771 return_val = false;
773 else if (omitted_permissions)
775 omitted_permissions &= ~ cached_umask ();
776 if (omitted_permissions
777 && fchmod_or_lchmod (dest_desc, dst_name, dst_mode) != 0)
779 error (0, errno, _("preserving permissions for %s"),
780 quote (dst_name));
781 if (x->require_preserve)
782 return_val = false;
786 close_src_and_dst_desc:
787 if (close (dest_desc) < 0)
789 error (0, errno, _("closing %s"), quote (dst_name));
790 return_val = false;
792 close_src_desc:
793 if (close (source_desc) < 0)
795 error (0, errno, _("closing %s"), quote (src_name));
796 return_val = false;
799 free (buf_alloc);
800 free (name_alloc);
801 return return_val;
804 /* Return true if it's ok that the source and destination
805 files are the `same' by some measure. The goal is to avoid
806 making the `copy' operation remove both copies of the file
807 in that case, while still allowing the user to e.g., move or
808 copy a regular file onto a symlink that points to it.
809 Try to minimize the cost of this function in the common case.
810 Set *RETURN_NOW if we've determined that the caller has no more
811 work to do and should return successfully, right away.
813 Set *UNLINK_SRC if we've determined that the caller wants to do
814 `rename (a, b)' where `a' and `b' are distinct hard links to the same
815 file. In that case, the caller should try to unlink `a' and then return
816 successfully. Ideally, we wouldn't have to do that, and we'd be
817 able to rely on rename to remove the source file. However, POSIX
818 mistakenly requires that such a rename call do *nothing* and return
819 successfully. */
821 static bool
822 same_file_ok (char const *src_name, struct stat const *src_sb,
823 char const *dst_name, struct stat const *dst_sb,
824 const struct cp_options *x, bool *return_now, bool *unlink_src)
826 const struct stat *src_sb_link;
827 const struct stat *dst_sb_link;
828 struct stat tmp_dst_sb;
829 struct stat tmp_src_sb;
831 bool same_link;
832 bool same = SAME_INODE (*src_sb, *dst_sb);
834 *return_now = false;
835 *unlink_src = false;
837 /* FIXME: this should (at the very least) be moved into the following
838 if-block. More likely, it should be removed, because it inhibits
839 making backups. But removing it will result in a change in behavior
840 that will probably have to be documented -- and tests will have to
841 be updated. */
842 if (same && x->hard_link)
844 *return_now = true;
845 return true;
848 if (x->dereference == DEREF_NEVER)
850 same_link = same;
852 /* If both the source and destination files are symlinks (and we'll
853 know this here IFF preserving symlinks), then it's ok -- as long
854 as they are distinct. */
855 if (S_ISLNK (src_sb->st_mode) && S_ISLNK (dst_sb->st_mode))
856 return ! same_name (src_name, dst_name);
858 src_sb_link = src_sb;
859 dst_sb_link = dst_sb;
861 else
863 if (!same)
864 return true;
866 if (lstat (dst_name, &tmp_dst_sb) != 0
867 || lstat (src_name, &tmp_src_sb) != 0)
868 return true;
870 src_sb_link = &tmp_src_sb;
871 dst_sb_link = &tmp_dst_sb;
873 same_link = SAME_INODE (*src_sb_link, *dst_sb_link);
875 /* If both are symlinks, then it's ok, but only if the destination
876 will be unlinked before being opened. This is like the test
877 above, but with the addition of the unlink_dest_before_opening
878 conjunct because otherwise, with two symlinks to the same target,
879 we'd end up truncating the source file. */
880 if (S_ISLNK (src_sb_link->st_mode) && S_ISLNK (dst_sb_link->st_mode)
881 && x->unlink_dest_before_opening)
882 return true;
885 /* The backup code ensures there's a copy, so it's usually ok to
886 remove any destination file. One exception is when both
887 source and destination are the same directory entry. In that
888 case, moving the destination file aside (in making the backup)
889 would also rename the source file and result in an error. */
890 if (x->backup_type != no_backups)
892 if (!same_link)
894 /* In copy mode when dereferencing symlinks, if the source is a
895 symlink and the dest is not, then backing up the destination
896 (moving it aside) would make it a dangling symlink, and the
897 subsequent attempt to open it in copy_reg would fail with
898 a misleading diagnostic. Avoid that by returning zero in
899 that case so the caller can make cp (or mv when it has to
900 resort to reading the source file) fail now. */
902 /* FIXME-note: even with the following kludge, we can still provoke
903 the offending diagnostic. It's just a little harder to do :-)
904 $ rm -f a b c; touch c; ln -s c b; ln -s b a; cp -b a b
905 cp: cannot open `a' for reading: No such file or directory
906 That's misleading, since a subsequent `ls' shows that `a'
907 is still there.
908 One solution would be to open the source file *before* moving
909 aside the destination, but that'd involve a big rewrite. */
910 if ( ! x->move_mode
911 && x->dereference != DEREF_NEVER
912 && S_ISLNK (src_sb_link->st_mode)
913 && ! S_ISLNK (dst_sb_link->st_mode))
914 return false;
916 return true;
919 return ! same_name (src_name, dst_name);
922 #if 0
923 /* FIXME: use or remove */
925 /* If we're making a backup, we'll detect the problem case in
926 copy_reg because SRC_NAME will no longer exist. Allowing
927 the test to be deferred lets cp do some useful things.
928 But when creating hardlinks and SRC_NAME is a symlink
929 but DST_NAME is not we must test anyway. */
930 if (x->hard_link
931 || !S_ISLNK (src_sb_link->st_mode)
932 || S_ISLNK (dst_sb_link->st_mode))
933 return true;
935 if (x->dereference != DEREF_NEVER)
936 return true;
937 #endif
939 /* They may refer to the same file if we're in move mode and the
940 target is a symlink. That is ok, since we remove any existing
941 destination file before opening it -- via `rename' if they're on
942 the same file system, via `unlink (DST_NAME)' otherwise.
943 It's also ok if they're distinct hard links to the same file. */
944 if (x->move_mode || x->unlink_dest_before_opening)
946 if (S_ISLNK (dst_sb_link->st_mode))
947 return true;
949 if (same_link
950 && 1 < dst_sb_link->st_nlink
951 && ! same_name (src_name, dst_name))
953 if (x->move_mode)
955 *unlink_src = true;
956 *return_now = true;
958 return true;
962 /* If neither is a symlink, then it's ok as long as they aren't
963 hard links to the same file. */
964 if (!S_ISLNK (src_sb_link->st_mode) && !S_ISLNK (dst_sb_link->st_mode))
966 if (!SAME_INODE (*src_sb_link, *dst_sb_link))
967 return true;
969 /* If they are the same file, it's ok if we're making hard links. */
970 if (x->hard_link)
972 *return_now = true;
973 return true;
977 /* It's ok to remove a destination symlink. But that works only when we
978 unlink before opening the destination and when the source and destination
979 files are on the same partition. */
980 if (x->unlink_dest_before_opening
981 && S_ISLNK (dst_sb_link->st_mode))
982 return dst_sb_link->st_dev == src_sb_link->st_dev;
984 if (x->dereference == DEREF_NEVER)
986 if ( ! S_ISLNK (src_sb_link->st_mode))
987 tmp_src_sb = *src_sb_link;
988 else if (stat (src_name, &tmp_src_sb) != 0)
989 return true;
991 if ( ! S_ISLNK (dst_sb_link->st_mode))
992 tmp_dst_sb = *dst_sb_link;
993 else if (stat (dst_name, &tmp_dst_sb) != 0)
994 return true;
996 if ( ! SAME_INODE (tmp_src_sb, tmp_dst_sb))
997 return true;
999 /* FIXME: shouldn't this be testing whether we're making symlinks? */
1000 if (x->hard_link)
1002 *return_now = true;
1003 return true;
1007 return false;
1010 /* Return true if FILE, with mode MODE, is writable in the sense of 'mv'.
1011 Always consider a symbolic link to be writable. */
1012 static bool
1013 writable_destination (char const *file, mode_t mode)
1015 return (S_ISLNK (mode)
1016 || can_write_any_file ()
1017 || euidaccess (file, W_OK) == 0);
1020 static void
1021 overwrite_prompt (char const *dst_name, struct stat const *dst_sb)
1023 if (! writable_destination (dst_name, dst_sb->st_mode))
1025 char perms[12]; /* "-rwxrwxrwx " ls-style modes. */
1026 strmode (dst_sb->st_mode, perms);
1027 perms[10] = '\0';
1028 fprintf (stderr,
1029 _("%s: try to overwrite %s, overriding mode %04lo (%s)? "),
1030 program_name, quote (dst_name),
1031 (unsigned long int) (dst_sb->st_mode & CHMOD_MODE_BITS),
1032 &perms[1]);
1034 else
1036 fprintf (stderr, _("%s: overwrite %s? "),
1037 program_name, quote (dst_name));
1041 /* Initialize the hash table implementing a set of F_triple entries
1042 corresponding to destination files. */
1043 extern void
1044 dest_info_init (struct cp_options *x)
1046 x->dest_info
1047 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
1048 NULL,
1049 triple_hash,
1050 triple_compare,
1051 triple_free);
1054 /* Initialize the hash table implementing a set of F_triple entries
1055 corresponding to source files listed on the command line. */
1056 extern void
1057 src_info_init (struct cp_options *x)
1060 /* Note that we use triple_hash_no_name here.
1061 Contrast with the use of triple_hash above.
1062 That is necessary because a source file may be specified
1063 in many different ways. We want to warn about this
1064 cp a a d/
1065 as well as this:
1066 cp a ./a d/
1068 x->src_info
1069 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
1070 NULL,
1071 triple_hash_no_name,
1072 triple_compare,
1073 triple_free);
1076 /* When effecting a move (e.g., for mv(1)), and given the name DST_NAME
1077 of the destination and a corresponding stat buffer, DST_SB, return
1078 true if the logical `move' operation should _not_ proceed.
1079 Otherwise, return false.
1080 Depending on options specified in X, this code may issue an
1081 interactive prompt asking whether it's ok to overwrite DST_NAME. */
1082 static bool
1083 abandon_move (const struct cp_options *x,
1084 char const *dst_name,
1085 struct stat const *dst_sb)
1087 assert (x->move_mode);
1088 return (x->interactive == I_ALWAYS_NO
1089 || ((x->interactive == I_ASK_USER
1090 || (x->interactive == I_UNSPECIFIED
1091 && x->stdin_tty
1092 && ! writable_destination (dst_name, dst_sb->st_mode)))
1093 && (overwrite_prompt (dst_name, dst_sb), 1)
1094 && ! yesno ()));
1097 /* Print --verbose output on standard output, e.g. `new' -> `old'.
1098 If BACKUP_DST_NAME is non-NULL, then also indicate that it is
1099 the name of a backup file. */
1100 static void
1101 emit_verbose (char const *src, char const *dst, char const *backup_dst_name)
1103 printf ("%s -> %s", quote_n (0, src), quote_n (1, dst));
1104 if (backup_dst_name)
1105 printf (_(" (backup: %s)"), quote (backup_dst_name));
1106 putchar ('\n');
1109 /* A wrapper around "setfscreatecon (NULL)" that exits upon failure. */
1110 static void
1111 restore_default_fscreatecon_or_die (void)
1113 if (setfscreatecon (NULL) != 0)
1114 error (EXIT_FAILURE, errno,
1115 _("failed to restore the default file creation context"));
1118 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
1119 any type. NEW_DST should be true if the file DST_NAME cannot
1120 exist because its parent directory was just created; NEW_DST should
1121 be false if DST_NAME might already exist. DEVICE is the device
1122 number of the parent directory, or 0 if the parent of this file is
1123 not known. ANCESTORS points to a linked, null terminated list of
1124 devices and inodes of parent directories of SRC_NAME. COMMAND_LINE_ARG
1125 is true iff SRC_NAME was specified on the command line.
1126 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
1127 same as) DST_NAME; otherwise, clear it.
1128 Return true if successful. */
1129 static bool
1130 copy_internal (char const *src_name, char const *dst_name,
1131 bool new_dst,
1132 dev_t device,
1133 struct dir_list *ancestors,
1134 const struct cp_options *x,
1135 bool command_line_arg,
1136 bool *copy_into_self,
1137 bool *rename_succeeded)
1139 struct stat src_sb;
1140 struct stat dst_sb;
1141 mode_t src_mode;
1142 mode_t dst_mode IF_LINT (= 0);
1143 mode_t dst_mode_bits;
1144 mode_t omitted_permissions;
1145 bool restore_dst_mode = false;
1146 char *earlier_file = NULL;
1147 char *dst_backup = NULL;
1148 bool backup_succeeded = false;
1149 bool delayed_ok;
1150 bool copied_as_regular = false;
1151 bool preserve_metadata;
1152 bool have_dst_lstat = false;
1154 if (x->move_mode && rename_succeeded)
1155 *rename_succeeded = false;
1157 *copy_into_self = false;
1159 if (XSTAT (x, src_name, &src_sb) != 0)
1161 error (0, errno, _("cannot stat %s"), quote (src_name));
1162 return false;
1165 src_mode = src_sb.st_mode;
1167 if (S_ISDIR (src_mode) && !x->recursive)
1169 error (0, 0, _("omitting directory %s"), quote (src_name));
1170 return false;
1173 /* Detect the case in which the same source file appears more than
1174 once on the command line and no backup option has been selected.
1175 If so, simply warn and don't copy it the second time.
1176 This check is enabled only if x->src_info is non-NULL. */
1177 if (command_line_arg)
1179 if ( ! S_ISDIR (src_sb.st_mode)
1180 && x->backup_type == no_backups
1181 && seen_file (x->src_info, src_name, &src_sb))
1183 error (0, 0, _("warning: source file %s specified more than once"),
1184 quote (src_name));
1185 return true;
1188 record_file (x->src_info, src_name, &src_sb);
1191 if (!new_dst)
1193 /* Regular files can be created by writing through symbolic
1194 links, but other files cannot. So use stat on the
1195 destination when copying a regular file, and lstat otherwise.
1196 However, if we intend to unlink or remove the destination
1197 first, use lstat, since a copy won't actually be made to the
1198 destination in that case. */
1199 bool use_stat =
1200 ((S_ISREG (src_mode)
1201 || (x->copy_as_regular
1202 && ! (S_ISDIR (src_mode) || S_ISLNK (src_mode))))
1203 && ! (x->move_mode || x->symbolic_link || x->hard_link
1204 || x->backup_type != no_backups
1205 || x->unlink_dest_before_opening));
1206 if ((use_stat
1207 ? stat (dst_name, &dst_sb)
1208 : lstat (dst_name, &dst_sb))
1209 != 0)
1211 if (errno != ENOENT)
1213 error (0, errno, _("cannot stat %s"), quote (dst_name));
1214 return false;
1216 else
1218 new_dst = true;
1221 else
1222 { /* Here, we know that dst_name exists, at least to the point
1223 that it is stat'able or lstat'able. */
1224 bool return_now;
1225 bool unlink_src;
1227 have_dst_lstat = !use_stat;
1228 if (! same_file_ok (src_name, &src_sb, dst_name, &dst_sb,
1229 x, &return_now, &unlink_src))
1231 error (0, 0, _("%s and %s are the same file"),
1232 quote_n (0, src_name), quote_n (1, dst_name));
1233 return false;
1236 if (!S_ISDIR (src_mode) && x->update)
1238 /* When preserving time stamps (but not moving within a file
1239 system), don't worry if the destination time stamp is
1240 less than the source merely because of time stamp
1241 truncation. */
1242 int options = ((x->preserve_timestamps
1243 && ! (x->move_mode
1244 && dst_sb.st_dev == src_sb.st_dev))
1245 ? UTIMECMP_TRUNCATE_SOURCE
1246 : 0);
1248 if (0 <= utimecmp (dst_name, &dst_sb, &src_sb, options))
1250 /* We're using --update and the destination is not older
1251 than the source, so do not copy or move. Pretend the
1252 rename succeeded, so the caller (if it's mv) doesn't
1253 end up removing the source file. */
1254 if (rename_succeeded)
1255 *rename_succeeded = true;
1256 return true;
1260 /* When there is an existing destination file, we may end up
1261 returning early, and hence not copying/moving the file.
1262 This may be due to an interactive `negative' reply to the
1263 prompt about the existing file. It may also be due to the
1264 use of the --reply=no option.
1266 cp and mv treat -i and -f differently. */
1267 if (x->move_mode)
1269 if (abandon_move (x, dst_name, &dst_sb)
1270 || (unlink_src && unlink (src_name) == 0))
1272 /* Pretend the rename succeeded, so the caller (mv)
1273 doesn't end up removing the source file. */
1274 if (rename_succeeded)
1275 *rename_succeeded = true;
1276 if (unlink_src && x->verbose)
1277 printf (_("removed %s\n"), quote (src_name));
1278 return true;
1280 if (unlink_src)
1282 error (0, errno, _("cannot remove %s"), quote (src_name));
1283 return false;
1286 else
1288 if (! S_ISDIR (src_mode)
1289 && (x->interactive == I_ALWAYS_NO
1290 || (x->interactive == I_ASK_USER
1291 && (overwrite_prompt (dst_name, &dst_sb), 1)
1292 && ! yesno ())))
1293 return true;
1296 if (return_now)
1297 return true;
1299 if (!S_ISDIR (dst_sb.st_mode))
1301 if (S_ISDIR (src_mode))
1303 if (x->move_mode && x->backup_type != no_backups)
1305 /* Moving a directory onto an existing
1306 non-directory is ok only with --backup. */
1308 else
1310 error (0, 0,
1311 _("cannot overwrite non-directory %s with directory %s"),
1312 quote_n (0, dst_name), quote_n (1, src_name));
1313 return false;
1317 /* Don't let the user destroy their data, even if they try hard:
1318 This mv command must fail (likewise for cp):
1319 rm -rf a b c; mkdir a b c; touch a/f b/f; mv a/f b/f c
1320 Otherwise, the contents of b/f would be lost.
1321 In the case of `cp', b/f would be lost if the user simulated
1322 a move using cp and rm.
1323 Note that it works fine if you use --backup=numbered. */
1324 if (command_line_arg
1325 && x->backup_type != numbered_backups
1326 && seen_file (x->dest_info, dst_name, &dst_sb))
1328 error (0, 0,
1329 _("will not overwrite just-created %s with %s"),
1330 quote_n (0, dst_name), quote_n (1, src_name));
1331 return false;
1335 if (!S_ISDIR (src_mode))
1337 if (S_ISDIR (dst_sb.st_mode))
1339 if (x->move_mode && x->backup_type != no_backups)
1341 /* Moving a non-directory onto an existing
1342 directory is ok only with --backup. */
1344 else
1346 error (0, 0,
1347 _("cannot overwrite directory %s with non-directory"),
1348 quote (dst_name));
1349 return false;
1354 if (x->move_mode)
1356 /* Don't allow user to move a directory onto a non-directory. */
1357 if (S_ISDIR (src_sb.st_mode) && !S_ISDIR (dst_sb.st_mode)
1358 && x->backup_type == no_backups)
1360 error (0, 0,
1361 _("cannot move directory onto non-directory: %s -> %s"),
1362 quote_n (0, src_name), quote_n (0, dst_name));
1363 return false;
1367 if (x->backup_type != no_backups
1368 /* Don't try to back up a destination if the last
1369 component of src_name is "." or "..". */
1370 && ! dot_or_dotdot (last_component (src_name))
1371 /* Create a backup of each destination directory in move mode,
1372 but not in copy mode. FIXME: it might make sense to add an
1373 option to suppress backup creation also for move mode.
1374 That would let one use mv to merge new content into an
1375 existing hierarchy. */
1376 && (x->move_mode || ! S_ISDIR (dst_sb.st_mode)))
1378 char *tmp_backup = find_backup_file_name (dst_name,
1379 x->backup_type);
1381 /* Detect (and fail) when creating the backup file would
1382 destroy the source file. Before, running the commands
1383 cd /tmp; rm -f a a~; : > a; echo A > a~; cp --b=simple a~ a
1384 would leave two zero-length files: a and a~. */
1385 /* FIXME: but simply change e.g., the final a~ to `./a~'
1386 and the source will still be destroyed. */
1387 if (STREQ (tmp_backup, src_name))
1389 const char *fmt;
1390 fmt = (x->move_mode
1391 ? _("backing up %s would destroy source; %s not moved")
1392 : _("backing up %s would destroy source; %s not copied"));
1393 error (0, 0, fmt,
1394 quote_n (0, dst_name),
1395 quote_n (1, src_name));
1396 free (tmp_backup);
1397 return false;
1400 /* FIXME: use fts:
1401 Using alloca for a file name that may be arbitrarily
1402 long is not recommended. In fact, even forming such a name
1403 should be discouraged. Eventually, this code will be rewritten
1404 to use fts, so using alloca here will be less of a problem. */
1405 ASSIGN_STRDUPA (dst_backup, tmp_backup);
1406 free (tmp_backup);
1407 if (rename (dst_name, dst_backup) != 0)
1409 if (errno != ENOENT)
1411 error (0, errno, _("cannot backup %s"), quote (dst_name));
1412 return false;
1414 else
1416 dst_backup = NULL;
1419 else
1421 backup_succeeded = true;
1423 new_dst = true;
1425 else if (! S_ISDIR (dst_sb.st_mode)
1426 /* Never unlink dst_name when in move mode. */
1427 && ! x->move_mode
1428 && (x->unlink_dest_before_opening
1429 || (x->preserve_links && 1 < dst_sb.st_nlink)
1430 || (x->dereference == DEREF_NEVER
1431 && ! S_ISREG (src_sb.st_mode))
1434 if (unlink (dst_name) != 0 && errno != ENOENT)
1436 error (0, errno, _("cannot remove %s"), quote (dst_name));
1437 return false;
1439 new_dst = true;
1440 if (x->verbose)
1441 printf (_("removed %s\n"), quote (dst_name));
1446 /* Ensure we don't try to copy through a symlink that was
1447 created by a prior call to this function. */
1448 if (command_line_arg
1449 && x->dest_info
1450 && ! x->move_mode
1451 && x->backup_type == no_backups)
1453 bool lstat_ok = true;
1454 struct stat tmp_buf;
1455 struct stat *dst_lstat_sb;
1457 /* If we called lstat above, good: use that data.
1458 Otherwise, call lstat here, in case dst_name is a symlink. */
1459 if (have_dst_lstat)
1460 dst_lstat_sb = &dst_sb;
1461 else
1463 if (lstat (dst_name, &tmp_buf) == 0)
1464 dst_lstat_sb = &tmp_buf;
1465 else
1466 lstat_ok = false;
1469 /* Never copy through a symlink we've just created. */
1470 if (lstat_ok
1471 && S_ISLNK (dst_lstat_sb->st_mode)
1472 && seen_file (x->dest_info, dst_name, dst_lstat_sb))
1474 error (0, 0,
1475 _("will not copy %s through just-created symlink %s"),
1476 quote_n (0, src_name), quote_n (1, dst_name));
1477 return false;
1481 /* If the source is a directory, we don't always create the destination
1482 directory. So --verbose should not announce anything until we're
1483 sure we'll create a directory. */
1484 if (x->verbose && !S_ISDIR (src_mode))
1485 emit_verbose (src_name, dst_name, backup_succeeded ? dst_backup : NULL);
1487 /* Associate the destination file name with the source device and inode
1488 so that if we encounter a matching dev/ino pair in the source tree
1489 we can arrange to create a hard link between the corresponding names
1490 in the destination tree.
1492 When using the --link (-l) option, there is no need to take special
1493 measures, because (barring race conditions) files that are hard-linked
1494 in the source tree will also be hard-linked in the destination tree.
1496 Sometimes, when preserving links, we have to record dev/ino even
1497 though st_nlink == 1:
1498 - when in move_mode, since we may be moving a group of N hard-linked
1499 files (via two or more command line arguments) to a different
1500 partition; the links may be distributed among the command line
1501 arguments (possibly hierarchies) so that the link count of
1502 the final, once-linked source file is reduced to 1 when it is
1503 considered below. But in this case (for mv) we don't need to
1504 incur the expense of recording the dev/ino => name mapping; all we
1505 really need is a lookup, to see if the dev/ino pair has already
1506 been copied.
1507 - when using -H and processing a command line argument;
1508 that command line argument could be a symlink pointing to another
1509 command line argument. With `cp -H --preserve=link', we hard-link
1510 those two destination files.
1511 - likewise for -L except that it applies to all files, not just
1512 command line arguments.
1514 Also, with --recursive, record dev/ino of each command-line directory.
1515 We'll use that info to detect this problem: cp -R dir dir. */
1517 if (x->move_mode && src_sb.st_nlink == 1)
1519 earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev);
1521 else if (x->preserve_links
1522 && !x->hard_link
1523 && (1 < src_sb.st_nlink
1524 || (command_line_arg
1525 && x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
1526 || x->dereference == DEREF_ALWAYS))
1528 earlier_file = remember_copied (dst_name, src_sb.st_ino, src_sb.st_dev);
1530 else if (x->recursive && S_ISDIR (src_mode))
1532 if (command_line_arg)
1533 earlier_file = remember_copied (dst_name, src_sb.st_ino, src_sb.st_dev);
1534 else
1535 earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev);
1538 /* Did we copy this inode somewhere else (in this command line argument)
1539 and therefore this is a second hard link to the inode? */
1541 if (earlier_file)
1543 /* Avoid damaging the destination file system by refusing to preserve
1544 hard-linked directories (which are found at least in Netapp snapshot
1545 directories). */
1546 if (S_ISDIR (src_mode))
1548 /* If src_name and earlier_file refer to the same directory entry,
1549 then warn about copying a directory into itself. */
1550 if (same_name (src_name, earlier_file))
1552 error (0, 0, _("cannot copy a directory, %s, into itself, %s"),
1553 quote_n (0, top_level_src_name),
1554 quote_n (1, top_level_dst_name));
1555 *copy_into_self = true;
1556 goto un_backup;
1558 else if (x->dereference == DEREF_ALWAYS)
1560 /* This happens when e.g., encountering a directory for the
1561 second or subsequent time via symlinks when cp is invoked
1562 with -R and -L. E.g.,
1563 rm -rf a b c d; mkdir a b c d; ln -s ../c a; ln -s ../c b;
1564 cp -RL a b d
1567 else
1569 error (0, 0, _("will not create hard link %s to directory %s"),
1570 quote_n (0, dst_name), quote_n (1, earlier_file));
1571 goto un_backup;
1574 else
1576 bool link_failed = (link (earlier_file, dst_name) != 0);
1578 /* If the link failed because of an existing destination,
1579 remove that file and then call link again. */
1580 if (link_failed && errno == EEXIST)
1582 if (unlink (dst_name) != 0)
1584 error (0, errno, _("cannot remove %s"), quote (dst_name));
1585 goto un_backup;
1587 if (x->verbose)
1588 printf (_("removed %s\n"), quote (dst_name));
1589 link_failed = (link (earlier_file, dst_name) != 0);
1592 if (link_failed)
1594 error (0, errno, _("cannot create hard link %s to %s"),
1595 quote_n (0, dst_name), quote_n (1, earlier_file));
1596 goto un_backup;
1599 return true;
1603 if (x->move_mode)
1605 if (rename (src_name, dst_name) == 0)
1607 if (x->verbose && S_ISDIR (src_mode))
1608 emit_verbose (src_name, dst_name,
1609 backup_succeeded ? dst_backup : NULL);
1611 if (rename_succeeded)
1612 *rename_succeeded = true;
1614 if (command_line_arg)
1616 /* Record destination dev/ino/name, so that if we are asked
1617 to overwrite that file again, we can detect it and fail. */
1618 /* It's fine to use the _source_ stat buffer (src_sb) to get the
1619 _destination_ dev/ino, since the rename above can't have
1620 changed those, and `mv' always uses lstat.
1621 We could limit it further by operating
1622 only on non-directories. */
1623 record_file (x->dest_info, dst_name, &src_sb);
1626 return true;
1629 /* FIXME: someday, consider what to do when moving a directory into
1630 itself but when source and destination are on different devices. */
1632 /* This happens when attempting to rename a directory to a
1633 subdirectory of itself. */
1634 if (errno == EINVAL)
1636 /* FIXME: this is a little fragile in that it relies on rename(2)
1637 failing with a specific errno value. Expect problems on
1638 non-POSIX systems. */
1639 error (0, 0, _("cannot move %s to a subdirectory of itself, %s"),
1640 quote_n (0, top_level_src_name),
1641 quote_n (1, top_level_dst_name));
1643 /* Note that there is no need to call forget_created here,
1644 (compare with the other calls in this file) since the
1645 destination directory didn't exist before. */
1647 *copy_into_self = true;
1648 /* FIXME-cleanup: Don't return true here; adjust mv.c accordingly.
1649 The only caller that uses this code (mv.c) ends up setting its
1650 exit status to nonzero when copy_into_self is nonzero. */
1651 return true;
1654 /* WARNING: there probably exist systems for which an inter-device
1655 rename fails with a value of errno not handled here.
1656 If/as those are reported, add them to the condition below.
1657 If this happens to you, please do the following and send the output
1658 to the bug-reporting address (e.g., in the output of cp --help):
1659 touch k; perl -e 'rename "k","/tmp/k" or print "$!(",$!+0,")\n"'
1660 where your current directory is on one partion and /tmp is the other.
1661 Also, please try to find the E* errno macro name corresponding to
1662 the diagnostic and parenthesized integer, and include that in your
1663 e-mail. One way to do that is to run a command like this
1664 find /usr/include/. -type f \
1665 | xargs grep 'define.*\<E[A-Z]*\>.*\<18\>' /dev/null
1666 where you'd replace `18' with the integer in parentheses that
1667 was output from the perl one-liner above.
1668 If necessary, of course, change `/tmp' to some other directory. */
1669 if (errno != EXDEV)
1671 /* There are many ways this can happen due to a race condition.
1672 When something happens between the initial XSTAT and the
1673 subsequent rename, we can get many different types of errors.
1674 For example, if the destination is initially a non-directory
1675 or non-existent, but it is created as a directory, the rename
1676 fails. If two `mv' commands try to rename the same file at
1677 about the same time, one will succeed and the other will fail.
1678 If the permissions on the directory containing the source or
1679 destination file are made too restrictive, the rename will
1680 fail. Etc. */
1681 error (0, errno,
1682 _("cannot move %s to %s"),
1683 quote_n (0, src_name), quote_n (1, dst_name));
1684 forget_created (src_sb.st_ino, src_sb.st_dev);
1685 return false;
1688 /* The rename attempt has failed. Remove any existing destination
1689 file so that a cross-device `mv' acts as if it were really using
1690 the rename syscall. */
1691 if (unlink (dst_name) != 0 && errno != ENOENT)
1693 error (0, errno,
1694 _("inter-device move failed: %s to %s; unable to remove target"),
1695 quote_n (0, src_name), quote_n (1, dst_name));
1696 forget_created (src_sb.st_ino, src_sb.st_dev);
1697 return false;
1700 new_dst = true;
1703 /* If the ownership might change, or if it is a directory (whose
1704 special mode bits may change after the directory is created),
1705 omit some permissions at first, so unauthorized users cannot nip
1706 in before the file is ready. */
1707 dst_mode_bits = (x->set_mode ? x->mode : src_mode) & CHMOD_MODE_BITS;
1708 omitted_permissions =
1709 (dst_mode_bits
1710 & (x->preserve_ownership ? S_IRWXG | S_IRWXO
1711 : S_ISDIR (src_mode) ? S_IWGRP | S_IWOTH
1712 : 0));
1714 delayed_ok = true;
1716 if (x->preserve_security_context)
1718 security_context_t con;
1720 if (0 <= lgetfilecon (src_name, &con))
1722 if (setfscreatecon (con) < 0)
1724 error (0, errno,
1725 _("failed to set default file creation context to %s"),
1726 quote (con));
1727 if (x->require_preserve_context)
1729 freecon (con);
1730 return false;
1733 freecon (con);
1735 else
1737 if (errno != ENOTSUP && errno != ENODATA)
1739 error (0, errno,
1740 _("failed to get security context of %s"),
1741 quote (src_name));
1742 if (x->require_preserve_context)
1743 return false;
1748 /* In certain modes (cp's --symbolic-link), and for certain file types
1749 (symlinks and hard links) it doesn't make sense to preserve metadata,
1750 or it's possible to preserve only some of it.
1751 In such cases, set this variable to zero. */
1752 preserve_metadata = true;
1754 if (S_ISDIR (src_mode))
1756 struct dir_list *dir;
1758 /* If this directory has been copied before during the
1759 recursion, there is a symbolic link to an ancestor
1760 directory of the symbolic link. It is impossible to
1761 continue to copy this, unless we've got an infinite disk. */
1763 if (is_ancestor (&src_sb, ancestors))
1765 error (0, 0, _("cannot copy cyclic symbolic link %s"),
1766 quote (src_name));
1767 goto un_backup;
1770 /* Insert the current directory in the list of parents. */
1772 dir = alloca (sizeof *dir);
1773 dir->parent = ancestors;
1774 dir->ino = src_sb.st_ino;
1775 dir->dev = src_sb.st_dev;
1777 if (new_dst || !S_ISDIR (dst_sb.st_mode))
1779 /* POSIX says mkdir's behavior is implementation-defined when
1780 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
1781 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
1782 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
1783 if (mkdir (dst_name, dst_mode_bits & ~omitted_permissions) != 0)
1785 error (0, errno, _("cannot create directory %s"),
1786 quote (dst_name));
1787 goto un_backup;
1790 /* We need search and write permissions to the new directory
1791 for writing the directory's contents. Check if these
1792 permissions are there. */
1794 if (lstat (dst_name, &dst_sb) != 0)
1796 error (0, errno, _("cannot stat %s"), quote (dst_name));
1797 goto un_backup;
1799 else if ((dst_sb.st_mode & S_IRWXU) != S_IRWXU)
1801 /* Make the new directory searchable and writable. */
1803 dst_mode = dst_sb.st_mode;
1804 restore_dst_mode = true;
1806 if (lchmod (dst_name, dst_mode | S_IRWXU) != 0)
1808 error (0, errno, _("setting permissions for %s"),
1809 quote (dst_name));
1810 goto un_backup;
1814 /* Insert the created directory's inode and device
1815 numbers into the search structure, so that we can
1816 avoid copying it again. */
1817 if (!x->hard_link)
1818 remember_copied (dst_name, dst_sb.st_ino, dst_sb.st_dev);
1820 if (x->verbose)
1821 emit_verbose (src_name, dst_name, NULL);
1824 /* Decide whether to copy the contents of the directory. */
1825 if (x->one_file_system && device != 0 && device != src_sb.st_dev)
1827 /* Here, we are crossing a file system boundary and cp's -x option
1828 is in effect: so don't copy the contents of this directory. */
1830 else
1832 /* Copy the contents of the directory. Don't just return if
1833 this fails -- otherwise, the failure to read a single file
1834 in a source directory would cause the containing destination
1835 directory not to have owner/perms set properly. */
1836 delayed_ok = copy_dir (src_name, dst_name, new_dst, &src_sb, dir, x,
1837 copy_into_self);
1840 else if (x->symbolic_link)
1842 preserve_metadata = false;
1844 if (*src_name != '/')
1846 /* Check that DST_NAME denotes a file in the current directory. */
1847 struct stat dot_sb;
1848 struct stat dst_parent_sb;
1849 char *dst_parent;
1850 bool in_current_dir;
1852 dst_parent = dir_name (dst_name);
1854 in_current_dir = (STREQ (".", dst_parent)
1855 /* If either stat call fails, it's ok not to report
1856 the failure and say dst_name is in the current
1857 directory. Other things will fail later. */
1858 || stat (".", &dot_sb) != 0
1859 || stat (dst_parent, &dst_parent_sb) != 0
1860 || SAME_INODE (dot_sb, dst_parent_sb));
1861 free (dst_parent);
1863 if (! in_current_dir)
1865 error (0, 0,
1866 _("%s: can make relative symbolic links only in current directory"),
1867 quote (dst_name));
1868 goto un_backup;
1871 if (symlink (src_name, dst_name) != 0)
1873 error (0, errno, _("cannot create symbolic link %s to %s"),
1874 quote_n (0, dst_name), quote_n (1, src_name));
1875 goto un_backup;
1879 else if (x->hard_link
1880 #ifdef LINK_FOLLOWS_SYMLINKS
1881 /* A POSIX-conforming link syscall dereferences a symlink, yet cp,
1882 invoked with `--link --no-dereference', should not. Thus, with
1883 a POSIX-conforming link system call, we can't use link() here,
1884 since that would create a hard link to the referent (effectively
1885 dereferencing the symlink), rather than to the symlink itself.
1886 We can approximate the desired behavior by skipping this hard-link
1887 creating block and instead copying the symlink, via the `S_ISLNK'-
1888 copying code below.
1889 When link operates on the symlinks themselves, we use this block
1890 and just call link(). */
1891 && !(S_ISLNK (src_mode) && x->dereference == DEREF_NEVER)
1892 #endif
1895 preserve_metadata = false;
1896 if (link (src_name, dst_name))
1898 error (0, errno, _("cannot create link %s"), quote (dst_name));
1899 goto un_backup;
1902 else if (S_ISREG (src_mode)
1903 || (x->copy_as_regular && !S_ISLNK (src_mode)))
1905 copied_as_regular = true;
1906 /* POSIX says the permission bits of the source file must be
1907 used as the 3rd argument in the open call. Historical
1908 practice passed all the source mode bits to 'open', but the extra
1909 bits were ignored, so it should be the same either way. */
1910 if (! copy_reg (src_name, dst_name, x, src_mode & S_IRWXUGO,
1911 omitted_permissions, &new_dst, &src_sb))
1912 goto un_backup;
1914 else if (S_ISFIFO (src_mode))
1916 /* Use mknod, rather than mkfifo, because the former preserves
1917 the special mode bits of a fifo on Solaris 10, while mkfifo
1918 does not. But fall back on mkfifo, because on some BSD systems,
1919 mknod always fails when asked to create a FIFO. */
1920 if (mknod (dst_name, src_mode & ~omitted_permissions, 0) != 0)
1921 if (mkfifo (dst_name, src_mode & ~S_IFIFO & ~omitted_permissions) != 0)
1923 error (0, errno, _("cannot create fifo %s"), quote (dst_name));
1924 goto un_backup;
1927 else if (S_ISBLK (src_mode) || S_ISCHR (src_mode) || S_ISSOCK (src_mode))
1929 if (mknod (dst_name, src_mode & ~omitted_permissions, src_sb.st_rdev)
1930 != 0)
1932 error (0, errno, _("cannot create special file %s"),
1933 quote (dst_name));
1934 goto un_backup;
1937 else if (S_ISLNK (src_mode))
1939 char *src_link_val = areadlink_with_size (src_name, src_sb.st_size);
1940 if (src_link_val == NULL)
1942 error (0, errno, _("cannot read symbolic link %s"), quote (src_name));
1943 goto un_backup;
1946 if (symlink (src_link_val, dst_name) == 0)
1947 free (src_link_val);
1948 else
1950 int saved_errno = errno;
1951 bool same_link = false;
1952 if (x->update && !new_dst && S_ISLNK (dst_sb.st_mode)
1953 && dst_sb.st_size == strlen (src_link_val))
1955 /* See if the destination is already the desired symlink.
1956 FIXME: This behavior isn't documented, and seems wrong
1957 in some cases, e.g., if the destination symlink has the
1958 wrong ownership, permissions, or time stamps. */
1959 char *dest_link_val =
1960 areadlink_with_size (dst_name, dst_sb.st_size);
1961 if (dest_link_val && STREQ (dest_link_val, src_link_val))
1962 same_link = true;
1963 free (dest_link_val);
1965 free (src_link_val);
1967 if (! same_link)
1969 error (0, saved_errno, _("cannot create symbolic link %s"),
1970 quote (dst_name));
1971 goto un_backup;
1975 if (x->preserve_security_context)
1976 restore_default_fscreatecon_or_die ();
1978 /* There's no need to preserve timestamps or permissions. */
1979 preserve_metadata = false;
1981 if (x->preserve_ownership)
1983 /* Preserve the owner and group of the just-`copied'
1984 symbolic link, if possible. */
1985 if (HAVE_LCHOWN
1986 && lchown (dst_name, src_sb.st_uid, src_sb.st_gid) != 0
1987 && ! chown_failure_ok (x))
1989 error (0, errno, _("failed to preserve ownership for %s"),
1990 dst_name);
1991 goto un_backup;
1993 else
1995 /* Can't preserve ownership of symlinks.
1996 FIXME: maybe give a warning or even error for symlinks
1997 in directories with the sticky bit set -- there, not
1998 preserving owner/group is a potential security problem. */
2002 else
2004 error (0, 0, _("%s has unknown file type"), quote (src_name));
2005 goto un_backup;
2008 if (command_line_arg && x->dest_info)
2010 /* Now that the destination file is very likely to exist,
2011 add its info to the set. */
2012 struct stat sb;
2013 if (lstat (dst_name, &sb) == 0)
2014 record_file (x->dest_info, dst_name, &sb);
2017 if ( ! preserve_metadata)
2018 return true;
2020 if (copied_as_regular)
2021 return delayed_ok;
2023 /* POSIX says that `cp -p' must restore the following:
2024 - permission bits
2025 - setuid, setgid bits
2026 - owner and group
2027 If it fails to restore any of those, we may give a warning but
2028 the destination must not be removed.
2029 FIXME: implement the above. */
2031 /* Adjust the times (and if possible, ownership) for the copy.
2032 chown turns off set[ug]id bits for non-root,
2033 so do the chmod last. */
2035 if (x->preserve_timestamps)
2037 struct timespec timespec[2];
2038 timespec[0] = get_stat_atime (&src_sb);
2039 timespec[1] = get_stat_mtime (&src_sb);
2041 if (utimens (dst_name, timespec) != 0)
2043 error (0, errno, _("preserving times for %s"), quote (dst_name));
2044 if (x->require_preserve)
2045 return false;
2049 /* Avoid calling chown if we know it's not necessary. */
2050 if (x->preserve_ownership
2051 && (new_dst || !SAME_OWNER_AND_GROUP (src_sb, dst_sb)))
2053 switch (set_owner (x, dst_name, -1, &src_sb, new_dst, &dst_sb))
2055 case -1:
2056 return false;
2058 case 0:
2059 src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX);
2060 break;
2064 set_author (dst_name, -1, &src_sb);
2066 if (x->preserve_xattr && ! copy_attr_by_name (src_name, dst_name)
2067 && x->require_preserve_xattr)
2068 return false;
2070 if (x->preserve_mode || x->move_mode)
2072 if (copy_acl (src_name, -1, dst_name, -1, src_mode) != 0
2073 && x->require_preserve)
2074 return false;
2076 else if (x->set_mode)
2078 if (set_acl (dst_name, -1, x->mode) != 0)
2079 return false;
2081 else
2083 if (omitted_permissions)
2085 omitted_permissions &= ~ cached_umask ();
2087 if (omitted_permissions && !restore_dst_mode)
2089 /* Permissions were deliberately omitted when the file
2090 was created due to security concerns. See whether
2091 they need to be re-added now. It'd be faster to omit
2092 the lstat, but deducing the current destination mode
2093 is tricky in the presence of implementation-defined
2094 rules for special mode bits. */
2095 if (new_dst && lstat (dst_name, &dst_sb) != 0)
2097 error (0, errno, _("cannot stat %s"), quote (dst_name));
2098 return false;
2100 dst_mode = dst_sb.st_mode;
2101 if (omitted_permissions & ~dst_mode)
2102 restore_dst_mode = true;
2106 if (restore_dst_mode)
2108 if (lchmod (dst_name, dst_mode | omitted_permissions) != 0)
2110 error (0, errno, _("preserving permissions for %s"),
2111 quote (dst_name));
2112 if (x->require_preserve)
2113 return false;
2118 return delayed_ok;
2120 un_backup:
2122 if (x->preserve_security_context)
2123 restore_default_fscreatecon_or_die ();
2125 /* We have failed to create the destination file.
2126 If we've just added a dev/ino entry via the remember_copied
2127 call above (i.e., unless we've just failed to create a hard link),
2128 remove the entry associating the source dev/ino with the
2129 destination file name, so we don't try to `preserve' a link
2130 to a file we didn't create. */
2131 if (earlier_file == NULL)
2132 forget_created (src_sb.st_ino, src_sb.st_dev);
2134 if (dst_backup)
2136 if (rename (dst_backup, dst_name) != 0)
2137 error (0, errno, _("cannot un-backup %s"), quote (dst_name));
2138 else
2140 if (x->verbose)
2141 printf (_("%s -> %s (unbackup)\n"),
2142 quote_n (0, dst_backup), quote_n (1, dst_name));
2145 return false;
2148 static bool
2149 valid_options (const struct cp_options *co)
2151 assert (co != NULL);
2152 assert (VALID_BACKUP_TYPE (co->backup_type));
2153 assert (VALID_SPARSE_MODE (co->sparse_mode));
2154 assert (!(co->hard_link && co->symbolic_link));
2155 return true;
2158 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
2159 any type. NONEXISTENT_DST should be true if the file DST_NAME
2160 is known not to exist (e.g., because its parent directory was just
2161 created); NONEXISTENT_DST should be false if DST_NAME might already
2162 exist. OPTIONS is ... FIXME-describe
2163 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
2164 same as) DST_NAME; otherwise, set clear it.
2165 Return true if successful. */
2167 extern bool
2168 copy (char const *src_name, char const *dst_name,
2169 bool nonexistent_dst, const struct cp_options *options,
2170 bool *copy_into_self, bool *rename_succeeded)
2172 assert (valid_options (options));
2174 /* Record the file names: they're used in case of error, when copying
2175 a directory into itself. I don't like to make these tools do *any*
2176 extra work in the common case when that work is solely to handle
2177 exceptional cases, but in this case, I don't see a way to derive the
2178 top level source and destination directory names where they're used.
2179 An alternative is to use COPY_INTO_SELF and print the diagnostic
2180 from every caller -- but I don't want to do that. */
2181 top_level_src_name = src_name;
2182 top_level_dst_name = dst_name;
2184 return copy_internal (src_name, dst_name, nonexistent_dst, 0, NULL,
2185 options, true, copy_into_self, rename_succeeded);
2188 /* Set *X to the default options for a value of type struct cp_options. */
2190 extern void
2191 cp_options_default (struct cp_options *x)
2193 memset (x, 0, sizeof *x);
2194 #ifdef PRIV_FILE_CHOWN
2196 priv_set_t *pset = priv_allocset ();
2197 if (!pset)
2198 xalloc_die ();
2199 if (getppriv (PRIV_EFFECTIVE, pset) == 0)
2201 x->chown_privileges = priv_ismember (pset, PRIV_FILE_CHOWN);
2202 x->owner_privileges = priv_ismember (pset, PRIV_FILE_OWNER);
2204 priv_freeset (pset);
2206 #else
2207 x->chown_privileges = x->owner_privileges = (geteuid () == 0);
2208 #endif
2211 /* Return true if it's OK for chown to fail, where errno is
2212 the error number that chown failed with and X is the copying
2213 option set. */
2215 extern bool
2216 chown_failure_ok (struct cp_options const *x)
2218 /* If non-root uses -p, it's ok if we can't preserve ownership.
2219 But root probably wants to know, e.g. if NFS disallows it,
2220 or if the target system doesn't support file ownership. */
2222 return ((errno == EPERM || errno == EINVAL) && !x->chown_privileges);
2225 /* Similarly, return true if it's OK for chmod and similar operations
2226 to fail, where errno is the error number that chmod failed with and
2227 X is the copying option set. */
2229 static bool
2230 owner_failure_ok (struct cp_options const *x)
2232 return ((errno == EPERM || errno == EINVAL) && !x->owner_privileges);
2235 /* Return the user's umask, caching the result. */
2237 extern mode_t
2238 cached_umask (void)
2240 static mode_t mask = (mode_t) -1;
2241 if (mask == (mode_t) -1)
2243 mask = umask (0);
2244 umask (mask);
2246 return mask;