* src/dd.c (flags): noatime and nofollow now depend on
[coreutils/bo.git] / src / copy.c
blob2a85578a607797faff754e73be98ea73bcc6bf07
1 /* copy.c -- core functions for copying files and directories
2 Copyright (C) 89, 90, 91, 1995-2006 Free Software Foundation.
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 2, or (at your option)
7 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, write to the Free Software Foundation,
16 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
18 /* Extracted from cp.c and librarified by Jim Meyering. */
20 #include <config.h>
21 #include <stdio.h>
22 #include <assert.h>
23 #include <sys/types.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 "euidaccess.h"
39 #include "error.h"
40 #include "fcntl--.h"
41 #include "filenamecat.h"
42 #include "full-write.h"
43 #include "getpagesize.h"
44 #include "hash.h"
45 #include "hash-pjw.h"
46 #include "lchmod.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 "xreadlink.h"
54 #include "yesno.h"
56 #ifndef HAVE_FCHOWN
57 # define HAVE_FCHOWN false
58 # define fchown(fd, uid, gid) (-1)
59 #endif
61 #define SAME_OWNER(A, B) ((A).st_uid == (B).st_uid)
62 #define SAME_GROUP(A, B) ((A).st_gid == (B).st_gid)
63 #define SAME_OWNER_AND_GROUP(A, B) (SAME_OWNER (A, B) && SAME_GROUP (A, B))
65 #define UNWRITABLE(File_name, File_mode) \
66 ( /* euidaccess is not meaningful for symlinks */ \
67 ! S_ISLNK (File_mode) \
68 && euidaccess (File_name, W_OK) != 0)
70 struct dir_list
72 struct dir_list *parent;
73 ino_t ino;
74 dev_t dev;
77 /* Describe a just-created or just-renamed destination file. */
78 struct F_triple
80 char *name;
81 ino_t st_ino;
82 dev_t st_dev;
85 /* Initial size of the above hash table. */
86 #define DEST_INFO_INITIAL_CAPACITY 61
88 static bool copy_internal (char const *src_name, char const *dst_name,
89 bool new_dst, dev_t device,
90 struct dir_list *ancestors,
91 const struct cp_options *x,
92 bool command_line_arg,
93 bool *copy_into_self,
94 bool *rename_succeeded);
96 /* Pointers to the file names: they're used in the diagnostic that is issued
97 when we detect the user is trying to copy a directory into itself. */
98 static char const *top_level_src_name;
99 static char const *top_level_dst_name;
101 /* The invocation name of this program. */
102 extern char *program_name;
104 /* FIXME: describe */
105 /* FIXME: rewrite this to use a hash table so we avoid the quadratic
106 performance hit that's probably noticeable only on trees deeper
107 than a few hundred levels. See use of active_dir_map in remove.c */
109 static bool
110 is_ancestor (const struct stat *sb, const struct dir_list *ancestors)
112 while (ancestors != 0)
114 if (ancestors->ino == sb->st_ino && ancestors->dev == sb->st_dev)
115 return true;
116 ancestors = ancestors->parent;
118 return false;
121 /* Read the contents of the directory SRC_NAME_IN, and recursively
122 copy the contents to DST_NAME_IN. NEW_DST is true if
123 DST_NAME_IN is a directory that was created previously in the
124 recursion. SRC_SB and ANCESTORS describe SRC_NAME_IN.
125 Set *COPY_INTO_SELF if SRC_NAME_IN is a parent of
126 (or the same as) DST_NAME_IN; otherwise, clear it.
127 Return true if successful. */
129 static bool
130 copy_dir (char const *src_name_in, char const *dst_name_in, bool new_dst,
131 const struct stat *src_sb, struct dir_list *ancestors,
132 const struct cp_options *x, bool *copy_into_self)
134 char *name_space;
135 char *namep;
136 struct cp_options non_command_line_options = *x;
137 bool ok = true;
139 name_space = savedir (src_name_in);
140 if (name_space == NULL)
142 /* This diagnostic is a bit vague because savedir can fail in
143 several different ways. */
144 error (0, errno, _("cannot access %s"), quote (src_name_in));
145 return false;
148 /* For cp's -H option, dereference command line arguments, but do not
149 dereference symlinks that are found via recursive traversal. */
150 if (x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
151 non_command_line_options.dereference = DEREF_NEVER;
153 namep = name_space;
154 while (*namep != '\0')
156 bool local_copy_into_self;
157 char *src_name = file_name_concat (src_name_in, namep, NULL);
158 char *dst_name = file_name_concat (dst_name_in, namep, NULL);
160 ok &= copy_internal (src_name, dst_name, new_dst, src_sb->st_dev,
161 ancestors, &non_command_line_options, false,
162 &local_copy_into_self, NULL);
163 *copy_into_self |= local_copy_into_self;
165 free (dst_name);
166 free (src_name);
168 namep += strlen (namep) + 1;
170 free (name_space);
171 return ok;
174 /* Set the owner and owning group of DEST_DESC to the st_uid and
175 st_gid fields of SRC_SB. If DEST_DESC is undefined (-1), set
176 the owner and owning group of DST_NAME instead. DEST_DESC must
177 refer to the same file as DEST_NAME if defined.
178 Return true if the syscall succeeds, or if it's ok not to
179 preserve ownership. */
181 static bool
182 set_owner (const struct cp_options *x, char const *dst_name, int dest_desc,
183 uid_t uid, gid_t gid)
185 if (HAVE_FCHOWN && dest_desc != -1)
187 if (fchown (dest_desc, uid, gid) == 0)
188 return true;
190 else
192 if (chown (dst_name, uid, gid) == 0)
193 return true;
196 if (! chown_failure_ok (x))
198 error (0, errno, _("failed to preserve ownership for %s"),
199 quote (dst_name));
200 if (x->require_preserve)
201 return false;
204 return true;
207 /* Set the st_author field of DEST_DESC to the st_author field of
208 SRC_SB. If DEST_DESC is undefined (-1), set the st_author field
209 of DST_NAME instead. DEST_DESC must refer to the same file as
210 DEST_NAME if defined. */
212 static void
213 set_author (const char *dst_name, int dest_desc, const struct stat *src_sb)
215 #if HAVE_STRUCT_STAT_ST_AUTHOR
216 /* Preserve the st_author field. */
217 file_t file = (dest_desc < 0
218 ? file_name_lookup (dst_name, 0, 0)
219 : getdport (dest_desc));
220 if (file == MACH_PORT_NULL)
221 error (0, errno, _("failed to lookup file %s"), quote (dst_name));
222 else
224 error_t err = file_chauthor (file, src_sb->st_author);
225 if (err)
226 error (0, err, _("failed to preserve authorship for %s"),
227 quote (dst_name));
228 mach_port_deallocate (mach_task_self (), file);
230 #endif
233 /* Copy a regular file from SRC_NAME to DST_NAME.
234 If the source file contains holes, copies holes and blocks of zeros
235 in the source file as holes in the destination file.
236 (Holes are read as zeroes by the `read' system call.)
237 Use DST_MODE as the 3rd argument in the call to open.
238 X provides many option settings.
239 Return true if successful.
240 *NEW_DST is as in copy_internal.
241 SRC_SB is the result of calling XSTAT (aka stat) on SRC_NAME. */
243 static bool
244 copy_reg (char const *src_name, char const *dst_name,
245 const struct cp_options *x, mode_t dst_mode, bool *new_dst,
246 struct stat const *src_sb)
248 char *buf;
249 char *buf_alloc = NULL;
250 int dest_desc;
251 int source_desc;
252 struct stat sb;
253 struct stat src_open_sb;
254 bool return_val = true;
256 source_desc = open (src_name, O_RDONLY | O_BINARY);
257 if (source_desc < 0)
259 error (0, errno, _("cannot open %s for reading"), quote (src_name));
260 return false;
263 if (fstat (source_desc, &src_open_sb))
265 error (0, errno, _("cannot fstat %s"), quote (src_name));
266 return_val = false;
267 goto close_src_desc;
270 /* Compare the source dev/ino from the open file to the incoming,
271 saved ones obtained via a previous call to stat. */
272 if (! SAME_INODE (*src_sb, src_open_sb))
274 error (0, 0,
275 _("skipping file %s, as it was replaced while being copied"),
276 quote (src_name));
277 return_val = false;
278 goto close_src_desc;
281 /* These semantics are required for cp.
282 The if-block will be taken in move_mode. */
283 if (*new_dst)
285 dest_desc = open (dst_name, O_WRONLY | O_CREAT | O_BINARY, dst_mode);
287 else
289 dest_desc = open (dst_name, O_WRONLY | O_TRUNC | O_BINARY, dst_mode);
291 if (dest_desc < 0 && x->unlink_dest_after_failed_open)
293 if (unlink (dst_name) != 0)
295 error (0, errno, _("cannot remove %s"), quote (dst_name));
296 return_val = false;
297 goto close_src_desc;
299 if (x->verbose)
300 printf (_("removed %s\n"), quote (dst_name));
302 /* Tell caller that the destination file was unlinked. */
303 *new_dst = true;
305 /* Try the open again, but this time with different flags. */
306 dest_desc = open (dst_name, O_WRONLY | O_CREAT | O_BINARY, dst_mode);
310 if (dest_desc < 0)
312 error (0, errno, _("cannot create regular file %s"), quote (dst_name));
313 return_val = false;
314 goto close_src_desc;
317 if (fstat (dest_desc, &sb))
319 error (0, errno, _("cannot fstat %s"), quote (dst_name));
320 return_val = false;
321 goto close_src_and_dst_desc;
324 if (! (S_ISREG (src_open_sb.st_mode) && src_open_sb.st_size == 0))
326 typedef uintptr_t word;
327 off_t n_read_total = 0;
329 /* Choose a suitable buffer size; it may be adjusted later. */
330 size_t buf_alignment = lcm (getpagesize (), sizeof (word));
331 size_t buf_alignment_slop = sizeof (word) + buf_alignment - 1;
332 size_t buf_size = ST_BLKSIZE (sb);
334 /* Deal with sparse files. */
335 bool last_write_made_hole = false;
336 bool make_holes = false;
338 if (S_ISREG (sb.st_mode))
340 /* Even with --sparse=always, try to create holes only
341 if the destination is a regular file. */
342 if (x->sparse_mode == SPARSE_ALWAYS)
343 make_holes = true;
345 #if HAVE_STRUCT_STAT_ST_BLOCKS
346 /* Use a heuristic to determine whether SRC_NAME contains any sparse
347 blocks. If the file has fewer blocks than would normally be
348 needed for a file of its size, then at least one of the blocks in
349 the file is a hole. */
350 if (x->sparse_mode == SPARSE_AUTO && S_ISREG (src_open_sb.st_mode)
351 && ST_NBLOCKS (src_open_sb) < src_open_sb.st_size / ST_NBLOCKSIZE)
352 make_holes = true;
353 #endif
356 /* If not making a sparse file, try to use a more-efficient
357 buffer size. */
358 if (! make_holes)
360 /* These days there's no point ever messing with buffers smaller
361 than 8 KiB. It would be nice to configure SMALL_BUF_SIZE
362 dynamically for this host and pair of files, but there doesn't
363 seem to be a good way to get readahead info portably. */
364 enum { SMALL_BUF_SIZE = 8 * 1024 };
366 /* Compute the least common multiple of the input and output
367 buffer sizes, adjusting for outlandish values. */
368 size_t blcm_max = MIN (SIZE_MAX, SSIZE_MAX) - buf_alignment_slop;
369 size_t blcm = buffer_lcm (ST_BLKSIZE (src_open_sb), buf_size,
370 blcm_max);
372 /* Do not use a block size that is too small. */
373 buf_size = MAX (SMALL_BUF_SIZE, blcm);
375 /* Do not bother with a buffer larger than the input file, plus one
376 byte to make sure the file has not grown while reading it. */
377 if (S_ISREG (src_open_sb.st_mode) && src_open_sb.st_size < buf_size)
378 buf_size = src_open_sb.st_size + 1;
380 /* However, stick with a block size that is a positive multiple of
381 blcm, overriding the above adjustments. Watch out for
382 overflow. */
383 buf_size += blcm - 1;
384 buf_size -= buf_size % blcm;
385 if (buf_size == 0 || blcm_max < buf_size)
386 buf_size = blcm;
389 /* Make a buffer with space for a sentinel at the end. */
390 buf_alloc = xmalloc (buf_size + buf_alignment_slop);
391 buf = ptr_align (buf_alloc, buf_alignment);
393 for (;;)
395 word *wp = NULL;
397 ssize_t n_read = read (source_desc, buf, buf_size);
398 if (n_read < 0)
400 #ifdef EINTR
401 if (errno == EINTR)
402 continue;
403 #endif
404 error (0, errno, _("reading %s"), quote (src_name));
405 return_val = false;
406 goto close_src_and_dst_desc;
408 if (n_read == 0)
409 break;
411 n_read_total += n_read;
413 if (make_holes)
415 char *cp;
417 buf[n_read] = 1; /* Sentinel to stop loop. */
419 /* Find first nonzero *word*, or the word with the sentinel. */
421 wp = (word *) buf;
422 while (*wp++ == 0)
423 continue;
425 /* Find the first nonzero *byte*, or the sentinel. */
427 cp = (char *) (wp - 1);
428 while (*cp++ == 0)
429 continue;
431 if (cp <= buf + n_read)
432 /* Clear to indicate that a normal write is needed. */
433 wp = NULL;
434 else
436 /* We found the sentinel, so the whole input block was zero.
437 Make a hole. */
438 if (lseek (dest_desc, n_read, SEEK_CUR) < 0)
440 error (0, errno, _("cannot lseek %s"), quote (dst_name));
441 return_val = false;
442 goto close_src_and_dst_desc;
444 last_write_made_hole = true;
448 if (!wp)
450 size_t n = n_read;
451 if (full_write (dest_desc, buf, n) != n)
453 error (0, errno, _("writing %s"), quote (dst_name));
454 return_val = false;
455 goto close_src_and_dst_desc;
457 last_write_made_hole = false;
459 /* A short read on a regular file means EOF. */
460 if (n_read != buf_size && S_ISREG (src_open_sb.st_mode))
461 break;
465 /* If the file ends with a `hole', we need to do something to record
466 the length of the file. On modern systems, calling ftruncate does
467 the job. On systems without native ftruncate support, we have to
468 write a byte at the ending position. Otherwise the kernel would
469 truncate the file at the end of the last write operation. */
471 if (last_write_made_hole)
473 if (HAVE_FTRUNCATE
474 ? /* ftruncate sets the file size,
475 so there is no need for a write. */
476 ftruncate (dest_desc, n_read_total) < 0
477 : /* Seek backwards one character and write a null. */
478 (lseek (dest_desc, (off_t) -1, SEEK_CUR) < 0L
479 || full_write (dest_desc, "", 1) != 1))
481 error (0, errno, _("writing %s"), quote (dst_name));
482 return_val = false;
483 goto close_src_and_dst_desc;
488 if (x->preserve_timestamps)
490 struct timespec timespec[2];
491 timespec[0] = get_stat_atime (src_sb);
492 timespec[1] = get_stat_mtime (src_sb);
494 if (futimens (dest_desc, dst_name, timespec) != 0)
496 error (0, errno, _("preserving times for %s"), quote (dst_name));
497 if (x->require_preserve)
499 return_val = false;
500 goto close_src_and_dst_desc;
505 if (x->preserve_ownership && ! SAME_OWNER_AND_GROUP (*src_sb, sb))
507 if (! set_owner (x, dst_name, dest_desc, src_sb->st_uid, src_sb->st_gid))
509 return_val = false;
510 goto close_src_and_dst_desc;
514 set_author (dst_name, dest_desc, src_sb);
516 if (x->preserve_mode || x->move_mode)
518 if (copy_acl (src_name, source_desc, dst_name, dest_desc,
519 src_sb->st_mode) != 0 && x->require_preserve)
520 return_val = false;
522 else if (x->set_mode)
524 if (set_acl (dst_name, dest_desc, x->mode) != 0)
525 return_val = false;
528 close_src_and_dst_desc:
529 if (close (dest_desc) < 0)
531 error (0, errno, _("closing %s"), quote (dst_name));
532 return_val = false;
534 close_src_desc:
535 if (close (source_desc) < 0)
537 error (0, errno, _("closing %s"), quote (src_name));
538 return_val = false;
541 free (buf_alloc);
542 return return_val;
545 /* Return true if it's ok that the source and destination
546 files are the `same' by some measure. The goal is to avoid
547 making the `copy' operation remove both copies of the file
548 in that case, while still allowing the user to e.g., move or
549 copy a regular file onto a symlink that points to it.
550 Try to minimize the cost of this function in the common case.
551 Set *RETURN_NOW if we've determined that the caller has no more
552 work to do and should return successfully, right away.
554 Set *UNLINK_SRC if we've determined that the caller wants to do
555 `rename (a, b)' where `a' and `b' are distinct hard links to the same
556 file. In that case, the caller should try to unlink `a' and then return
557 successfully. Ideally, we wouldn't have to do that, and we'd be
558 able to rely on rename to remove the source file. However, POSIX
559 mistakenly requires that such a rename call do *nothing* and return
560 successfully. */
562 static bool
563 same_file_ok (char const *src_name, struct stat const *src_sb,
564 char const *dst_name, struct stat const *dst_sb,
565 const struct cp_options *x, bool *return_now, bool *unlink_src)
567 const struct stat *src_sb_link;
568 const struct stat *dst_sb_link;
569 struct stat tmp_dst_sb;
570 struct stat tmp_src_sb;
572 bool same_link;
573 bool same = SAME_INODE (*src_sb, *dst_sb);
575 *return_now = false;
576 *unlink_src = false;
578 /* FIXME: this should (at the very least) be moved into the following
579 if-block. More likely, it should be removed, because it inhibits
580 making backups. But removing it will result in a change in behavior
581 that will probably have to be documented -- and tests will have to
582 be updated. */
583 if (same && x->hard_link)
585 *return_now = true;
586 return true;
589 if (x->dereference == DEREF_NEVER)
591 same_link = same;
593 /* If both the source and destination files are symlinks (and we'll
594 know this here IFF preserving symlinks), then it's ok -- as long
595 as they are distinct. */
596 if (S_ISLNK (src_sb->st_mode) && S_ISLNK (dst_sb->st_mode))
597 return ! same_name (src_name, dst_name);
599 src_sb_link = src_sb;
600 dst_sb_link = dst_sb;
602 else
604 if (!same)
605 return true;
607 if (lstat (dst_name, &tmp_dst_sb) != 0
608 || lstat (src_name, &tmp_src_sb) != 0)
609 return true;
611 src_sb_link = &tmp_src_sb;
612 dst_sb_link = &tmp_dst_sb;
614 same_link = SAME_INODE (*src_sb_link, *dst_sb_link);
616 /* If both are symlinks, then it's ok, but only if the destination
617 will be unlinked before being opened. This is like the test
618 above, but with the addition of the unlink_dest_before_opening
619 conjunct because otherwise, with two symlinks to the same target,
620 we'd end up truncating the source file. */
621 if (S_ISLNK (src_sb_link->st_mode) && S_ISLNK (dst_sb_link->st_mode)
622 && x->unlink_dest_before_opening)
623 return true;
626 /* The backup code ensures there's a copy, so it's usually ok to
627 remove any destination file. One exception is when both
628 source and destination are the same directory entry. In that
629 case, moving the destination file aside (in making the backup)
630 would also rename the source file and result in an error. */
631 if (x->backup_type != no_backups)
633 if (!same_link)
635 /* In copy mode when dereferencing symlinks, if the source is a
636 symlink and the dest is not, then backing up the destination
637 (moving it aside) would make it a dangling symlink, and the
638 subsequent attempt to open it in copy_reg would fail with
639 a misleading diagnostic. Avoid that by returning zero in
640 that case so the caller can make cp (or mv when it has to
641 resort to reading the source file) fail now. */
643 /* FIXME-note: even with the following kludge, we can still provoke
644 the offending diagnostic. It's just a little harder to do :-)
645 $ rm -f a b c; touch c; ln -s c b; ln -s b a; cp -b a b
646 cp: cannot open `a' for reading: No such file or directory
647 That's misleading, since a subsequent `ls' shows that `a'
648 is still there.
649 One solution would be to open the source file *before* moving
650 aside the destination, but that'd involve a big rewrite. */
651 if ( ! x->move_mode
652 && x->dereference != DEREF_NEVER
653 && S_ISLNK (src_sb_link->st_mode)
654 && ! S_ISLNK (dst_sb_link->st_mode))
655 return false;
657 return true;
660 return ! same_name (src_name, dst_name);
663 #if 0
664 /* FIXME: use or remove */
666 /* If we're making a backup, we'll detect the problem case in
667 copy_reg because SRC_NAME will no longer exist. Allowing
668 the test to be deferred lets cp do some useful things.
669 But when creating hardlinks and SRC_NAME is a symlink
670 but DST_NAME is not we must test anyway. */
671 if (x->hard_link
672 || !S_ISLNK (src_sb_link->st_mode)
673 || S_ISLNK (dst_sb_link->st_mode))
674 return true;
676 if (x->dereference != DEREF_NEVER)
677 return true;
678 #endif
680 /* They may refer to the same file if we're in move mode and the
681 target is a symlink. That is ok, since we remove any existing
682 destination file before opening it -- via `rename' if they're on
683 the same file system, via `unlink (DST_NAME)' otherwise.
684 It's also ok if they're distinct hard links to the same file. */
685 if (x->move_mode || x->unlink_dest_before_opening)
687 if (S_ISLNK (dst_sb_link->st_mode))
688 return true;
690 if (same_link
691 && 1 < dst_sb_link->st_nlink
692 && ! same_name (src_name, dst_name))
694 if (x->move_mode)
696 *unlink_src = true;
697 *return_now = true;
699 return true;
703 /* If neither is a symlink, then it's ok as long as they aren't
704 hard links to the same file. */
705 if (!S_ISLNK (src_sb_link->st_mode) && !S_ISLNK (dst_sb_link->st_mode))
707 if (!SAME_INODE (*src_sb_link, *dst_sb_link))
708 return true;
710 /* If they are the same file, it's ok if we're making hard links. */
711 if (x->hard_link)
713 *return_now = true;
714 return true;
718 /* It's ok to remove a destination symlink. But that works only when we
719 unlink before opening the destination and when the source and destination
720 files are on the same partition. */
721 if (x->unlink_dest_before_opening
722 && S_ISLNK (dst_sb_link->st_mode))
723 return dst_sb_link->st_dev == src_sb_link->st_dev;
725 if (x->dereference == DEREF_NEVER)
727 if ( ! S_ISLNK (src_sb_link->st_mode))
728 tmp_src_sb = *src_sb_link;
729 else if (stat (src_name, &tmp_src_sb) != 0)
730 return true;
732 if ( ! S_ISLNK (dst_sb_link->st_mode))
733 tmp_dst_sb = *dst_sb_link;
734 else if (stat (dst_name, &tmp_dst_sb) != 0)
735 return true;
737 if ( ! SAME_INODE (tmp_src_sb, tmp_dst_sb))
738 return true;
740 /* FIXME: shouldn't this be testing whether we're making symlinks? */
741 if (x->hard_link)
743 *return_now = true;
744 return true;
748 return false;
751 static void
752 overwrite_prompt (char const *dst_name, struct stat const *dst_sb)
754 if (euidaccess (dst_name, W_OK) != 0)
756 fprintf (stderr,
757 _("%s: overwrite %s, overriding mode %04lo? "),
758 program_name, quote (dst_name),
759 (unsigned long int) (dst_sb->st_mode & CHMOD_MODE_BITS));
761 else
763 fprintf (stderr, _("%s: overwrite %s? "),
764 program_name, quote (dst_name));
768 /* Hash an F_triple. */
769 static size_t
770 triple_hash (void const *x, size_t table_size)
772 struct F_triple const *p = x;
774 /* Also take the name into account, so that when moving N hard links to the
775 same file (all listed on the command line) all into the same directory,
776 we don't experience any N^2 behavior. */
777 /* FIXME-maybe: is it worth the overhead of doing this
778 just to avoid N^2 in such an unusual case? N would have
779 to be very large to make the N^2 factor noticable, and
780 one would probably encounter a limit on the length of
781 a command line before it became a problem. */
782 size_t tmp = hash_pjw (p->name, table_size);
784 /* Ignoring the device number here should be fine. */
785 return (tmp | p->st_ino) % table_size;
788 /* Hash an F_triple. */
789 static size_t
790 triple_hash_no_name (void const *x, size_t table_size)
792 struct F_triple const *p = x;
794 /* Ignoring the device number here should be fine. */
795 return p->st_ino % table_size;
798 /* Compare two F_triple structs. */
799 static bool
800 triple_compare (void const *x, void const *y)
802 struct F_triple const *a = x;
803 struct F_triple const *b = y;
804 return (SAME_INODE (*a, *b) && same_name (a->name, b->name)) ? true : false;
807 /* Free an F_triple. */
808 static void
809 triple_free (void *x)
811 struct F_triple *a = x;
812 free (a->name);
813 free (a);
816 /* Initialize the hash table implementing a set of F_triple entries
817 corresponding to destination files. */
818 extern void
819 dest_info_init (struct cp_options *x)
821 x->dest_info
822 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
823 NULL,
824 triple_hash,
825 triple_compare,
826 triple_free);
829 /* Initialize the hash table implementing a set of F_triple entries
830 corresponding to source files listed on the command line. */
831 extern void
832 src_info_init (struct cp_options *x)
835 /* Note that we use triple_hash_no_name here.
836 Contrast with the use of triple_hash above.
837 That is necessary because a source file may be specified
838 in many different ways. We want to warn about this
839 cp a a d/
840 as well as this:
841 cp a ./a d/
843 x->src_info
844 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
845 NULL,
846 triple_hash_no_name,
847 triple_compare,
848 triple_free);
851 /* Return true if there is an entry in hash table, HT,
852 for the file described by FILE and STATS. */
853 static bool
854 seen_file (Hash_table const *ht, char const *file,
855 struct stat const *stats)
857 struct F_triple new_ent;
859 if (ht == NULL)
860 return false;
862 new_ent.name = (char *) file;
863 new_ent.st_ino = stats->st_ino;
864 new_ent.st_dev = stats->st_dev;
866 return !!hash_lookup (ht, &new_ent);
869 /* Record destination file, FILE, and dev/ino from *STATS,
870 in the hash table, HT. If HT is NULL, return immediately.
871 If STATS is NULL, call lstat on FILE to get the device
872 and inode numbers. If that lstat fails, simply return.
873 If memory allocation fails, exit immediately. */
874 static void
875 record_file (Hash_table *ht, char const *file,
876 struct stat const *stats)
878 struct F_triple *ent;
880 if (ht == NULL)
881 return;
883 ent = xmalloc (sizeof *ent);
884 ent->name = xstrdup (file);
885 if (stats)
887 ent->st_ino = stats->st_ino;
888 ent->st_dev = stats->st_dev;
890 else
892 struct stat sb;
893 if (lstat (file, &sb) != 0)
894 return;
895 ent->st_ino = sb.st_ino;
896 ent->st_dev = sb.st_dev;
900 struct F_triple *ent_from_table = hash_insert (ht, ent);
901 if (ent_from_table == NULL)
903 /* Insertion failed due to lack of memory. */
904 xalloc_die ();
907 if (ent_from_table != ent)
909 /* There was alread a matching entry in the table, so ENT was
910 not inserted. Free it. */
911 triple_free (ent);
916 /* When effecting a move (e.g., for mv(1)), and given the name DST_NAME
917 of the destination and a corresponding stat buffer, DST_SB, return
918 true if the logical `move' operation should _not_ proceed.
919 Otherwise, return false.
920 Depending on options specified in X, this code may issue an
921 interactive prompt asking whether it's ok to overwrite DST_NAME. */
922 static bool
923 abandon_move (const struct cp_options *x,
924 char const *dst_name,
925 struct stat const *dst_sb)
927 assert (x->move_mode);
928 return (x->interactive == I_ALWAYS_NO
929 || ((x->interactive == I_ASK_USER
930 || (x->interactive == I_UNSPECIFIED
931 && x->stdin_tty
932 && UNWRITABLE (dst_name, dst_sb->st_mode)))
933 && (overwrite_prompt (dst_name, dst_sb), 1)
934 && ! yesno ()));
937 /* Print --verbose output on standard output, e.g. `new' -> `old'.
938 If BACKUP_DST_NAME is non-NULL, then also indicate that it is
939 the name of a backup file. */
940 static void
941 emit_verbose (char const *src, char const *dst, char const *backup_dst_name)
943 printf ("%s -> %s", quote_n (0, src), quote_n (1, dst));
944 if (backup_dst_name)
945 printf (_(" (backup: %s)"), quote (backup_dst_name));
946 putchar ('\n');
949 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
950 any type. NEW_DST should be true if the file DST_NAME cannot
951 exist because its parent directory was just created; NEW_DST should
952 be false if DST_NAME might already exist. DEVICE is the device
953 number of the parent directory, or 0 if the parent of this file is
954 not known. ANCESTORS points to a linked, null terminated list of
955 devices and inodes of parent directories of SRC_NAME. COMMAND_LINE_ARG
956 is true iff SRC_NAME was specified on the command line.
957 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
958 same as) DST_NAME; otherwise, clear it.
959 Return true if successful. */
960 static bool
961 copy_internal (char const *src_name, char const *dst_name,
962 bool new_dst,
963 dev_t device,
964 struct dir_list *ancestors,
965 const struct cp_options *x,
966 bool command_line_arg,
967 bool *copy_into_self,
968 bool *rename_succeeded)
970 struct stat src_sb;
971 struct stat dst_sb;
972 mode_t src_mode;
973 mode_t src_type;
974 mode_t dst_mode IF_LINT (= 0);
975 bool restore_dst_mode = false;
976 char *earlier_file = NULL;
977 char *dst_backup = NULL;
978 bool backup_succeeded = false;
979 bool delayed_ok;
980 bool copied_as_regular = false;
981 bool preserve_metadata;
983 if (x->move_mode && rename_succeeded)
984 *rename_succeeded = false;
986 *copy_into_self = false;
988 if (XSTAT (x, src_name, &src_sb) != 0)
990 error (0, errno, _("cannot stat %s"), quote (src_name));
991 return false;
994 src_type = src_sb.st_mode;
996 src_mode = src_sb.st_mode;
998 if (S_ISDIR (src_type) && !x->recursive)
1000 error (0, 0, _("omitting directory %s"), quote (src_name));
1001 return false;
1004 /* Detect the case in which the same source file appears more than
1005 once on the command line and no backup option has been selected.
1006 If so, simply warn and don't copy it the second time.
1007 This check is enabled only if x->src_info is non-NULL. */
1008 if (command_line_arg)
1010 if ( ! S_ISDIR (src_sb.st_mode)
1011 && x->backup_type == no_backups
1012 && seen_file (x->src_info, src_name, &src_sb))
1014 error (0, 0, _("warning: source file %s specified more than once"),
1015 quote (src_name));
1016 return true;
1019 record_file (x->src_info, src_name, &src_sb);
1022 if (!new_dst)
1024 if (XSTAT (x, dst_name, &dst_sb) != 0)
1026 if (errno != ENOENT)
1028 error (0, errno, _("cannot stat %s"), quote (dst_name));
1029 return false;
1031 else
1033 new_dst = true;
1036 else
1037 { /* Here, we know that dst_name exists, at least to the point
1038 that it is XSTAT'able. */
1039 bool return_now;
1040 bool unlink_src;
1042 if (! same_file_ok (src_name, &src_sb, dst_name, &dst_sb,
1043 x, &return_now, &unlink_src))
1045 error (0, 0, _("%s and %s are the same file"),
1046 quote_n (0, src_name), quote_n (1, dst_name));
1047 return false;
1050 /* When there is an existing destination file, we may end up
1051 returning early, and hence not copying/moving the file.
1052 This may be due to an interactive `negative' reply to the
1053 prompt about the existing file. It may also be due to the
1054 use of the --reply=no option.
1056 cp and mv treat -i and -f differently. */
1057 if (x->move_mode)
1059 if (abandon_move (x, dst_name, &dst_sb)
1060 || (unlink_src && unlink (src_name) == 0))
1062 /* Pretend the rename succeeded, so the caller (mv)
1063 doesn't end up removing the source file. */
1064 if (rename_succeeded)
1065 *rename_succeeded = true;
1066 if (unlink_src && x->verbose)
1067 printf (_("removed %s\n"), quote (src_name));
1068 return true;
1070 if (unlink_src)
1072 error (0, errno, _("cannot remove %s"), quote (src_name));
1073 return false;
1076 else
1078 if (! S_ISDIR (src_mode)
1079 && (x->interactive == I_ALWAYS_NO
1080 || (x->interactive == I_ASK_USER
1081 && (overwrite_prompt (dst_name, &dst_sb), 1)
1082 && ! yesno ())))
1083 return true;
1086 if (return_now)
1087 return true;
1089 if (!S_ISDIR (dst_sb.st_mode))
1091 if (S_ISDIR (src_type))
1093 if (x->move_mode && x->backup_type != no_backups)
1095 /* Moving a directory onto an existing
1096 non-directory is ok only with --backup. */
1098 else
1100 error (0, 0,
1101 _("cannot overwrite non-directory %s with directory %s"),
1102 quote_n (0, dst_name), quote_n (1, src_name));
1103 return false;
1107 /* Don't let the user destroy their data, even if they try hard:
1108 This mv command must fail (likewise for cp):
1109 rm -rf a b c; mkdir a b c; touch a/f b/f; mv a/f b/f c
1110 Otherwise, the contents of b/f would be lost.
1111 In the case of `cp', b/f would be lost if the user simulated
1112 a move using cp and rm.
1113 Note that it works fine if you use --backup=numbered. */
1114 if (command_line_arg
1115 && x->backup_type != numbered_backups
1116 && seen_file (x->dest_info, dst_name, &dst_sb))
1118 error (0, 0,
1119 _("will not overwrite just-created %s with %s"),
1120 quote_n (0, dst_name), quote_n (1, src_name));
1121 return false;
1125 if (!S_ISDIR (src_type))
1127 if (S_ISDIR (dst_sb.st_mode))
1129 if (x->move_mode && x->backup_type != no_backups)
1131 /* Moving a non-directory onto an existing
1132 directory is ok only with --backup. */
1134 else
1136 error (0, 0,
1137 _("cannot overwrite directory %s with non-directory"),
1138 quote (dst_name));
1139 return false;
1143 if (x->update)
1145 /* When preserving time stamps (but not moving within a file
1146 system), don't worry if the destination time stamp is
1147 less than the source merely because of time stamp
1148 truncation. */
1149 int options = ((x->preserve_timestamps
1150 && ! (x->move_mode
1151 && dst_sb.st_dev == src_sb.st_dev))
1152 ? UTIMECMP_TRUNCATE_SOURCE
1153 : 0);
1155 if (0 <= utimecmp (dst_name, &dst_sb, &src_sb, options))
1157 /* We're using --update and the destination is not older
1158 than the source, so do not copy or move. Pretend the
1159 rename succeeded, so the caller (if it's mv) doesn't
1160 end up removing the source file. */
1161 if (rename_succeeded)
1162 *rename_succeeded = true;
1163 return true;
1168 if (x->move_mode)
1170 /* Don't allow user to move a directory onto a non-directory. */
1171 if (S_ISDIR (src_sb.st_mode) && !S_ISDIR (dst_sb.st_mode)
1172 && x->backup_type == no_backups)
1174 error (0, 0,
1175 _("cannot move directory onto non-directory: %s -> %s"),
1176 quote_n (0, src_name), quote_n (0, dst_name));
1177 return false;
1181 if (x->backup_type != no_backups
1182 /* Don't try to back up a destination if the last
1183 component of src_name is "." or "..". */
1184 && ! dot_or_dotdot (last_component (src_name)))
1186 char *tmp_backup = find_backup_file_name (dst_name,
1187 x->backup_type);
1189 /* Detect (and fail) when creating the backup file would
1190 destroy the source file. Before, running the commands
1191 cd /tmp; rm -f a a~; : > a; echo A > a~; cp --b=simple a~ a
1192 would leave two zero-length files: a and a~. */
1193 /* FIXME: but simply change e.g., the final a~ to `./a~'
1194 and the source will still be destroyed. */
1195 if (STREQ (tmp_backup, src_name))
1197 const char *fmt;
1198 fmt = (x->move_mode
1199 ? _("backing up %s would destroy source; %s not moved")
1200 : _("backing up %s would destroy source; %s not copied"));
1201 error (0, 0, fmt,
1202 quote_n (0, dst_name),
1203 quote_n (1, src_name));
1204 free (tmp_backup);
1205 return false;
1208 /* FIXME: use fts:
1209 Using alloca for a file name that may be arbitrarily
1210 long is not recommended. In fact, even forming such a name
1211 should be discouraged. Eventually, this code will be rewritten
1212 to use fts, so using alloca here will be less of a problem. */
1213 ASSIGN_STRDUPA (dst_backup, tmp_backup);
1214 free (tmp_backup);
1215 if (rename (dst_name, dst_backup) != 0)
1217 if (errno != ENOENT)
1219 error (0, errno, _("cannot backup %s"), quote (dst_name));
1220 return false;
1222 else
1224 dst_backup = NULL;
1227 else
1229 backup_succeeded = true;
1231 new_dst = true;
1233 else if (! S_ISDIR (dst_sb.st_mode)
1234 && (x->unlink_dest_before_opening
1235 || (x->preserve_links && 1 < dst_sb.st_nlink)
1236 || (!x->move_mode
1237 && x->dereference == DEREF_NEVER
1238 && S_ISLNK (src_sb.st_mode))
1241 if (unlink (dst_name) != 0 && errno != ENOENT)
1243 error (0, errno, _("cannot remove %s"), quote (dst_name));
1244 return false;
1246 new_dst = true;
1247 if (x->verbose)
1248 printf (_("removed %s\n"), quote (dst_name));
1253 /* If the source is a directory, we don't always create the destination
1254 directory. So --verbose should not announce anything until we're
1255 sure we'll create a directory. */
1256 if (x->verbose && !S_ISDIR (src_type))
1257 emit_verbose (src_name, dst_name, backup_succeeded ? dst_backup : NULL);
1259 /* Associate the destination file name with the source device and inode
1260 so that if we encounter a matching dev/ino pair in the source tree
1261 we can arrange to create a hard link between the corresponding names
1262 in the destination tree.
1264 Sometimes, when preserving links, we have to record dev/ino even
1265 though st_nlink == 1:
1266 - when in move_mode, since we may be moving a group of N hard-linked
1267 files (via two or more command line arguments) to a different
1268 partition; the links may be distributed among the command line
1269 arguments (possibly hierarchies) so that the link count of
1270 the final, once-linked source file is reduced to 1 when it is
1271 considered below. But in this case (for mv) we don't need to
1272 incur the expense of recording the dev/ino => name mapping; all we
1273 really need is a lookup, to see if the dev/ino pair has already
1274 been copied.
1275 - when using -H and processing a command line argument;
1276 that command line argument could be a symlink pointing to another
1277 command line argument. With `cp -H --preserve=link', we hard-link
1278 those two destination files.
1279 - likewise for -L except that it applies to all files, not just
1280 command line arguments.
1282 Also record directory dev/ino when using --recursive. We'll use that
1283 info to detect this problem: cp -R dir dir. FIXME-maybe: ideally,
1284 directory info would be recorded in a separate hash table, since
1285 such entries are useful only while a single command line hierarchy
1286 is being copied -- so that separate table could be cleared between
1287 command line args. Using the same hash table to preserve hard
1288 links means that it may not be cleared. */
1290 if (x->move_mode && src_sb.st_nlink == 1)
1292 earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev);
1294 else if ((x->preserve_links
1295 && (1 < src_sb.st_nlink
1296 || (command_line_arg
1297 && x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
1298 || x->dereference == DEREF_ALWAYS))
1299 || (x->recursive && S_ISDIR (src_type)))
1301 earlier_file = remember_copied (dst_name, src_sb.st_ino, src_sb.st_dev);
1304 /* Did we copy this inode somewhere else (in this command line argument)
1305 and therefore this is a second hard link to the inode? */
1307 if (earlier_file)
1309 /* Avoid damaging the destination file system by refusing to preserve
1310 hard-linked directories (which are found at least in Netapp snapshot
1311 directories). */
1312 if (S_ISDIR (src_type))
1314 /* If src_name and earlier_file refer to the same directory entry,
1315 then warn about copying a directory into itself. */
1316 if (same_name (src_name, earlier_file))
1318 error (0, 0, _("cannot copy a directory, %s, into itself, %s"),
1319 quote_n (0, top_level_src_name),
1320 quote_n (1, top_level_dst_name));
1321 *copy_into_self = true;
1322 goto un_backup;
1324 else if (x->dereference == DEREF_ALWAYS)
1326 /* This happens when e.g., encountering a directory for the
1327 second or subsequent time via symlinks when cp is invoked
1328 with -R and -L. E.g.,
1329 rm -rf a b c d; mkdir a b c d; ln -s ../c a; ln -s ../c b;
1330 cp -RL a b d
1333 else
1335 error (0, 0, _("will not create hard link %s to directory %s"),
1336 quote_n (0, dst_name), quote_n (1, earlier_file));
1337 goto un_backup;
1340 else
1342 bool link_failed = (link (earlier_file, dst_name) != 0);
1344 /* If the link failed because of an existing destination,
1345 remove that file and then call link again. */
1346 if (link_failed && errno == EEXIST)
1348 if (unlink (dst_name) != 0)
1350 error (0, errno, _("cannot remove %s"), quote (dst_name));
1351 goto un_backup;
1353 if (x->verbose)
1354 printf (_("removed %s\n"), quote (dst_name));
1355 link_failed = (link (earlier_file, dst_name) != 0);
1358 if (link_failed)
1360 error (0, errno, _("cannot create hard link %s to %s"),
1361 quote_n (0, dst_name), quote_n (1, earlier_file));
1362 goto un_backup;
1365 return true;
1369 if (x->move_mode)
1371 if (rename (src_name, dst_name) == 0)
1373 if (x->verbose && S_ISDIR (src_type))
1374 emit_verbose (src_name, dst_name,
1375 backup_succeeded ? dst_backup : NULL);
1377 if (rename_succeeded)
1378 *rename_succeeded = true;
1380 if (command_line_arg)
1382 /* Record destination dev/ino/name, so that if we are asked
1383 to overwrite that file again, we can detect it and fail. */
1384 /* It's fine to use the _source_ stat buffer (src_sb) to get the
1385 _destination_ dev/ino, since the rename above can't have
1386 changed those, and `mv' always uses lstat.
1387 We could limit it further by operating
1388 only on non-directories. */
1389 record_file (x->dest_info, dst_name, &src_sb);
1392 return true;
1395 /* FIXME: someday, consider what to do when moving a directory into
1396 itself but when source and destination are on different devices. */
1398 /* This happens when attempting to rename a directory to a
1399 subdirectory of itself. */
1400 if (errno == EINVAL)
1402 /* FIXME: this is a little fragile in that it relies on rename(2)
1403 failing with a specific errno value. Expect problems on
1404 non-POSIX systems. */
1405 error (0, 0, _("cannot move %s to a subdirectory of itself, %s"),
1406 quote_n (0, top_level_src_name),
1407 quote_n (1, top_level_dst_name));
1409 /* Note that there is no need to call forget_created here,
1410 (compare with the other calls in this file) since the
1411 destination directory didn't exist before. */
1413 *copy_into_self = true;
1414 /* FIXME-cleanup: Don't return true here; adjust mv.c accordingly.
1415 The only caller that uses this code (mv.c) ends up setting its
1416 exit status to nonzero when copy_into_self is nonzero. */
1417 return true;
1420 /* WARNING: there probably exist systems for which an inter-device
1421 rename fails with a value of errno not handled here.
1422 If/as those are reported, add them to the condition below.
1423 If this happens to you, please do the following and send the output
1424 to the bug-reporting address (e.g., in the output of cp --help):
1425 touch k; perl -e 'rename "k","/tmp/k" or print "$!(",$!+0,")\n"'
1426 where your current directory is on one partion and /tmp is the other.
1427 Also, please try to find the E* errno macro name corresponding to
1428 the diagnostic and parenthesized integer, and include that in your
1429 e-mail. One way to do that is to run a command like this
1430 find /usr/include/. -type f \
1431 | xargs grep 'define.*\<E[A-Z]*\>.*\<18\>' /dev/null
1432 where you'd replace `18' with the integer in parentheses that
1433 was output from the perl one-liner above.
1434 If necessary, of course, change `/tmp' to some other directory. */
1435 if (errno != EXDEV)
1437 /* There are many ways this can happen due to a race condition.
1438 When something happens between the initial XSTAT and the
1439 subsequent rename, we can get many different types of errors.
1440 For example, if the destination is initially a non-directory
1441 or non-existent, but it is created as a directory, the rename
1442 fails. If two `mv' commands try to rename the same file at
1443 about the same time, one will succeed and the other will fail.
1444 If the permissions on the directory containing the source or
1445 destination file are made too restrictive, the rename will
1446 fail. Etc. */
1447 error (0, errno,
1448 _("cannot move %s to %s"),
1449 quote_n (0, src_name), quote_n (1, dst_name));
1450 forget_created (src_sb.st_ino, src_sb.st_dev);
1451 return false;
1454 /* The rename attempt has failed. Remove any existing destination
1455 file so that a cross-device `mv' acts as if it were really using
1456 the rename syscall. */
1457 if (unlink (dst_name) != 0 && errno != ENOENT)
1459 error (0, errno,
1460 _("inter-device move failed: %s to %s; unable to remove target"),
1461 quote_n (0, src_name), quote_n (1, dst_name));
1462 forget_created (src_sb.st_ino, src_sb.st_dev);
1463 return false;
1466 new_dst = true;
1469 delayed_ok = true;
1471 /* In certain modes (cp's --symbolic-link), and for certain file types
1472 (symlinks and hard links) it doesn't make sense to preserve metadata,
1473 or it's possible to preserve only some of it.
1474 In such cases, set this variable to zero. */
1475 preserve_metadata = true;
1477 if (S_ISDIR (src_type))
1479 struct dir_list *dir;
1481 /* If this directory has been copied before during the
1482 recursion, there is a symbolic link to an ancestor
1483 directory of the symbolic link. It is impossible to
1484 continue to copy this, unless we've got an infinite disk. */
1486 if (is_ancestor (&src_sb, ancestors))
1488 error (0, 0, _("cannot copy cyclic symbolic link %s"),
1489 quote (src_name));
1490 goto un_backup;
1493 /* Insert the current directory in the list of parents. */
1495 dir = alloca (sizeof *dir);
1496 dir->parent = ancestors;
1497 dir->ino = src_sb.st_ino;
1498 dir->dev = src_sb.st_dev;
1500 if (new_dst || !S_ISDIR (dst_sb.st_mode))
1502 if (mkdir (dst_name, src_mode) != 0)
1504 error (0, errno, _("cannot create directory %s"),
1505 quote (dst_name));
1506 goto un_backup;
1509 /* We need search and write permissions to the new directory
1510 for writing the directory's contents. Check if these
1511 permissions are there. */
1513 if (lstat (dst_name, &dst_sb) != 0)
1515 error (0, errno, _("cannot stat %s"), quote (dst_name));
1516 goto un_backup;
1518 else if ((dst_sb.st_mode & S_IRWXU) != S_IRWXU)
1520 /* Make the new directory searchable and writable. */
1522 dst_mode = dst_sb.st_mode;
1523 restore_dst_mode = true;
1525 if (lchmod (dst_name, dst_mode | S_IRWXU) != 0)
1527 error (0, errno, _("setting permissions for %s"),
1528 quote (dst_name));
1529 goto un_backup;
1533 /* Insert the created directory's inode and device
1534 numbers into the search structure, so that we can
1535 avoid copying it again. */
1537 remember_copied (dst_name, dst_sb.st_ino, dst_sb.st_dev);
1539 if (x->verbose)
1540 emit_verbose (src_name, dst_name, NULL);
1543 /* Are we crossing a file system boundary? */
1544 if (x->one_file_system && device != 0 && device != src_sb.st_dev)
1545 return true;
1547 /* Copy the contents of the directory. */
1549 if (! copy_dir (src_name, dst_name, new_dst, &src_sb, dir, x,
1550 copy_into_self))
1552 /* Don't just return here -- otherwise, the failure to read a
1553 single file in a source directory would cause the containing
1554 destination directory not to have owner/perms set properly. */
1555 delayed_ok = false;
1558 else if (x->symbolic_link)
1560 preserve_metadata = false;
1562 if (*src_name != '/')
1564 /* Check that DST_NAME denotes a file in the current directory. */
1565 struct stat dot_sb;
1566 struct stat dst_parent_sb;
1567 char *dst_parent;
1568 bool in_current_dir;
1570 dst_parent = dir_name (dst_name);
1572 in_current_dir = (STREQ (".", dst_parent)
1573 /* If either stat call fails, it's ok not to report
1574 the failure and say dst_name is in the current
1575 directory. Other things will fail later. */
1576 || stat (".", &dot_sb)
1577 || stat (dst_parent, &dst_parent_sb)
1578 || SAME_INODE (dot_sb, dst_parent_sb));
1579 free (dst_parent);
1581 if (! in_current_dir)
1583 error (0, 0,
1584 _("%s: can make relative symbolic links only in current directory"),
1585 quote (dst_name));
1586 goto un_backup;
1589 if (symlink (src_name, dst_name) != 0)
1591 error (0, errno, _("cannot create symbolic link %s to %s"),
1592 quote_n (0, dst_name), quote_n (1, src_name));
1593 goto un_backup;
1597 else if (x->hard_link
1598 #ifdef LINK_FOLLOWS_SYMLINKS
1599 /* A POSIX-conforming link syscall dereferences a symlink, yet cp,
1600 invoked with `--link --no-dereference', should not. Thus, with
1601 a POSIX-conforming link system call, we can't use link() here,
1602 since that would create a hard link to the referent (effectively
1603 dereferencing the symlink), rather than to the symlink itself.
1604 We can approximate the desired behavior by skipping this hard-link
1605 creating block and instead copying the symlink, via the `S_ISLNK'-
1606 copying code below.
1607 When link operates on the symlinks themselves, we use this block
1608 and just call link(). */
1609 && !(S_ISLNK (src_mode) && x->dereference == DEREF_NEVER)
1610 #endif
1613 preserve_metadata = false;
1614 if (link (src_name, dst_name))
1616 error (0, errno, _("cannot create link %s"), quote (dst_name));
1617 goto un_backup;
1620 else if (S_ISREG (src_type)
1621 || (x->copy_as_regular && !S_ISLNK (src_type)))
1623 copied_as_regular = true;
1624 /* POSIX says the permission bits of the source file must be
1625 used as the 3rd argument in the open call, but that's not consistent
1626 with historical practice. */
1627 if (! copy_reg (src_name, dst_name, x, src_mode, &new_dst, &src_sb))
1628 goto un_backup;
1630 else if (S_ISFIFO (src_type))
1632 if (mkfifo (dst_name, src_mode))
1634 error (0, errno, _("cannot create fifo %s"), quote (dst_name));
1635 goto un_backup;
1638 else if (S_ISBLK (src_type) || S_ISCHR (src_type) || S_ISSOCK (src_type))
1640 if (mknod (dst_name, src_mode, src_sb.st_rdev))
1642 error (0, errno, _("cannot create special file %s"),
1643 quote (dst_name));
1644 goto un_backup;
1647 else if (S_ISLNK (src_type))
1649 char *src_link_val = xreadlink (src_name, src_sb.st_size);
1650 if (src_link_val == NULL)
1652 error (0, errno, _("cannot read symbolic link %s"), quote (src_name));
1653 goto un_backup;
1656 if (symlink (src_link_val, dst_name) == 0)
1657 free (src_link_val);
1658 else
1660 int saved_errno = errno;
1661 bool same_link = false;
1662 if (x->update && !new_dst && S_ISLNK (dst_sb.st_mode)
1663 && dst_sb.st_size == strlen (src_link_val))
1665 /* See if the destination is already the desired symlink.
1666 FIXME: This behavior isn't documented, and seems wrong
1667 in some cases, e.g., if the destination symlink has the
1668 wrong ownership, permissions, or time stamps. */
1669 char *dest_link_val = xreadlink (dst_name, dst_sb.st_size);
1670 if (STREQ (dest_link_val, src_link_val))
1671 same_link = true;
1672 free (dest_link_val);
1674 free (src_link_val);
1676 if (! same_link)
1678 error (0, saved_errno, _("cannot create symbolic link %s"),
1679 quote (dst_name));
1680 goto un_backup;
1684 /* There's no need to preserve timestamps or permissions. */
1685 preserve_metadata = false;
1687 if (x->preserve_ownership)
1689 /* Preserve the owner and group of the just-`copied'
1690 symbolic link, if possible. */
1691 #if HAVE_LCHOWN
1692 if (lchown (dst_name, src_sb.st_uid, src_sb.st_gid) != 0
1693 && ! chown_failure_ok (x))
1695 error (0, errno, _("failed to preserve ownership for %s"),
1696 dst_name);
1697 goto un_backup;
1699 #else
1700 /* Can't preserve ownership of symlinks.
1701 FIXME: maybe give a warning or even error for symlinks
1702 in directories with the sticky bit set -- there, not
1703 preserving owner/group is a potential security problem. */
1704 #endif
1707 else
1709 error (0, 0, _("%s has unknown file type"), quote (src_name));
1710 goto un_backup;
1713 if (command_line_arg)
1714 record_file (x->dest_info, dst_name, NULL);
1716 if ( ! preserve_metadata)
1717 return true;
1719 if (copied_as_regular)
1720 return delayed_ok;
1722 /* POSIX says that `cp -p' must restore the following:
1723 - permission bits
1724 - setuid, setgid bits
1725 - owner and group
1726 If it fails to restore any of those, we may give a warning but
1727 the destination must not be removed.
1728 FIXME: implement the above. */
1730 /* Adjust the times (and if possible, ownership) for the copy.
1731 chown turns off set[ug]id bits for non-root,
1732 so do the chmod last. */
1734 if (x->preserve_timestamps)
1736 struct timespec timespec[2];
1737 timespec[0] = get_stat_atime (&src_sb);
1738 timespec[1] = get_stat_mtime (&src_sb);
1740 if (utimens (dst_name, timespec) != 0)
1742 error (0, errno, _("preserving times for %s"), quote (dst_name));
1743 if (x->require_preserve)
1744 return false;
1748 /* Avoid calling chown if we know it's not necessary. */
1749 if (x->preserve_ownership
1750 && (new_dst || !SAME_OWNER_AND_GROUP (src_sb, dst_sb)))
1752 if (! set_owner (x, dst_name, -1, src_sb.st_uid, src_sb.st_gid))
1753 return false;
1756 set_author (dst_name, -1, &src_sb);
1758 if (x->preserve_mode || x->move_mode)
1760 if (copy_acl (src_name, -1, dst_name, -1, src_mode) != 0
1761 && x->require_preserve)
1762 return false;
1764 else if (x->set_mode)
1766 if (set_acl (dst_name, -1, x->mode) != 0)
1767 return false;
1769 else if (restore_dst_mode)
1771 if (lchmod (dst_name, dst_mode) != 0)
1773 error (0, errno, _("preserving permissions for %s"),
1774 quote (dst_name));
1775 if (x->require_preserve)
1776 return false;
1780 return delayed_ok;
1782 un_backup:
1784 /* We have failed to create the destination file.
1785 If we've just added a dev/ino entry via the remember_copied
1786 call above (i.e., unless we've just failed to create a hard link),
1787 remove the entry associating the source dev/ino with the
1788 destination file name, so we don't try to `preserve' a link
1789 to a file we didn't create. */
1790 if (earlier_file == NULL)
1791 forget_created (src_sb.st_ino, src_sb.st_dev);
1793 if (dst_backup)
1795 if (rename (dst_backup, dst_name) != 0)
1796 error (0, errno, _("cannot un-backup %s"), quote (dst_name));
1797 else
1799 if (x->verbose)
1800 printf (_("%s -> %s (unbackup)\n"),
1801 quote_n (0, dst_backup), quote_n (1, dst_name));
1804 return false;
1807 static bool
1808 valid_options (const struct cp_options *co)
1810 assert (co != NULL);
1811 assert (VALID_BACKUP_TYPE (co->backup_type));
1812 assert (VALID_SPARSE_MODE (co->sparse_mode));
1813 assert (!(co->hard_link && co->symbolic_link));
1814 return true;
1817 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
1818 any type. NONEXISTENT_DST should be true if the file DST_NAME
1819 is known not to exist (e.g., because its parent directory was just
1820 created); NONEXISTENT_DST should be false if DST_NAME might already
1821 exist. OPTIONS is ... FIXME-describe
1822 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
1823 same as) DST_NAME; otherwise, set clear it.
1824 Return true if successful. */
1826 extern bool
1827 copy (char const *src_name, char const *dst_name,
1828 bool nonexistent_dst, const struct cp_options *options,
1829 bool *copy_into_self, bool *rename_succeeded)
1831 assert (valid_options (options));
1833 /* Record the file names: they're used in case of error, when copying
1834 a directory into itself. I don't like to make these tools do *any*
1835 extra work in the common case when that work is solely to handle
1836 exceptional cases, but in this case, I don't see a way to derive the
1837 top level source and destination directory names where they're used.
1838 An alternative is to use COPY_INTO_SELF and print the diagnostic
1839 from every caller -- but I don't want to do that. */
1840 top_level_src_name = src_name;
1841 top_level_dst_name = dst_name;
1843 return copy_internal (src_name, dst_name, nonexistent_dst, 0, NULL,
1844 options, true, copy_into_self, rename_succeeded);
1847 /* Return true if this process has appropriate privileges to chown a
1848 file whose owner is not the effective user ID. */
1850 extern bool
1851 chown_privileges (void)
1853 #ifdef PRIV_FILE_CHOWN
1854 bool result;
1855 priv_set_t *pset = priv_allocset ();
1856 if (!pset)
1857 xalloc_die ();
1858 result = (getppriv (PRIV_EFFECTIVE, pset) == 0
1859 && priv_ismember (pset, PRIV_FILE_CHOWN));
1860 priv_freeset (pset);
1861 return result;
1862 #else
1863 return (geteuid () == 0);
1864 #endif
1867 /* Return true if it's OK for chown to fail, where errno is
1868 the error number that chown failed with and X is the copying
1869 option set. */
1871 extern bool
1872 chown_failure_ok (struct cp_options const *x)
1874 /* If non-root uses -p, it's ok if we can't preserve ownership.
1875 But root probably wants to know, e.g. if NFS disallows it,
1876 or if the target system doesn't support file ownership. */
1878 return ((errno == EPERM || errno == EINVAL) && !x->chown_privileges);