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