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