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