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