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