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