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