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