*** empty log message ***
[platform/upstream/coreutils.git] / src / copy.c
1 /* copy.c -- core functions for copying files and directories
2    Copyright (C) 89, 90, 91, 1995-2006 Free Software Foundation.
3
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.
8
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.
13
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.  */
17
18 /* Extracted from cp.c and librarified by Jim Meyering.  */
19
20 #include <config.h>
21 #include <stdio.h>
22 #include <assert.h>
23 #include <sys/types.h>
24
25 #if HAVE_HURD_H
26 # include <hurd.h>
27 #endif
28 #if HAVE_PRIV_H
29 # include <priv.h>
30 #endif
31
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 "dirname.h"
39 #include "euidaccess.h"
40 #include "error.h"
41 #include "fcntl--.h"
42 #include "filenamecat.h"
43 #include "full-write.h"
44 #include "getpagesize.h"
45 #include "hash.h"
46 #include "hash-pjw.h"
47 #include "lchmod.h"
48 #include "quote.h"
49 #include "same.h"
50 #include "savedir.h"
51 #include "stat-time.h"
52 #include "utimecmp.h"
53 #include "utimens.h"
54 #include "xreadlink.h"
55 #include "yesno.h"
56
57 #ifndef HAVE_FCHOWN
58 # define HAVE_FCHOWN false
59 # define fchown(fd, uid, gid) (-1)
60 #endif
61
62 #define SAME_OWNER(A, B) ((A).st_uid == (B).st_uid)
63 #define SAME_GROUP(A, B) ((A).st_gid == (B).st_gid)
64 #define SAME_OWNER_AND_GROUP(A, B) (SAME_OWNER (A, B) && SAME_GROUP (A, B))
65
66 #define UNWRITABLE(File_name, File_mode)                \
67   ( /* euidaccess is not meaningful for symlinks */     \
68     ! S_ISLNK (File_mode)                               \
69     && euidaccess (File_name, W_OK) != 0)
70
71 struct dir_list
72 {
73   struct dir_list *parent;
74   ino_t ino;
75   dev_t dev;
76 };
77
78 /* Describe a just-created or just-renamed destination file.  */
79 struct F_triple
80 {
81   char *name;
82   ino_t st_ino;
83   dev_t st_dev;
84 };
85
86 /* Initial size of the above hash table.  */
87 #define DEST_INFO_INITIAL_CAPACITY 61
88
89 static bool copy_internal (char const *src_name, char const *dst_name,
90                            bool new_dst, dev_t device,
91                            struct dir_list *ancestors,
92                            const struct cp_options *x,
93                            bool command_line_arg,
94                            bool *copy_into_self,
95                            bool *rename_succeeded);
96
97 /* Pointers to the file names:  they're used in the diagnostic that is issued
98    when we detect the user is trying to copy a directory into itself.  */
99 static char const *top_level_src_name;
100 static char const *top_level_dst_name;
101
102 /* The invocation name of this program.  */
103 extern char *program_name;
104
105 /* FIXME: describe */
106 /* FIXME: rewrite this to use a hash table so we avoid the quadratic
107    performance hit that's probably noticeable only on trees deeper
108    than a few hundred levels.  See use of active_dir_map in remove.c  */
109
110 static bool
111 is_ancestor (const struct stat *sb, const struct dir_list *ancestors)
112 {
113   while (ancestors != 0)
114     {
115       if (ancestors->ino == sb->st_ino && ancestors->dev == sb->st_dev)
116         return true;
117       ancestors = ancestors->parent;
118     }
119   return false;
120 }
121
122 /* Read the contents of the directory SRC_NAME_IN, and recursively
123    copy the contents to DST_NAME_IN.  NEW_DST is true if
124    DST_NAME_IN is a directory that was created previously in the
125    recursion.   SRC_SB and ANCESTORS describe SRC_NAME_IN.
126    Set *COPY_INTO_SELF if SRC_NAME_IN is a parent of
127    (or the same as) DST_NAME_IN; otherwise, clear it.
128    Return true if successful.  */
129
130 static bool
131 copy_dir (char const *src_name_in, char const *dst_name_in, bool new_dst,
132           const struct stat *src_sb, struct dir_list *ancestors,
133           const struct cp_options *x, bool *copy_into_self)
134 {
135   char *name_space;
136   char *namep;
137   struct cp_options non_command_line_options = *x;
138   bool ok = true;
139
140   name_space = savedir (src_name_in);
141   if (name_space == NULL)
142     {
143       /* This diagnostic is a bit vague because savedir can fail in
144          several different ways.  */
145       error (0, errno, _("cannot access %s"), quote (src_name_in));
146       return false;
147     }
148
149   /* For cp's -H option, dereference command line arguments, but do not
150      dereference symlinks that are found via recursive traversal.  */
151   if (x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
152     non_command_line_options.dereference = DEREF_NEVER;
153
154   namep = name_space;
155   while (*namep != '\0')
156     {
157       bool local_copy_into_self;
158       char *src_name = file_name_concat (src_name_in, namep, NULL);
159       char *dst_name = file_name_concat (dst_name_in, namep, NULL);
160
161       ok &= copy_internal (src_name, dst_name, new_dst, src_sb->st_dev,
162                            ancestors, &non_command_line_options, false,
163                            &local_copy_into_self, NULL);
164       *copy_into_self |= local_copy_into_self;
165
166       free (dst_name);
167       free (src_name);
168
169       namep += strlen (namep) + 1;
170     }
171   free (name_space);
172   return ok;
173 }
174
175 /* Set the owner and owning group of DEST_DESC to the st_uid and
176    st_gid fields of SRC_SB.  If DEST_DESC is undefined (-1), set
177    the owner and owning group of DST_NAME instead.  DEST_DESC must
178    refer to the same file as DEST_NAME if defined.
179    Return true if the syscall succeeds, or if it's ok not to
180    preserve ownership.  */
181
182 static bool
183 set_owner (const struct cp_options *x, char const *dst_name, int dest_desc,
184            uid_t uid, gid_t gid)
185 {
186   if (HAVE_FCHOWN && dest_desc != -1)
187     {
188       if (fchown (dest_desc, uid, gid) == 0)
189         return true;
190     }
191   else
192     {
193       if (chown (dst_name, uid, gid) == 0)
194         return true;
195     }
196
197   if (! chown_failure_ok (x))
198     {
199       error (0, errno, _("failed to preserve ownership for %s"),
200              quote (dst_name));
201       if (x->require_preserve)
202         return false;
203     }
204
205   return true;
206 }
207
208 /* Set the st_author field of DEST_DESC to the st_author field of
209    SRC_SB. If DEST_DESC is undefined (-1), set the st_author field
210    of DST_NAME instead.  DEST_DESC must refer to the same file as
211    DEST_NAME if defined.  */
212
213 static void
214 set_author (const char *dst_name, int dest_desc, const struct stat *src_sb)
215 {
216   /* FIXME: Preserve the st_author field via the file descriptor dest_desc.  */
217 #if HAVE_STRUCT_STAT_ST_AUTHOR
218   /* Preserve the st_author field.  */
219   file_t file = file_name_lookup (dst_name, 0, 0);
220   if (file == MACH_PORT_NULL)
221     error (0, errno, _("failed to lookup file %s"), quote (dst_name));
222   else
223     {
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);
229     }
230 #endif
231 }
232
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.  */
242
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)
247 {
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;
255
256   source_desc = open (src_name, O_RDONLY | O_BINARY);
257   if (source_desc < 0)
258     {
259       error (0, errno, _("cannot open %s for reading"), quote (src_name));
260       return false;
261     }
262
263   if (fstat (source_desc, &src_open_sb))
264     {
265       error (0, errno, _("cannot fstat %s"), quote (src_name));
266       return_val = false;
267       goto close_src_desc;
268     }
269
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))
273     {
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;
279     }
280
281   /* These semantics are required for cp.
282      The if-block will be taken in move_mode.  */
283   if (*new_dst)
284     {
285       dest_desc = open (dst_name, O_WRONLY | O_CREAT | O_BINARY, dst_mode);
286     }
287   else
288     {
289       dest_desc = open (dst_name, O_WRONLY | O_TRUNC | O_BINARY, dst_mode);
290
291       if (dest_desc < 0 && x->unlink_dest_after_failed_open)
292         {
293           if (unlink (dst_name) != 0)
294             {
295               error (0, errno, _("cannot remove %s"), quote (dst_name));
296               return_val = false;
297               goto close_src_desc;
298             }
299
300           /* Tell caller that the destination file was unlinked.  */
301           *new_dst = true;
302
303           /* Try the open again, but this time with different flags.  */
304           dest_desc = open (dst_name, O_WRONLY | O_CREAT | O_BINARY, dst_mode);
305         }
306     }
307
308   if (dest_desc < 0)
309     {
310       error (0, errno, _("cannot create regular file %s"), quote (dst_name));
311       return_val = false;
312       goto close_src_desc;
313     }
314
315   if (fstat (dest_desc, &sb))
316     {
317       error (0, errno, _("cannot fstat %s"), quote (dst_name));
318       return_val = false;
319       goto close_src_and_dst_desc;
320     }
321
322   if (! (S_ISREG (src_open_sb.st_mode) && src_open_sb.st_size == 0))
323     {
324       typedef uintptr_t word;
325       off_t n_read_total = 0;
326
327       /* Choose a suitable buffer size; it may be adjusted later.  */
328       size_t buf_alignment = lcm (getpagesize (), sizeof (word));
329       size_t buf_alignment_slop = sizeof (word) + buf_alignment - 1;
330       size_t buf_size = ST_BLKSIZE (sb);
331
332       /* Deal with sparse files.  */
333       bool last_write_made_hole = false;
334       bool make_holes = false;
335
336       if (S_ISREG (sb.st_mode))
337         {
338           /* Even with --sparse=always, try to create holes only
339              if the destination is a regular file.  */
340           if (x->sparse_mode == SPARSE_ALWAYS)
341             make_holes = true;
342
343 #if HAVE_STRUCT_STAT_ST_BLOCKS
344           /* Use a heuristic to determine whether SRC_NAME contains any sparse
345              blocks.  If the file has fewer blocks than would normally be
346              needed for a file of its size, then at least one of the blocks in
347              the file is a hole.  */
348           if (x->sparse_mode == SPARSE_AUTO && S_ISREG (src_open_sb.st_mode)
349               && ST_NBLOCKS (src_open_sb) < src_open_sb.st_size / ST_NBLOCKSIZE)
350             make_holes = true;
351 #endif
352         }
353
354       /* If not making a sparse file, try to use a more-efficient
355          buffer size.  */
356       if (! make_holes)
357         {
358           /* These days there's no point ever messing with buffers smaller
359              than 8 KiB.  It would be nice to configure SMALL_BUF_SIZE
360              dynamically for this host and pair of files, but there doesn't
361              seem to be a good way to get readahead info portably.  */
362           enum { SMALL_BUF_SIZE = 8 * 1024 };
363
364           /* Compute the least common multiple of the input and output
365              buffer sizes, adjusting for outlandish values.  */
366           size_t blcm_max = MIN (SIZE_MAX, SSIZE_MAX) - buf_alignment_slop;
367           size_t blcm = buffer_lcm (ST_BLKSIZE (src_open_sb), buf_size,
368                                     blcm_max);
369
370           /* Do not use a block size that is too small.  */
371           buf_size = MAX (SMALL_BUF_SIZE, blcm);
372
373           /* Do not bother with a buffer larger than the input file, plus one
374              byte to make sure the file has not grown while reading it.  */
375           if (S_ISREG (src_open_sb.st_mode) && src_open_sb.st_size < buf_size)
376             buf_size = src_open_sb.st_size + 1;
377
378           /* However, stick with a block size that is a positive multiple of
379              blcm, overriding the above adjustments.  Watch out for
380              overflow.  */
381           buf_size += blcm - 1;
382           buf_size -= buf_size % blcm;
383           if (buf_size == 0 || blcm_max < buf_size)
384             buf_size = blcm;
385         }
386
387       /* Make a buffer with space for a sentinel at the end.  */
388       buf_alloc = xmalloc (buf_size + buf_alignment_slop);
389       buf = ptr_align (buf_alloc, buf_alignment);
390
391       for (;;)
392         {
393           word *wp = NULL;
394
395           ssize_t n_read = read (source_desc, buf, buf_size);
396           if (n_read < 0)
397             {
398 #ifdef EINTR
399               if (errno == EINTR)
400                 continue;
401 #endif
402               error (0, errno, _("reading %s"), quote (src_name));
403               return_val = false;
404               goto close_src_and_dst_desc;
405             }
406           if (n_read == 0)
407             break;
408
409           n_read_total += n_read;
410
411           if (make_holes)
412             {
413               char *cp;
414
415               buf[n_read] = 1;  /* Sentinel to stop loop.  */
416
417               /* Find first nonzero *word*, or the word with the sentinel.  */
418
419               wp = (word *) buf;
420               while (*wp++ == 0)
421                 continue;
422
423               /* Find the first nonzero *byte*, or the sentinel.  */
424
425               cp = (char *) (wp - 1);
426               while (*cp++ == 0)
427                 continue;
428
429               if (cp <= buf + n_read)
430                 /* Clear to indicate that a normal write is needed. */
431                 wp = NULL;
432               else
433                 {
434                   /* We found the sentinel, so the whole input block was zero.
435                      Make a hole.  */
436                   if (lseek (dest_desc, n_read, SEEK_CUR) < 0)
437                     {
438                       error (0, errno, _("cannot lseek %s"), quote (dst_name));
439                       return_val = false;
440                       goto close_src_and_dst_desc;
441                     }
442                   last_write_made_hole = true;
443                 }
444             }
445
446           if (!wp)
447             {
448               size_t n = n_read;
449               if (full_write (dest_desc, buf, n) != n)
450                 {
451                   error (0, errno, _("writing %s"), quote (dst_name));
452                   return_val = false;
453                   goto close_src_and_dst_desc;
454                 }
455               last_write_made_hole = false;
456
457               /* A short read on a regular file means EOF.  */
458               if (n_read != buf_size && S_ISREG (src_open_sb.st_mode))
459                 break;
460             }
461         }
462
463       /* If the file ends with a `hole', something needs to be written at
464          the end.  Otherwise the kernel would truncate the file at the end
465          of the last write operation.  */
466
467       if (last_write_made_hole)
468         {
469 #if HAVE_FTRUNCATE
470           /* Write a null character and truncate it again.  */
471           if (full_write (dest_desc, "", 1) != 1
472               || ftruncate (dest_desc, n_read_total) < 0)
473 #else
474           /* Seek backwards one character and write a null.  */
475           if (lseek (dest_desc, (off_t) -1, SEEK_CUR) < 0L
476               || full_write (dest_desc, "", 1) != 1)
477 #endif
478             {
479               error (0, errno, _("writing %s"), quote (dst_name));
480               return_val = false;
481               goto close_src_and_dst_desc;
482             }
483         }
484     }
485
486   if (x->preserve_timestamps)
487     {
488       struct timespec timespec[2];
489       timespec[0] = get_stat_atime (src_sb);
490       timespec[1] = get_stat_mtime (src_sb);
491
492       if (futimens (dest_desc, dst_name, timespec) != 0)
493         {
494           error (0, errno, _("preserving times for %s"), quote (dst_name));
495           if (x->require_preserve)
496             {
497               return_val = false;
498               goto close_src_and_dst_desc;
499             }
500         }
501     }
502
503   if (x->preserve_ownership && ! SAME_OWNER_AND_GROUP (*src_sb, sb))
504     {
505       if (! set_owner (x, dst_name, dest_desc, src_sb->st_uid, src_sb->st_gid))
506         {
507           return_val = false;
508           goto close_src_and_dst_desc;
509         }
510     }
511
512   set_author (dst_name, dest_desc, src_sb);
513
514   if (x->preserve_mode || x->move_mode)
515     {
516       if (copy_acl (src_name, source_desc, dst_name, dest_desc,
517                     src_sb->st_mode) != 0 && x->require_preserve)
518         return_val = false;
519     }
520   else if (x->set_mode)
521     {
522       if (set_acl (dst_name, dest_desc, x->mode) != 0)
523         return_val = false;
524     }
525
526 close_src_and_dst_desc:
527   if (close (dest_desc) < 0)
528     {
529       error (0, errno, _("closing %s"), quote (dst_name));
530       return_val = false;
531     }
532 close_src_desc:
533   if (close (source_desc) < 0)
534     {
535       error (0, errno, _("closing %s"), quote (src_name));
536       return_val = false;
537     }
538
539   free (buf_alloc);
540   return return_val;
541 }
542
543 /* Return true if it's ok that the source and destination
544    files are the `same' by some measure.  The goal is to avoid
545    making the `copy' operation remove both copies of the file
546    in that case, while still allowing the user to e.g., move or
547    copy a regular file onto a symlink that points to it.
548    Try to minimize the cost of this function in the common case.
549    Set *RETURN_NOW if we've determined that the caller has no more
550    work to do and should return successfully, right away.
551
552    Set *UNLINK_SRC if we've determined that the caller wants to do
553    `rename (a, b)' where `a' and `b' are distinct hard links to the same
554    file. In that case, the caller should try to unlink `a' and then return
555    successfully.  Ideally, we wouldn't have to do that, and we'd be
556    able to rely on rename to remove the source file.  However, POSIX
557    mistakenly requires that such a rename call do *nothing* and return
558    successfully.  */
559
560 static bool
561 same_file_ok (char const *src_name, struct stat const *src_sb,
562               char const *dst_name, struct stat const *dst_sb,
563               const struct cp_options *x, bool *return_now, bool *unlink_src)
564 {
565   const struct stat *src_sb_link;
566   const struct stat *dst_sb_link;
567   struct stat tmp_dst_sb;
568   struct stat tmp_src_sb;
569
570   bool same_link;
571   bool same = SAME_INODE (*src_sb, *dst_sb);
572
573   *return_now = false;
574   *unlink_src = false;
575
576   /* FIXME: this should (at the very least) be moved into the following
577      if-block.  More likely, it should be removed, because it inhibits
578      making backups.  But removing it will result in a change in behavior
579      that will probably have to be documented -- and tests will have to
580      be updated.  */
581   if (same && x->hard_link)
582     {
583       *return_now = true;
584       return true;
585     }
586
587   if (x->dereference == DEREF_NEVER)
588     {
589       same_link = same;
590
591       /* If both the source and destination files are symlinks (and we'll
592          know this here IFF preserving symlinks (aka xstat == lstat),
593          then it's ok -- as long as they are distinct.  */
594       if (S_ISLNK (src_sb->st_mode) && S_ISLNK (dst_sb->st_mode))
595         return ! same_name (src_name, dst_name);
596
597       src_sb_link = src_sb;
598       dst_sb_link = dst_sb;
599     }
600   else
601     {
602       if (!same)
603         return true;
604
605       if (lstat (dst_name, &tmp_dst_sb) != 0
606           || lstat (src_name, &tmp_src_sb) != 0)
607         return true;
608
609       src_sb_link = &tmp_src_sb;
610       dst_sb_link = &tmp_dst_sb;
611
612       same_link = SAME_INODE (*src_sb_link, *dst_sb_link);
613
614       /* If both are symlinks, then it's ok, but only if the destination
615          will be unlinked before being opened.  This is like the test
616          above, but with the addition of the unlink_dest_before_opening
617          conjunct because otherwise, with two symlinks to the same target,
618          we'd end up truncating the source file.  */
619       if (S_ISLNK (src_sb_link->st_mode) && S_ISLNK (dst_sb_link->st_mode)
620           && x->unlink_dest_before_opening)
621         return true;
622     }
623
624   /* The backup code ensures there's a copy, so it's usually ok to
625      remove any destination file.  One exception is when both
626      source and destination are the same directory entry.  In that
627      case, moving the destination file aside (in making the backup)
628      would also rename the source file and result in an error.  */
629   if (x->backup_type != no_backups)
630     {
631       if (!same_link)
632         {
633           /* In copy mode when dereferencing symlinks, if the source is a
634              symlink and the dest is not, then backing up the destination
635              (moving it aside) would make it a dangling symlink, and the
636              subsequent attempt to open it in copy_reg would fail with
637              a misleading diagnostic.  Avoid that by returning zero in
638              that case so the caller can make cp (or mv when it has to
639              resort to reading the source file) fail now.  */
640
641           /* FIXME-note: even with the following kludge, we can still provoke
642              the offending diagnostic.  It's just a little harder to do :-)
643              $ rm -f a b c; touch c; ln -s c b; ln -s b a; cp -b a b
644              cp: cannot open `a' for reading: No such file or directory
645              That's misleading, since a subsequent `ls' shows that `a'
646              is still there.
647              One solution would be to open the source file *before* moving
648              aside the destination, but that'd involve a big rewrite. */
649           if ( ! x->move_mode
650                && x->dereference != DEREF_NEVER
651                && S_ISLNK (src_sb_link->st_mode)
652                && ! S_ISLNK (dst_sb_link->st_mode))
653             return false;
654
655           return true;
656         }
657
658       return ! same_name (src_name, dst_name);
659     }
660
661 #if 0
662   /* FIXME: use or remove */
663
664   /* If we're making a backup, we'll detect the problem case in
665      copy_reg because SRC_NAME will no longer exist.  Allowing
666      the test to be deferred lets cp do some useful things.
667      But when creating hardlinks and SRC_NAME is a symlink
668      but DST_NAME is not we must test anyway.  */
669   if (x->hard_link
670       || !S_ISLNK (src_sb_link->st_mode)
671       || S_ISLNK (dst_sb_link->st_mode))
672     return true;
673
674   if (x->dereference != DEREF_NEVER)
675     return true;
676 #endif
677
678   /* They may refer to the same file if we're in move mode and the
679      target is a symlink.  That is ok, since we remove any existing
680      destination file before opening it -- via `rename' if they're on
681      the same file system, via `unlink (DST_NAME)' otherwise.
682      It's also ok if they're distinct hard links to the same file.  */
683   if (x->move_mode || x->unlink_dest_before_opening)
684     {
685       if (S_ISLNK (dst_sb_link->st_mode))
686         return true;
687
688       if (same_link
689           && 1 < dst_sb_link->st_nlink
690           && ! same_name (src_name, dst_name))
691         {
692           if (x->move_mode)
693             {
694               *unlink_src = true;
695               *return_now = true;
696             }
697           return true;
698         }
699     }
700
701   /* If neither is a symlink, then it's ok as long as they aren't
702      hard links to the same file.  */
703   if (!S_ISLNK (src_sb_link->st_mode) && !S_ISLNK (dst_sb_link->st_mode))
704     {
705       if (!SAME_INODE (*src_sb_link, *dst_sb_link))
706         return true;
707
708       /* If they are the same file, it's ok if we're making hard links.  */
709       if (x->hard_link)
710         {
711           *return_now = true;
712           return true;
713         }
714     }
715
716   /* It's ok to remove a destination symlink.  But that works only when we
717      unlink before opening the destination and when the source and destination
718      files are on the same partition.  */
719   if (x->unlink_dest_before_opening
720       && S_ISLNK (dst_sb_link->st_mode))
721     return dst_sb_link->st_dev == src_sb_link->st_dev;
722
723   if (x->dereference == DEREF_NEVER)
724     {
725       if ( ! S_ISLNK (src_sb_link->st_mode))
726         tmp_src_sb = *src_sb_link;
727       else if (stat (src_name, &tmp_src_sb) != 0)
728         return true;
729
730       if ( ! S_ISLNK (dst_sb_link->st_mode))
731         tmp_dst_sb = *dst_sb_link;
732       else if (stat (dst_name, &tmp_dst_sb) != 0)
733         return true;
734
735       if ( ! SAME_INODE (tmp_src_sb, tmp_dst_sb))
736         return true;
737
738       /* FIXME: shouldn't this be testing whether we're making symlinks?  */
739       if (x->hard_link)
740         {
741           *return_now = true;
742           return true;
743         }
744     }
745
746   return false;
747 }
748
749 static void
750 overwrite_prompt (char const *dst_name, struct stat const *dst_sb)
751 {
752   if (euidaccess (dst_name, W_OK) != 0)
753     {
754       fprintf (stderr,
755                _("%s: overwrite %s, overriding mode %04lo? "),
756                program_name, quote (dst_name),
757                (unsigned long int) (dst_sb->st_mode & CHMOD_MODE_BITS));
758     }
759   else
760     {
761       fprintf (stderr, _("%s: overwrite %s? "),
762                program_name, quote (dst_name));
763     }
764 }
765
766 /* Hash an F_triple.  */
767 static size_t
768 triple_hash (void const *x, size_t table_size)
769 {
770   struct F_triple const *p = x;
771
772   /* Also take the name into account, so that when moving N hard links to the
773      same file (all listed on the command line) all into the same directory,
774      we don't experience any N^2 behavior.  */
775   /* FIXME-maybe: is it worth the overhead of doing this
776      just to avoid N^2 in such an unusual case?  N would have
777      to be very large to make the N^2 factor noticable, and
778      one would probably encounter a limit on the length of
779      a command line before it became a problem.  */
780   size_t tmp = hash_pjw (p->name, table_size);
781
782   /* Ignoring the device number here should be fine.  */
783   return (tmp | p->st_ino) % table_size;
784 }
785
786 /* Hash an F_triple.  */
787 static size_t
788 triple_hash_no_name (void const *x, size_t table_size)
789 {
790   struct F_triple const *p = x;
791
792   /* Ignoring the device number here should be fine.  */
793   return p->st_ino % table_size;
794 }
795
796 /* Compare two F_triple structs.  */
797 static bool
798 triple_compare (void const *x, void const *y)
799 {
800   struct F_triple const *a = x;
801   struct F_triple const *b = y;
802   return (SAME_INODE (*a, *b) && same_name (a->name, b->name)) ? true : false;
803 }
804
805 /* Free an F_triple.  */
806 static void
807 triple_free (void *x)
808 {
809   struct F_triple *a = x;
810   free (a->name);
811   free (a);
812 }
813
814 /* Initialize the hash table implementing a set of F_triple entries
815    corresponding to destination files.  */
816 extern void
817 dest_info_init (struct cp_options *x)
818 {
819   x->dest_info
820     = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
821                        NULL,
822                        triple_hash,
823                        triple_compare,
824                        triple_free);
825 }
826
827 /* Initialize the hash table implementing a set of F_triple entries
828    corresponding to source files listed on the command line.  */
829 extern void
830 src_info_init (struct cp_options *x)
831 {
832
833   /* Note that we use triple_hash_no_name here.
834      Contrast with the use of triple_hash above.
835      That is necessary because a source file may be specified
836      in many different ways.  We want to warn about this
837        cp a a d/
838      as well as this:
839        cp a ./a d/
840   */
841   x->src_info
842     = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
843                        NULL,
844                        triple_hash_no_name,
845                        triple_compare,
846                        triple_free);
847 }
848
849 /* Return true if there is an entry in hash table, HT,
850    for the file described by FILE and STATS.  */
851 static bool
852 seen_file (Hash_table const *ht, char const *file,
853            struct stat const *stats)
854 {
855   struct F_triple new_ent;
856
857   if (ht == NULL)
858     return false;
859
860   new_ent.name = (char *) file;
861   new_ent.st_ino = stats->st_ino;
862   new_ent.st_dev = stats->st_dev;
863
864   return !!hash_lookup (ht, &new_ent);
865 }
866
867 /* Record destination file, FILE, and dev/ino from *STATS,
868    in the hash table, HT.  If HT is NULL, return immediately.
869    If STATS is NULL, call lstat on FILE to get the device
870    and inode numbers.  If that lstat fails, simply return.
871    If memory allocation fails, exit immediately.  */
872 static void
873 record_file (Hash_table *ht, char const *file,
874              struct stat const *stats)
875 {
876   struct F_triple *ent;
877
878   if (ht == NULL)
879     return;
880
881   ent = xmalloc (sizeof *ent);
882   ent->name = xstrdup (file);
883   if (stats)
884     {
885       ent->st_ino = stats->st_ino;
886       ent->st_dev = stats->st_dev;
887     }
888   else
889     {
890       struct stat sb;
891       if (lstat (file, &sb) != 0)
892         return;
893       ent->st_ino = sb.st_ino;
894       ent->st_dev = sb.st_dev;
895     }
896
897   {
898     struct F_triple *ent_from_table = hash_insert (ht, ent);
899     if (ent_from_table == NULL)
900       {
901         /* Insertion failed due to lack of memory.  */
902         xalloc_die ();
903       }
904
905     if (ent_from_table != ent)
906       {
907         /* There was alread a matching entry in the table, so ENT was
908            not inserted.  Free it.  */
909         triple_free (ent);
910       }
911   }
912 }
913
914 /* When effecting a move (e.g., for mv(1)), and given the name DST_NAME
915    of the destination and a corresponding stat buffer, DST_SB, return
916    true if the logical `move' operation should _not_ proceed.
917    Otherwise, return false.
918    Depending on options specified in X, this code may issue an
919    interactive prompt asking whether it's ok to overwrite DST_NAME.  */
920 static bool
921 abandon_move (const struct cp_options *x,
922               char const *dst_name,
923               struct stat const *dst_sb)
924 {
925   assert (x->move_mode);
926   return (x->interactive == I_ALWAYS_NO
927           || ((x->interactive == I_ASK_USER
928                || (x->interactive == I_UNSPECIFIED
929                    && x->stdin_tty
930                    && UNWRITABLE (dst_name, dst_sb->st_mode)))
931               && (overwrite_prompt (dst_name, dst_sb), 1)
932               && ! yesno ()));
933 }
934
935 /* Copy the file SRC_NAME to the file DST_NAME.  The files may be of
936    any type.  NEW_DST should be true if the file DST_NAME cannot
937    exist because its parent directory was just created; NEW_DST should
938    be false if DST_NAME might already exist.  DEVICE is the device
939    number of the parent directory, or 0 if the parent of this file is
940    not known.  ANCESTORS points to a linked, null terminated list of
941    devices and inodes of parent directories of SRC_NAME.  COMMAND_LINE_ARG
942    is true iff SRC_NAME was specified on the command line.
943    Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
944    same as) DST_NAME; otherwise, clear it.
945    Return true if successful.  */
946
947 static bool
948 copy_internal (char const *src_name, char const *dst_name,
949                bool new_dst,
950                dev_t device,
951                struct dir_list *ancestors,
952                const struct cp_options *x,
953                bool command_line_arg,
954                bool *copy_into_self,
955                bool *rename_succeeded)
956 {
957   struct stat src_sb;
958   struct stat dst_sb;
959   mode_t src_mode;
960   mode_t src_type;
961   mode_t dst_mode IF_LINT (= 0);
962   bool restore_dst_mode = false;
963   char *earlier_file = NULL;
964   char *dst_backup = NULL;
965   bool backup_succeeded = false;
966   bool delayed_ok;
967   bool copied_as_regular = false;
968   bool preserve_metadata;
969
970   if (x->move_mode && rename_succeeded)
971     *rename_succeeded = false;
972
973   *copy_into_self = false;
974
975   if (XSTAT (x, src_name, &src_sb) != 0)
976     {
977       error (0, errno, _("cannot stat %s"), quote (src_name));
978       return false;
979     }
980
981   src_type = src_sb.st_mode;
982
983   src_mode = src_sb.st_mode;
984
985   if (S_ISDIR (src_type) && !x->recursive)
986     {
987       error (0, 0, _("omitting directory %s"), quote (src_name));
988       return false;
989     }
990
991   /* Detect the case in which the same source file appears more than
992      once on the command line and no backup option has been selected.
993      If so, simply warn and don't copy it the second time.
994      This check is enabled only if x->src_info is non-NULL.  */
995   if (command_line_arg)
996     {
997       if ( ! S_ISDIR (src_sb.st_mode)
998            && x->backup_type == no_backups
999            && seen_file (x->src_info, src_name, &src_sb))
1000         {
1001           error (0, 0, _("warning: source file %s specified more than once"),
1002                  quote (src_name));
1003           return true;
1004         }
1005
1006       record_file (x->src_info, src_name, &src_sb);
1007     }
1008
1009   if (!new_dst)
1010     {
1011       if (XSTAT (x, dst_name, &dst_sb) != 0)
1012         {
1013           if (errno != ENOENT)
1014             {
1015               error (0, errno, _("cannot stat %s"), quote (dst_name));
1016               return false;
1017             }
1018           else
1019             {
1020               new_dst = true;
1021             }
1022         }
1023       else
1024         {
1025           bool return_now;
1026           bool unlink_src;
1027           bool ok = same_file_ok (src_name, &src_sb, dst_name, &dst_sb,
1028                                   x, &return_now, &unlink_src);
1029           if (unlink_src)
1030             {
1031               if (!abandon_move (x, dst_name, &dst_sb)
1032                   && unlink (src_name) != 0)
1033                 {
1034                   error (0, errno, _("cannot remove %s"), quote (src_name));
1035                   return false;
1036                 }
1037               /* Tell the caller that there's no need to remove src_name.  */
1038               if (rename_succeeded)
1039                 *rename_succeeded = true;
1040             }
1041
1042           if (return_now)
1043             return true;
1044
1045           if (! ok)
1046             {
1047               error (0, 0, _("%s and %s are the same file"),
1048                      quote_n (0, src_name), quote_n (1, dst_name));
1049               return false;
1050             }
1051
1052           if (!S_ISDIR (dst_sb.st_mode))
1053             {
1054               if (S_ISDIR (src_type))
1055                 {
1056                   if (x->move_mode && x->backup_type != no_backups)
1057                     {
1058                     }
1059                   else
1060                     {
1061                       error (0, 0,
1062                        _("cannot overwrite non-directory %s with directory %s"),
1063                              quote_n (0, dst_name), quote_n (1, src_name));
1064                       return false;
1065                     }
1066                 }
1067
1068               /* Don't let the user destroy their data, even if they try hard:
1069                  This mv command must fail (likewise for cp):
1070                    rm -rf a b c; mkdir a b c; touch a/f b/f; mv a/f b/f c
1071                  Otherwise, the contents of b/f would be lost.
1072                  In the case of `cp', b/f would be lost if the user simulated
1073                  a move using cp and rm.
1074                  Note that it works fine if you use --backup=numbered.  */
1075               if (command_line_arg
1076                   && x->backup_type != numbered_backups
1077                   && seen_file (x->dest_info, dst_name, &dst_sb))
1078                 {
1079                   error (0, 0,
1080                          _("will not overwrite just-created %s with %s"),
1081                          quote_n (0, dst_name), quote_n (1, src_name));
1082                   return false;
1083                 }
1084             }
1085
1086           if (!S_ISDIR (src_type))
1087             {
1088               if (S_ISDIR (dst_sb.st_mode))
1089                 {
1090                   if (x->move_mode && x->backup_type != no_backups)
1091                     {
1092                     }
1093                   else
1094                     {
1095                       error (0, 0,
1096                          _("cannot overwrite directory %s with non-directory"),
1097                              quote (dst_name));
1098                       return false;
1099                     }
1100                 }
1101
1102               if (x->update)
1103                 {
1104                   /* When preserving time stamps (but not moving within a file
1105                      system), don't worry if the destination time stamp is
1106                      less than the source merely because of time stamp
1107                      truncation.  */
1108                   int options = ((x->preserve_timestamps
1109                                   && ! (x->move_mode
1110                                         && dst_sb.st_dev == src_sb.st_dev))
1111                                  ? UTIMECMP_TRUNCATE_SOURCE
1112                                  : 0);
1113
1114                   if (0 <= utimecmp (dst_name, &dst_sb, &src_sb, options))
1115                     {
1116                       /* We're using --update and the destination is not older
1117                          than the source, so do not copy or move.  Pretend the
1118                          rename succeeded, so the caller (if it's mv) doesn't
1119                          end up removing the source file.  */
1120                       if (rename_succeeded)
1121                         *rename_succeeded = true;
1122                       return true;
1123                     }
1124                 }
1125             }
1126
1127           /* When there is an existing destination file, we may end up
1128              returning early, and hence not copying/moving the file.
1129              This may be due to an interactive `negative' reply to the
1130              prompt about the existing file.  It may also be due to the
1131              use of the --reply=no option.  */
1132           if (!S_ISDIR (src_type))
1133             {
1134               /* cp and mv treat -i and -f differently.  */
1135               if (x->move_mode)
1136                 {
1137                   if (abandon_move (x, dst_name, &dst_sb))
1138                     {
1139                       /* Pretend the rename succeeded, so the caller (mv)
1140                          doesn't end up removing the source file.  */
1141                       if (rename_succeeded)
1142                         *rename_succeeded = true;
1143                       return true;
1144                     }
1145                 }
1146               else
1147                 {
1148                   if (x->interactive == I_ALWAYS_NO
1149                       || (x->interactive == I_ASK_USER
1150                           && (overwrite_prompt (dst_name, &dst_sb), 1)
1151                           && ! yesno ()))
1152                     {
1153                       return true;
1154                     }
1155                 }
1156             }
1157
1158           if (x->move_mode)
1159             {
1160               /* Don't allow user to move a directory onto a non-directory.  */
1161               if (S_ISDIR (src_sb.st_mode) && !S_ISDIR (dst_sb.st_mode)
1162                   && x->backup_type == no_backups)
1163                 {
1164                   error (0, 0,
1165                        _("cannot move directory onto non-directory: %s -> %s"),
1166                          quote_n (0, src_name), quote_n (0, dst_name));
1167                   return false;
1168                 }
1169             }
1170
1171           bool backup_directories = true;
1172           if (x->backup_type != no_backups
1173               && (!S_ISDIR (dst_sb.st_mode) || backup_directories))
1174             {
1175               char *tmp_backup = find_backup_file_name (dst_name,
1176                                                         x->backup_type);
1177
1178               /* Detect (and fail) when creating the backup file would
1179                  destroy the source file.  Before, running the commands
1180                  cd /tmp; rm -f a a~; : > a; echo A > a~; cp --b=simple a~ a
1181                  would leave two zero-length files: a and a~.  */
1182               /* FIXME: but simply change e.g., the final a~ to `./a~'
1183                  and the source will still be destroyed.  */
1184               if (STREQ (tmp_backup, src_name))
1185                 {
1186                   const char *fmt;
1187                   fmt = (x->move_mode
1188                  ? _("backing up %s would destroy source;  %s not moved")
1189                  : _("backing up %s would destroy source;  %s not copied"));
1190                   error (0, 0, fmt,
1191                          quote_n (0, dst_name),
1192                          quote_n (1, src_name));
1193                   free (tmp_backup);
1194                   return false;
1195                 }
1196
1197               /* FIXME: use fts:
1198                  Using alloca for a file name that may be arbitrarily
1199                  long is not recommended.  In fact, even forming such a name
1200                  should be discouraged.  Eventually, this code will be rewritten
1201                  to use fts, so using alloca here will be less of a problem.  */
1202               ASSIGN_STRDUPA (dst_backup, tmp_backup);
1203               free (tmp_backup);
1204               if (rename (dst_name, dst_backup) != 0)
1205                 {
1206                   if (errno != ENOENT)
1207                     {
1208                       error (0, errno, _("cannot backup %s"), quote (dst_name));
1209                       return false;
1210                     }
1211                   else
1212                     {
1213                       dst_backup = NULL;
1214                     }
1215                 }
1216               else
1217                 {
1218                   backup_succeeded = true;
1219                 }
1220               new_dst = true;
1221             }
1222           else if (! S_ISDIR (dst_sb.st_mode)
1223                    && (x->unlink_dest_before_opening
1224                        || (x->preserve_links && 1 < dst_sb.st_nlink)
1225                        || (!x->move_mode
1226                            && x->dereference == DEREF_NEVER
1227                            && S_ISLNK (src_sb.st_mode))
1228                        ))
1229             {
1230               if (unlink (dst_name) != 0 && errno != ENOENT)
1231                 {
1232                   error (0, errno, _("cannot remove %s"), quote (dst_name));
1233                   return false;
1234                 }
1235               new_dst = true;
1236             }
1237         }
1238     }
1239
1240   /* If the source is a directory, we don't always create the destination
1241      directory.  So --verbose should not announce anything until we're
1242      sure we'll create a directory. */
1243   if (x->verbose && !S_ISDIR (src_type))
1244     {
1245       printf ("%s -> %s", quote_n (0, src_name), quote_n (1, dst_name));
1246       if (backup_succeeded)
1247         printf (_(" (backup: %s)"), quote (dst_backup));
1248       putchar ('\n');
1249     }
1250
1251   /* Associate the destination file name with the source device and inode
1252      so that if we encounter a matching dev/ino pair in the source tree
1253      we can arrange to create a hard link between the corresponding names
1254      in the destination tree.
1255
1256      Sometimes, when preserving links, we have to record dev/ino even
1257      though st_nlink == 1:
1258      - when in move_mode, since we may be moving a group of N hard-linked
1259         files (via two or more command line arguments) to a different
1260         partition; the links may be distributed among the command line
1261         arguments (possibly hierarchies) so that the link count of
1262         the final, once-linked source file is reduced to 1 when it is
1263         considered below.  But in this case (for mv) we don't need to
1264         incur the expense of recording the dev/ino => name mapping; all we
1265         really need is a lookup, to see if the dev/ino pair has already
1266         been copied.
1267      - when using -H and processing a command line argument;
1268         that command line argument could be a symlink pointing to another
1269         command line argument.  With `cp -H --preserve=link', we hard-link
1270         those two destination files.
1271      - likewise for -L except that it applies to all files, not just
1272         command line arguments.
1273
1274      Also record directory dev/ino when using --recursive.  We'll use that
1275      info to detect this problem: cp -R dir dir.  FIXME-maybe: ideally,
1276      directory info would be recorded in a separate hash table, since
1277      such entries are useful only while a single command line hierarchy
1278      is being copied -- so that separate table could be cleared between
1279      command line args.  Using the same hash table to preserve hard
1280      links means that it may not be cleared.  */
1281
1282   if (x->move_mode && src_sb.st_nlink == 1)
1283     {
1284         earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev);
1285     }
1286   else if ((x->preserve_links
1287             && (1 < src_sb.st_nlink
1288                 || (command_line_arg
1289                     && x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
1290                 || x->dereference == DEREF_ALWAYS))
1291            || (x->recursive && S_ISDIR (src_type)))
1292     {
1293       earlier_file = remember_copied (dst_name, src_sb.st_ino, src_sb.st_dev);
1294     }
1295
1296   /* Did we copy this inode somewhere else (in this command line argument)
1297      and therefore this is a second hard link to the inode?  */
1298
1299   if (earlier_file)
1300     {
1301       /* Avoid damaging the destination file system by refusing to preserve
1302          hard-linked directories (which are found at least in Netapp snapshot
1303          directories).  */
1304       if (S_ISDIR (src_type))
1305         {
1306           /* If src_name and earlier_file refer to the same directory entry,
1307              then warn about copying a directory into itself.  */
1308           if (same_name (src_name, earlier_file))
1309             {
1310               error (0, 0, _("cannot copy a directory, %s, into itself, %s"),
1311                      quote_n (0, top_level_src_name),
1312                      quote_n (1, top_level_dst_name));
1313               *copy_into_self = true;
1314               goto un_backup;
1315             }
1316           else if (x->dereference == DEREF_ALWAYS)
1317             {
1318               /* This happens when e.g., encountering a directory for the
1319                  second or subsequent time via symlinks when cp is invoked
1320                  with -R and -L.  E.g.,
1321                  rm -rf a b c d; mkdir a b c d; ln -s ../c a; ln -s ../c b;
1322                  cp -RL a b d
1323               */
1324             }
1325           else
1326             {
1327               error (0, 0, _("will not create hard link %s to directory %s"),
1328                      quote_n (0, dst_name), quote_n (1, earlier_file));
1329               goto un_backup;
1330             }
1331         }
1332       else
1333         {
1334           bool link_failed = (link (earlier_file, dst_name) != 0);
1335
1336           /* If the link failed because of an existing destination,
1337              remove that file and then call link again.  */
1338           if (link_failed && errno == EEXIST)
1339             {
1340               if (unlink (dst_name) != 0)
1341                 {
1342                   error (0, errno, _("cannot remove %s"), quote (dst_name));
1343                   goto un_backup;
1344                 }
1345               link_failed = (link (earlier_file, dst_name) != 0);
1346             }
1347
1348           if (link_failed)
1349             {
1350               error (0, errno, _("cannot create hard link %s to %s"),
1351                      quote_n (0, dst_name), quote_n (1, earlier_file));
1352               goto un_backup;
1353             }
1354
1355           return true;
1356         }
1357     }
1358
1359   if (x->move_mode)
1360     {
1361       if (rename (src_name, dst_name) == 0)
1362         {
1363           if (x->verbose && S_ISDIR (src_type))
1364             printf ("%s -> %s\n", quote_n (0, src_name), quote_n (1, dst_name));
1365           if (rename_succeeded)
1366             *rename_succeeded = true;
1367
1368           if (command_line_arg)
1369             {
1370               /* Record destination dev/ino/name, so that if we are asked
1371                  to overwrite that file again, we can detect it and fail.  */
1372               /* It's fine to use the _source_ stat buffer (src_sb) to get the
1373                  _destination_ dev/ino, since the rename above can't have
1374                  changed those, and `mv' always uses lstat.
1375                  We could limit it further by operating
1376                  only on non-directories.  */
1377               record_file (x->dest_info, dst_name, &src_sb);
1378             }
1379
1380           return true;
1381         }
1382
1383       /* FIXME: someday, consider what to do when moving a directory into
1384          itself but when source and destination are on different devices.  */
1385
1386       /* This happens when attempting to rename a directory to a
1387          subdirectory of itself.  */
1388       if (errno == EINVAL
1389
1390           /* When src_name is on an NFS file system, some types of
1391              clients, e.g., SunOS4.1.4 and IRIX-5.3, set errno to EIO
1392              instead.  Testing for this here risks misinterpreting a real
1393              I/O error as an attempt to move a directory into itself, so
1394              FIXME: consider not doing this.  */
1395           || errno == EIO
1396
1397           /* And with SunOS-4.1.4 client and OpenBSD-2.3 server,
1398              we get ENOTEMPTY.  */
1399           || errno == ENOTEMPTY)
1400         {
1401           /* FIXME: this is a little fragile in that it relies on rename(2)
1402              failing with a specific errno value.  Expect problems on
1403              non-POSIX systems.  */
1404           error (0, 0, _("cannot move %s to a subdirectory of itself, %s"),
1405                  quote_n (0, top_level_src_name),
1406                  quote_n (1, top_level_dst_name));
1407
1408           /* Note that there is no need to call forget_created here,
1409              (compare with the other calls in this file) since the
1410              destination directory didn't exist before.  */
1411
1412           *copy_into_self = true;
1413           /* FIXME-cleanup: Don't return true here; adjust mv.c accordingly.
1414              The only caller that uses this code (mv.c) ends up setting its
1415              exit status to nonzero when copy_into_self is nonzero.  */
1416           return true;
1417         }
1418
1419       /* WARNING: there probably exist systems for which an inter-device
1420          rename fails with a value of errno not handled here.
1421          If/as those are reported, add them to the condition below.
1422          If this happens to you, please do the following and send the output
1423          to the bug-reporting address (e.g., in the output of cp --help):
1424            touch k; perl -e 'rename "k","/tmp/k" or print "$!(",$!+0,")\n"'
1425          where your current directory is on one partion and /tmp is the other.
1426          Also, please try to find the E* errno macro name corresponding to
1427          the diagnostic and parenthesized integer, and include that in your
1428          e-mail.  One way to do that is to run a command like this
1429            find /usr/include/. -type f \
1430              | xargs grep 'define.*\<E[A-Z]*\>.*\<18\>' /dev/null
1431          where you'd replace `18' with the integer in parentheses that
1432          was output from the perl one-liner above.
1433          If necessary, of course, change `/tmp' to some other directory.  */
1434       if (errno != EXDEV)
1435         {
1436           /* There are many ways this can happen due to a race condition.
1437              When something happens between the initial xstat and the
1438              subsequent rename, we can get many different types of errors.
1439              For example, if the destination is initially a non-directory
1440              or non-existent, but it is created as a directory, the rename
1441              fails.  If two `mv' commands try to rename the same file at
1442              about the same time, one will succeed and the other will fail.
1443              If the permissions on the directory containing the source or
1444              destination file are made too restrictive, the rename will
1445              fail.  Etc.  */
1446           error (0, errno,
1447                  _("cannot move %s to %s"),
1448                  quote_n (0, src_name), quote_n (1, dst_name));
1449           forget_created (src_sb.st_ino, src_sb.st_dev);
1450           return false;
1451         }
1452
1453       /* The rename attempt has failed.  Remove any existing destination
1454          file so that a cross-device `mv' acts as if it were really using
1455          the rename syscall.  */
1456       if (unlink (dst_name) != 0 && errno != ENOENT)
1457         {
1458           error (0, errno,
1459              _("inter-device move failed: %s to %s; unable to remove target"),
1460                  quote_n (0, src_name), quote_n (1, dst_name));
1461           forget_created (src_sb.st_ino, src_sb.st_dev);
1462           return false;
1463         }
1464
1465       new_dst = true;
1466     }
1467
1468   delayed_ok = true;
1469
1470   /* In certain modes (cp's --symbolic-link), and for certain file types
1471      (symlinks and hard links) it doesn't make sense to preserve metadata,
1472      or it's possible to preserve only some of it.
1473      In such cases, set this variable to zero.  */
1474   preserve_metadata = true;
1475
1476   if (S_ISDIR (src_type))
1477     {
1478       struct dir_list *dir;
1479
1480       /* If this directory has been copied before during the
1481          recursion, there is a symbolic link to an ancestor
1482          directory of the symbolic link.  It is impossible to
1483          continue to copy this, unless we've got an infinite disk.  */
1484
1485       if (is_ancestor (&src_sb, ancestors))
1486         {
1487           error (0, 0, _("cannot copy cyclic symbolic link %s"),
1488                  quote (src_name));
1489           goto un_backup;
1490         }
1491
1492       /* Insert the current directory in the list of parents.  */
1493
1494       dir = alloca (sizeof *dir);
1495       dir->parent = ancestors;
1496       dir->ino = src_sb.st_ino;
1497       dir->dev = src_sb.st_dev;
1498
1499       if (new_dst || !S_ISDIR (dst_sb.st_mode))
1500         {
1501           if (mkdir (dst_name, src_mode) != 0)
1502             {
1503               error (0, errno, _("cannot create directory %s"),
1504                      quote (dst_name));
1505               goto un_backup;
1506             }
1507
1508           /* We need search and write permissions to the new directory
1509              for writing the directory's contents. Check if these
1510              permissions are there.  */
1511
1512           if (lstat (dst_name, &dst_sb) != 0)
1513             {
1514               error (0, errno, _("cannot stat %s"), quote (dst_name));
1515               goto un_backup;
1516             }
1517           else if ((dst_sb.st_mode & S_IRWXU) != S_IRWXU)
1518             {
1519               /* Make the new directory searchable and writable.  */
1520
1521               dst_mode = dst_sb.st_mode;
1522               restore_dst_mode = true;
1523
1524               if (lchmod (dst_name, dst_mode | S_IRWXU) != 0)
1525                 {
1526                   error (0, errno, _("setting permissions for %s"),
1527                          quote (dst_name));
1528                   goto un_backup;
1529                 }
1530             }
1531
1532           /* Insert the created directory's inode and device
1533              numbers into the search structure, so that we can
1534              avoid copying it again.  */
1535
1536           remember_copied (dst_name, dst_sb.st_ino, dst_sb.st_dev);
1537
1538           if (x->verbose)
1539             printf ("%s -> %s\n", quote_n (0, src_name), quote_n (1, dst_name));
1540         }
1541
1542       /* Are we crossing a file system boundary?  */
1543       if (x->one_file_system && device != 0 && device != src_sb.st_dev)
1544         return true;
1545
1546       /* Copy the contents of the directory.  */
1547
1548       if (! copy_dir (src_name, dst_name, new_dst, &src_sb, dir, x,
1549                       copy_into_self))
1550         {
1551           /* Don't just return here -- otherwise, the failure to read a
1552              single file in a source directory would cause the containing
1553              destination directory not to have owner/perms set properly.  */
1554           delayed_ok = false;
1555         }
1556     }
1557 #ifdef S_ISLNK
1558   else if (x->symbolic_link)
1559     {
1560       preserve_metadata = false;
1561
1562       if (*src_name != '/')
1563         {
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;
1569
1570           dst_parent = dir_name (dst_name);
1571
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);
1580
1581           if (! in_current_dir)
1582             {
1583               error (0, 0,
1584            _("%s: can make relative symbolic links only in current directory"),
1585                      quote (dst_name));
1586               goto un_backup;
1587             }
1588         }
1589       if (symlink (src_name, dst_name) != 0)
1590         {
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;
1594         }
1595     }
1596 #endif
1597
1598   else if (x->hard_link
1599 #ifdef LINK_FOLLOWS_SYMLINKS
1600   /* A POSIX-conforming link syscall dereferences a symlink, yet cp,
1601      invoked with `--link --no-dereference', should not.  Thus, with
1602      a POSIX-conforming link system call, we can't use link() here,
1603      since that would create a hard link to the referent (effectively
1604      dereferencing the symlink), rather than to the symlink itself.
1605      We can approximate the desired behavior by skipping this hard-link
1606      creating block and instead copying the symlink, via the `S_ISLNK'-
1607      copying code below.
1608      When link operates on the symlinks themselves, we use this block
1609      and just call link().  */
1610            && !(S_ISLNK (src_mode) && x->dereference == DEREF_NEVER)
1611 #endif
1612            )
1613     {
1614       preserve_metadata = false;
1615       if (link (src_name, dst_name))
1616         {
1617           error (0, errno, _("cannot create link %s"), quote (dst_name));
1618           goto un_backup;
1619         }
1620     }
1621   else if (S_ISREG (src_type)
1622            || (x->copy_as_regular && !S_ISLNK (src_type)))
1623     {
1624       copied_as_regular = true;
1625       /* POSIX says the permission bits of the source file must be
1626          used as the 3rd argument in the open call, but that's not consistent
1627          with historical practice.  */
1628       if (! copy_reg (src_name, dst_name, x, src_mode, &new_dst, &src_sb))
1629         goto un_backup;
1630     }
1631   else
1632 #ifdef S_ISFIFO
1633   if (S_ISFIFO (src_type))
1634     {
1635       if (mkfifo (dst_name, src_mode))
1636         {
1637           error (0, errno, _("cannot create fifo %s"), quote (dst_name));
1638           goto un_backup;
1639         }
1640     }
1641   else
1642 #endif
1643     if (S_ISBLK (src_type) || S_ISCHR (src_type)
1644         || S_ISSOCK (src_type))
1645     {
1646       if (mknod (dst_name, src_mode, src_sb.st_rdev))
1647         {
1648           error (0, errno, _("cannot create special file %s"),
1649                  quote (dst_name));
1650           goto un_backup;
1651         }
1652     }
1653   else
1654 #ifdef S_ISLNK
1655   if (S_ISLNK (src_type))
1656     {
1657       char *src_link_val = xreadlink (src_name, src_sb.st_size);
1658       if (src_link_val == NULL)
1659         {
1660           error (0, errno, _("cannot read symbolic link %s"), quote (src_name));
1661           goto un_backup;
1662         }
1663
1664       if (symlink (src_link_val, dst_name) == 0)
1665         free (src_link_val);
1666       else
1667         {
1668           int saved_errno = errno;
1669           bool same_link = false;
1670           if (x->update && !new_dst && S_ISLNK (dst_sb.st_mode)
1671               && dst_sb.st_size == strlen (src_link_val))
1672             {
1673               /* See if the destination is already the desired symlink.
1674                  FIXME: This behavior isn't documented, and seems wrong
1675                  in some cases, e.g., if the destination symlink has the
1676                  wrong ownership, permissions, or time stamps.  */
1677               char *dest_link_val = xreadlink (dst_name, dst_sb.st_size);
1678               if (STREQ (dest_link_val, src_link_val))
1679                 same_link = true;
1680               free (dest_link_val);
1681             }
1682           free (src_link_val);
1683
1684           if (! same_link)
1685             {
1686               error (0, saved_errno, _("cannot create symbolic link %s"),
1687                      quote (dst_name));
1688               goto un_backup;
1689             }
1690         }
1691
1692       /* There's no need to preserve timestamps or permissions.  */
1693       preserve_metadata = false;
1694
1695       if (x->preserve_ownership)
1696         {
1697           /* Preserve the owner and group of the just-`copied'
1698              symbolic link, if possible.  */
1699 # if HAVE_LCHOWN
1700           if (lchown (dst_name, src_sb.st_uid, src_sb.st_gid) != 0
1701               && ! chown_failure_ok (x))
1702             {
1703               error (0, errno, _("failed to preserve ownership for %s"),
1704                      dst_name);
1705               goto un_backup;
1706             }
1707 # else
1708           /* Can't preserve ownership of symlinks.
1709              FIXME: maybe give a warning or even error for symlinks
1710              in directories with the sticky bit set -- there, not
1711              preserving owner/group is a potential security problem.  */
1712 # endif
1713         }
1714     }
1715   else
1716 #endif
1717     {
1718       error (0, 0, _("%s has unknown file type"), quote (src_name));
1719       goto un_backup;
1720     }
1721
1722   if (command_line_arg)
1723     record_file (x->dest_info, dst_name, NULL);
1724
1725   if ( ! preserve_metadata)
1726     return true;
1727
1728   if (copied_as_regular)
1729     return delayed_ok;
1730
1731   /* POSIX says that `cp -p' must restore the following:
1732      - permission bits
1733      - setuid, setgid bits
1734      - owner and group
1735      If it fails to restore any of those, we may give a warning but
1736      the destination must not be removed.
1737      FIXME: implement the above. */
1738
1739   /* Adjust the times (and if possible, ownership) for the copy.
1740      chown turns off set[ug]id bits for non-root,
1741      so do the chmod last.  */
1742
1743   if (x->preserve_timestamps)
1744     {
1745       struct timespec timespec[2];
1746       timespec[0] = get_stat_atime (&src_sb);
1747       timespec[1] = get_stat_mtime (&src_sb);
1748
1749       if (utimens (dst_name, timespec) != 0)
1750         {
1751           error (0, errno, _("preserving times for %s"), quote (dst_name));
1752           if (x->require_preserve)
1753             return false;
1754         }
1755     }
1756
1757   /* Avoid calling chown if we know it's not necessary.  */
1758   if (x->preserve_ownership
1759       && (new_dst || !SAME_OWNER_AND_GROUP (src_sb, dst_sb)))
1760     {
1761       if (! set_owner (x, dst_name, -1, src_sb.st_uid, src_sb.st_gid))
1762         return false;
1763     }
1764
1765   set_author (dst_name, -1, &src_sb);
1766
1767   if (x->preserve_mode || x->move_mode)
1768     {
1769       if (copy_acl (src_name, -1, dst_name, -1, src_mode) != 0
1770           && x->require_preserve)
1771         return false;
1772     }
1773   else if (x->set_mode)
1774     {
1775       if (set_acl (dst_name, -1, x->mode) != 0)
1776         return false;
1777     }
1778   else if (restore_dst_mode)
1779     {
1780       if (lchmod (dst_name, dst_mode) != 0)
1781         {
1782           error (0, errno, _("preserving permissions for %s"),
1783                  quote (dst_name));
1784           if (x->require_preserve)
1785             return false;
1786         }
1787     }
1788
1789   return delayed_ok;
1790
1791 un_backup:
1792
1793   /* We have failed to create the destination file.
1794      If we've just added a dev/ino entry via the remember_copied
1795      call above (i.e., unless we've just failed to create a hard link),
1796      remove the entry associating the source dev/ino with the
1797      destination file name, so we don't try to `preserve' a link
1798      to a file we didn't create.  */
1799   if (earlier_file == NULL)
1800     forget_created (src_sb.st_ino, src_sb.st_dev);
1801
1802   if (dst_backup)
1803     {
1804       if (rename (dst_backup, dst_name) != 0)
1805         error (0, errno, _("cannot un-backup %s"), quote (dst_name));
1806       else
1807         {
1808           if (x->verbose)
1809             printf (_("%s -> %s (unbackup)\n"),
1810                     quote_n (0, dst_backup), quote_n (1, dst_name));
1811         }
1812     }
1813   return false;
1814 }
1815
1816 static bool
1817 valid_options (const struct cp_options *co)
1818 {
1819   assert (co != NULL);
1820   assert (VALID_BACKUP_TYPE (co->backup_type));
1821   assert (VALID_SPARSE_MODE (co->sparse_mode));
1822   assert (!(co->hard_link && co->symbolic_link));
1823   return true;
1824 }
1825
1826 /* Copy the file SRC_NAME to the file DST_NAME.  The files may be of
1827    any type.  NONEXISTENT_DST should be true if the file DST_NAME
1828    is known not to exist (e.g., because its parent directory was just
1829    created);  NONEXISTENT_DST should be false if DST_NAME might already
1830    exist.  OPTIONS is ... FIXME-describe
1831    Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
1832    same as) DST_NAME; otherwise, set clear it.
1833    Return true if successful.  */
1834
1835 extern bool
1836 copy (char const *src_name, char const *dst_name,
1837       bool nonexistent_dst, const struct cp_options *options,
1838       bool *copy_into_self, bool *rename_succeeded)
1839 {
1840   assert (valid_options (options));
1841
1842   /* Record the file names: they're used in case of error, when copying
1843      a directory into itself.  I don't like to make these tools do *any*
1844      extra work in the common case when that work is solely to handle
1845      exceptional cases, but in this case, I don't see a way to derive the
1846      top level source and destination directory names where they're used.
1847      An alternative is to use COPY_INTO_SELF and print the diagnostic
1848      from every caller -- but I don't want to do that.  */
1849   top_level_src_name = src_name;
1850   top_level_dst_name = dst_name;
1851
1852   return copy_internal (src_name, dst_name, nonexistent_dst, 0, NULL,
1853                         options, true, copy_into_self, rename_succeeded);
1854 }
1855
1856 /* Return true if this process has appropriate privileges to chown a
1857    file whose owner is not the effective user ID.  */
1858
1859 extern bool
1860 chown_privileges (void)
1861 {
1862 #ifdef PRIV_FILE_CHOWN
1863   bool result;
1864   priv_set_t *pset = priv_allocset ();
1865   if (!pset)
1866     xalloc_die ();
1867   result = (getppriv (PRIV_EFFECTIVE, pset) == 0
1868             && priv_ismember (pset, PRIV_FILE_CHOWN));
1869   priv_freeset (pset);
1870   return result;
1871 #else
1872   return (geteuid () == 0);
1873 #endif
1874 }
1875
1876 /* Return true if it's OK for chown to fail, where errno is
1877    the error number that chown failed with and X is the copying
1878    option set.  */
1879
1880 extern bool
1881 chown_failure_ok (struct cp_options const *x)
1882 {
1883   /* If non-root uses -p, it's ok if we can't preserve ownership.
1884      But root probably wants to know, e.g. if NFS disallows it,
1885      or if the target system doesn't support file ownership.  */
1886
1887   return ((errno == EPERM || errno == EINVAL) && !x->chown_privileges);
1888 }