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