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