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