mv: ignore xattr-preservation failure when not supported by filesystem
[coreutils.git] / src / copy.c
blobd01f9b3650cfe6b2de4c8f26fb6df53ea1033ad8
1 /* copy.c -- core functions for copying files and directories
2 Copyright (C) 89, 90, 91, 1995-2009 Free Software Foundation, Inc.
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.
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.
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/>. */
17 /* Extracted from cp.c and librarified by Jim Meyering. */
19 #include <config.h>
20 #include <stdio.h>
21 #include <assert.h>
22 #include <sys/types.h>
23 #include <selinux/selinux.h>
25 #if HAVE_HURD_H
26 # include <hurd.h>
27 #endif
28 #if HAVE_PRIV_H
29 # include <priv.h>
30 #endif
32 #include "system.h"
33 #include "acl.h"
34 #include "backupfile.h"
35 #include "buffer-lcm.h"
36 #include "copy.h"
37 #include "cp-hash.h"
38 #include "error.h"
39 #include "fcntl--.h"
40 #include "file-set.h"
41 #include "filemode.h"
42 #include "filenamecat.h"
43 #include "full-write.h"
44 #include "hash.h"
45 #include "hash-triple.h"
46 #include "ignore-value.h"
47 #include "quote.h"
48 #include "same.h"
49 #include "savedir.h"
50 #include "stat-time.h"
51 #include "utimecmp.h"
52 #include "utimens.h"
53 #include "write-any-file.h"
54 #include "areadlink.h"
55 #include "yesno.h"
57 #if USE_XATTR
58 # include <attr/error_context.h>
59 # include <attr/libattr.h>
60 # include <stdarg.h>
61 # include "verror.h"
62 #endif
64 #ifndef HAVE_FCHOWN
65 # define HAVE_FCHOWN false
66 # define fchown(fd, uid, gid) (-1)
67 #endif
69 #ifndef HAVE_LCHOWN
70 # define HAVE_LCHOWN false
71 # define lchown(name, uid, gid) chown (name, uid, gid)
72 #endif
74 #ifndef HAVE_MKFIFO
75 static int
76 rpl_mkfifo (char const *file, mode_t mode)
78 errno = ENOTSUP;
79 return -1;
81 # define mkfifo rpl_mkfifo
82 #endif
84 #ifndef USE_ACL
85 # define USE_ACL 0
86 #endif
88 #define SAME_OWNER(A, B) ((A).st_uid == (B).st_uid)
89 #define SAME_GROUP(A, B) ((A).st_gid == (B).st_gid)
90 #define SAME_OWNER_AND_GROUP(A, B) (SAME_OWNER (A, B) && SAME_GROUP (A, B))
92 struct dir_list
94 struct dir_list *parent;
95 ino_t ino;
96 dev_t dev;
99 /* Initial size of the cp.dest_info hash table. */
100 #define DEST_INFO_INITIAL_CAPACITY 61
102 static bool copy_internal (char const *src_name, char const *dst_name,
103 bool new_dst, dev_t device,
104 struct dir_list *ancestors,
105 const struct cp_options *x,
106 bool command_line_arg,
107 bool *first_dir_created_per_command_line_arg,
108 bool *copy_into_self,
109 bool *rename_succeeded);
110 static bool owner_failure_ok (struct cp_options const *x);
112 /* Pointers to the file names: they're used in the diagnostic that is issued
113 when we detect the user is trying to copy a directory into itself. */
114 static char const *top_level_src_name;
115 static char const *top_level_dst_name;
117 /* FIXME: describe */
118 /* FIXME: rewrite this to use a hash table so we avoid the quadratic
119 performance hit that's probably noticeable only on trees deeper
120 than a few hundred levels. See use of active_dir_map in remove.c */
122 static bool
123 is_ancestor (const struct stat *sb, const struct dir_list *ancestors)
125 while (ancestors != 0)
127 if (ancestors->ino == sb->st_ino && ancestors->dev == sb->st_dev)
128 return true;
129 ancestors = ancestors->parent;
131 return false;
134 #if USE_XATTR
135 static void
136 copy_attr_error (struct error_context *ctx ATTRIBUTE_UNUSED,
137 char const *fmt, ...)
139 int err = errno;
140 va_list ap;
142 if (errno != ENOTSUP && errno != ENODATA)
144 /* use verror module to print error message */
145 va_start (ap, fmt);
146 verror (0, err, fmt, ap);
147 va_end (ap);
151 static void
152 copy_attr_allerror (struct error_context *ctx ATTRIBUTE_UNUSED,
153 char const *fmt, ...)
155 int err = errno;
156 va_list ap;
158 /* use verror module to print error message */
159 va_start (ap, fmt);
160 verror (0, err, fmt, ap);
161 va_end (ap);
164 static char const *
165 copy_attr_quote (struct error_context *ctx ATTRIBUTE_UNUSED, char const *str)
167 return quote (str);
170 static void
171 copy_attr_free (struct error_context *ctx ATTRIBUTE_UNUSED,
172 char const *str ATTRIBUTE_UNUSED)
176 static bool
177 copy_attr_by_fd (char const *src_path, int src_fd,
178 char const *dst_path, int dst_fd, const struct cp_options *x)
180 struct error_context ctx =
182 .error = x->require_preserve_xattr ? copy_attr_allerror : copy_attr_error,
183 .quote = copy_attr_quote,
184 .quote_free = copy_attr_free
186 return 0 == attr_copy_fd (src_path, src_fd, dst_path, dst_fd, 0,
187 x->reduce_diagnostics ? NULL : &ctx);
190 static bool
191 copy_attr_by_name (char const *src_path, char const *dst_path,
192 const struct cp_options *x)
194 struct error_context ctx =
196 .error = x->require_preserve_xattr ? copy_attr_allerror : copy_attr_error,
197 .quote = copy_attr_quote,
198 .quote_free = copy_attr_free
200 return 0 == attr_copy_file (src_path, dst_path, 0,
201 x-> reduce_diagnostics ? NULL :&ctx);
203 #else /* USE_XATTR */
205 static bool
206 copy_attr_by_fd (char const *src_path, int src_fd,
207 char const *dst_path, int dst_fd, const struct cp_options *x)
209 return true;
212 static bool
213 copy_attr_by_name (char const *src_path, char const *dst_path,
214 const struct cp_options *x)
216 return true;
218 #endif /* USE_XATTR */
220 /* Read the contents of the directory SRC_NAME_IN, and recursively
221 copy the contents to DST_NAME_IN. NEW_DST is true if
222 DST_NAME_IN is a directory that was created previously in the
223 recursion. SRC_SB and ANCESTORS describe SRC_NAME_IN.
224 Set *COPY_INTO_SELF if SRC_NAME_IN is a parent of
225 FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG FIXME
226 (or the same as) DST_NAME_IN; otherwise, clear it.
227 Return true if successful. */
229 static bool
230 copy_dir (char const *src_name_in, char const *dst_name_in, bool new_dst,
231 const struct stat *src_sb, struct dir_list *ancestors,
232 const struct cp_options *x,
233 bool *first_dir_created_per_command_line_arg,
234 bool *copy_into_self)
236 char *name_space;
237 char *namep;
238 struct cp_options non_command_line_options = *x;
239 bool ok = true;
241 name_space = savedir (src_name_in);
242 if (name_space == NULL)
244 /* This diagnostic is a bit vague because savedir can fail in
245 several different ways. */
246 error (0, errno, _("cannot access %s"), quote (src_name_in));
247 return false;
250 /* For cp's -H option, dereference command line arguments, but do not
251 dereference symlinks that are found via recursive traversal. */
252 if (x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
253 non_command_line_options.dereference = DEREF_NEVER;
255 namep = name_space;
256 while (*namep != '\0')
258 bool local_copy_into_self;
259 char *src_name = file_name_concat (src_name_in, namep, NULL);
260 char *dst_name = file_name_concat (dst_name_in, namep, NULL);
262 ok &= copy_internal (src_name, dst_name, new_dst, src_sb->st_dev,
263 ancestors, &non_command_line_options, false,
264 first_dir_created_per_command_line_arg,
265 &local_copy_into_self, NULL);
266 *copy_into_self |= local_copy_into_self;
268 free (dst_name);
269 free (src_name);
271 /* If we're copying into self, there's no point in continuing,
272 and in fact, that would even infloop, now that we record only
273 the first created directory per command line argument. */
274 if (local_copy_into_self)
275 break;
277 namep += strlen (namep) + 1;
279 free (name_space);
280 return ok;
283 /* Set the owner and owning group of DEST_DESC to the st_uid and
284 st_gid fields of SRC_SB. If DEST_DESC is undefined (-1), set
285 the owner and owning group of DST_NAME instead; for
286 safety prefer lchown if the system supports it since no
287 symbolic links should be involved. DEST_DESC must
288 refer to the same file as DEST_NAME if defined.
289 Upon failure to set both UID and GID, try to set only the GID.
290 NEW_DST is true if the file was newly created; otherwise,
291 DST_SB is the status of the destination.
292 Return 1 if the initial syscall succeeds, 0 if it fails but it's OK
293 not to preserve ownership, -1 otherwise. */
295 static int
296 set_owner (const struct cp_options *x, char const *dst_name, int dest_desc,
297 struct stat const *src_sb, bool new_dst,
298 struct stat const *dst_sb)
300 uid_t uid = src_sb->st_uid;
301 gid_t gid = src_sb->st_gid;
303 /* Naively changing the ownership of an already-existing file before
304 changing its permissions would create a window of vulnerability if
305 the file's old permissions are too generous for the new owner and
306 group. Avoid the window by first changing to a restrictive
307 temporary mode if necessary. */
309 if (!new_dst && (x->preserve_mode | x->move_mode | x->set_mode))
311 mode_t old_mode = dst_sb->st_mode;
312 mode_t new_mode =
313 (x->preserve_mode | x->move_mode ? src_sb->st_mode : x->mode);
314 mode_t restrictive_temp_mode = old_mode & new_mode & S_IRWXU;
316 if ((USE_ACL
317 || (old_mode & CHMOD_MODE_BITS
318 & (~new_mode | S_ISUID | S_ISGID | S_ISVTX)))
319 && qset_acl (dst_name, dest_desc, restrictive_temp_mode) != 0)
321 if (! owner_failure_ok (x))
322 error (0, errno, _("clearing permissions for %s"), quote (dst_name));
323 return -x->require_preserve;
327 if (HAVE_FCHOWN && dest_desc != -1)
329 if (fchown (dest_desc, uid, gid) == 0)
330 return 1;
331 if (errno == EPERM || errno == EINVAL)
333 /* We've failed to set *both*. Now, try to set just the group
334 ID, but ignore any failure here, and don't change errno. */
335 int saved_errno = errno;
336 ignore_value (fchown (dest_desc, -1, gid));
337 errno = saved_errno;
340 else
342 if (lchown (dst_name, uid, gid) == 0)
343 return 1;
344 if (errno == EPERM || errno == EINVAL)
346 /* We've failed to set *both*. Now, try to set just the group
347 ID, but ignore any failure here, and don't change errno. */
348 int saved_errno = errno;
349 ignore_value (lchown (dst_name, -1, gid));
350 errno = saved_errno;
354 if (! chown_failure_ok (x))
356 error (0, errno, _("failed to preserve ownership for %s"),
357 quote (dst_name));
358 if (x->require_preserve)
359 return -1;
362 return 0;
365 /* Set the st_author field of DEST_DESC to the st_author field of
366 SRC_SB. If DEST_DESC is undefined (-1), set the st_author field
367 of DST_NAME instead. DEST_DESC must refer to the same file as
368 DEST_NAME if defined. */
370 static void
371 set_author (const char *dst_name, int dest_desc, const struct stat *src_sb)
373 #if HAVE_STRUCT_STAT_ST_AUTHOR
374 /* FIXME: Modify the following code so that it does not
375 follow symbolic links. */
377 /* Preserve the st_author field. */
378 file_t file = (dest_desc < 0
379 ? file_name_lookup (dst_name, 0, 0)
380 : getdport (dest_desc));
381 if (file == MACH_PORT_NULL)
382 error (0, errno, _("failed to lookup file %s"), quote (dst_name));
383 else
385 error_t err = file_chauthor (file, src_sb->st_author);
386 if (err)
387 error (0, err, _("failed to preserve authorship for %s"),
388 quote (dst_name));
389 mach_port_deallocate (mach_task_self (), file);
391 #else
392 (void) dst_name;
393 (void) dest_desc;
394 (void) src_sb;
395 #endif
398 /* Change the file mode bits of the file identified by DESC or NAME to MODE.
399 Use DESC if DESC is valid and fchmod is available, NAME otherwise. */
401 static int
402 fchmod_or_lchmod (int desc, char const *name, mode_t mode)
404 #if HAVE_FCHMOD
405 if (0 <= desc)
406 return fchmod (desc, mode);
407 #endif
408 return lchmod (name, mode);
411 /* Copy a regular file from SRC_NAME to DST_NAME.
412 If the source file contains holes, copies holes and blocks of zeros
413 in the source file as holes in the destination file.
414 (Holes are read as zeroes by the `read' system call.)
415 When creating the destination, use DST_MODE & ~OMITTED_PERMISSIONS
416 as the third argument in the call to open, adding
417 OMITTED_PERMISSIONS after copying as needed.
418 X provides many option settings.
419 Return true if successful.
420 *NEW_DST is as in copy_internal.
421 SRC_SB is the result of calling XSTAT (aka stat) on SRC_NAME. */
423 static bool
424 copy_reg (char const *src_name, char const *dst_name,
425 const struct cp_options *x,
426 mode_t dst_mode, mode_t omitted_permissions, bool *new_dst,
427 struct stat const *src_sb)
429 char *buf;
430 char *buf_alloc = NULL;
431 char *name_alloc = NULL;
432 int dest_desc;
433 int dest_errno;
434 int source_desc;
435 mode_t src_mode = src_sb->st_mode;
436 struct stat sb;
437 struct stat src_open_sb;
438 bool return_val = true;
440 source_desc = open (src_name,
441 (O_RDONLY | O_BINARY
442 | (x->dereference == DEREF_NEVER ? O_NOFOLLOW : 0)));
443 if (source_desc < 0)
445 error (0, errno, _("cannot open %s for reading"), quote (src_name));
446 return false;
449 if (fstat (source_desc, &src_open_sb) != 0)
451 error (0, errno, _("cannot fstat %s"), quote (src_name));
452 return_val = false;
453 goto close_src_desc;
456 /* Compare the source dev/ino from the open file to the incoming,
457 saved ones obtained via a previous call to stat. */
458 if (! SAME_INODE (*src_sb, src_open_sb))
460 error (0, 0,
461 _("skipping file %s, as it was replaced while being copied"),
462 quote (src_name));
463 return_val = false;
464 goto close_src_desc;
467 /* The semantics of the following open calls are mandated
468 by the specs for both cp and mv. */
469 if (! *new_dst)
471 dest_desc = open (dst_name, O_WRONLY | O_TRUNC | O_BINARY);
472 dest_errno = errno;
474 /* When using cp --preserve=context to copy to an existing destination,
475 use the default context rather than that of the source. Why?
476 1) the src context may prohibit writing, and
477 2) because it's more consistent to use the same context
478 that is used when the destination file doesn't already exist. */
479 if (x->preserve_security_context && 0 <= dest_desc)
481 security_context_t con = NULL;
482 if (getfscreatecon (&con) < 0)
484 if (!x->reduce_diagnostics)
485 error (0, errno, _("failed to get file system create context"));
486 if (x->require_preserve_context)
488 return_val = false;
489 goto close_src_and_dst_desc;
493 if (con)
495 if (fsetfilecon (dest_desc, con) < 0)
497 if (!x->reduce_diagnostics)
498 error (0, errno,
499 _("failed to set the security context of %s to %s"),
500 quote_n (0, dst_name), quote_n (1, con));
501 if (x->require_preserve_context)
503 return_val = false;
504 freecon (con);
505 goto close_src_and_dst_desc;
508 freecon (con);
512 if (dest_desc < 0 && x->unlink_dest_after_failed_open)
514 if (unlink (dst_name) != 0)
516 error (0, errno, _("cannot remove %s"), quote (dst_name));
517 return_val = false;
518 goto close_src_desc;
520 if (x->verbose)
521 printf (_("removed %s\n"), quote (dst_name));
523 /* Tell caller that the destination file was unlinked. */
524 *new_dst = true;
528 if (*new_dst)
530 int open_flags = O_WRONLY | O_CREAT | O_BINARY;
531 dest_desc = open (dst_name, open_flags | O_EXCL,
532 dst_mode & ~omitted_permissions);
533 dest_errno = errno;
535 /* When trying to copy through a dangling destination symlink,
536 the above open fails with EEXIST. If that happens, and
537 lstat'ing the DST_NAME shows that it is a symlink, then we
538 have a problem: trying to resolve this dangling symlink to
539 a directory/destination-entry pair is fundamentally racy,
540 so punt. If POSIXLY_CORRECT is set, simply call open again,
541 but without O_EXCL (potentially dangerous). If not, fail
542 with a diagnostic. These shenanigans are necessary only
543 when copying, i.e., not in move_mode. */
544 if (dest_desc < 0 && dest_errno == EEXIST && ! x->move_mode)
546 struct stat dangling_link_sb;
547 if (lstat (dst_name, &dangling_link_sb) == 0
548 && S_ISLNK (dangling_link_sb.st_mode))
550 if (x->open_dangling_dest_symlink)
552 dest_desc = open (dst_name, open_flags,
553 dst_mode & ~omitted_permissions);
554 dest_errno = errno;
556 else
558 error (0, 0, _("not writing through dangling symlink %s"),
559 quote (dst_name));
560 return_val = false;
561 goto close_src_desc;
566 else
567 omitted_permissions = 0;
569 if (dest_desc < 0)
571 error (0, dest_errno, _("cannot create regular file %s"),
572 quote (dst_name));
573 return_val = false;
574 goto close_src_desc;
577 if (fstat (dest_desc, &sb) != 0)
579 error (0, errno, _("cannot fstat %s"), quote (dst_name));
580 return_val = false;
581 goto close_src_and_dst_desc;
585 typedef uintptr_t word;
586 off_t n_read_total = 0;
588 /* Choose a suitable buffer size; it may be adjusted later. */
589 size_t buf_alignment = lcm (getpagesize (), sizeof (word));
590 size_t buf_alignment_slop = sizeof (word) + buf_alignment - 1;
591 size_t buf_size = io_blksize (sb);
593 /* Deal with sparse files. */
594 bool last_write_made_hole = false;
595 bool make_holes = false;
597 if (S_ISREG (sb.st_mode))
599 /* Even with --sparse=always, try to create holes only
600 if the destination is a regular file. */
601 if (x->sparse_mode == SPARSE_ALWAYS)
602 make_holes = true;
604 #if HAVE_STRUCT_STAT_ST_BLOCKS
605 /* Use a heuristic to determine whether SRC_NAME contains any sparse
606 blocks. If the file has fewer blocks than would normally be
607 needed for a file of its size, then at least one of the blocks in
608 the file is a hole. */
609 if (x->sparse_mode == SPARSE_AUTO && S_ISREG (src_open_sb.st_mode)
610 && ST_NBLOCKS (src_open_sb) < src_open_sb.st_size / ST_NBLOCKSIZE)
611 make_holes = true;
612 #endif
615 /* If not making a sparse file, try to use a more-efficient
616 buffer size. */
617 if (! make_holes)
619 /* Compute the least common multiple of the input and output
620 buffer sizes, adjusting for outlandish values. */
621 size_t blcm_max = MIN (SIZE_MAX, SSIZE_MAX) - buf_alignment_slop;
622 size_t blcm = buffer_lcm (io_blksize (src_open_sb), buf_size,
623 blcm_max);
625 /* Do not bother with a buffer larger than the input file, plus one
626 byte to make sure the file has not grown while reading it. */
627 if (S_ISREG (src_open_sb.st_mode) && src_open_sb.st_size < buf_size)
628 buf_size = src_open_sb.st_size + 1;
630 /* However, stick with a block size that is a positive multiple of
631 blcm, overriding the above adjustments. Watch out for
632 overflow. */
633 buf_size += blcm - 1;
634 buf_size -= buf_size % blcm;
635 if (buf_size == 0 || blcm_max < buf_size)
636 buf_size = blcm;
639 /* Make a buffer with space for a sentinel at the end. */
640 buf_alloc = xmalloc (buf_size + buf_alignment_slop);
641 buf = ptr_align (buf_alloc, buf_alignment);
643 for (;;)
645 word *wp = NULL;
647 ssize_t n_read = read (source_desc, buf, buf_size);
648 if (n_read < 0)
650 #ifdef EINTR
651 if (errno == EINTR)
652 continue;
653 #endif
654 error (0, errno, _("reading %s"), quote (src_name));
655 return_val = false;
656 goto close_src_and_dst_desc;
658 if (n_read == 0)
659 break;
661 n_read_total += n_read;
663 if (make_holes)
665 char *cp;
667 /* Sentinel to stop loop. */
668 buf[n_read] = '\1';
669 #ifdef lint
670 /* Usually, buf[n_read] is not the byte just before a "word"
671 (aka uintptr_t) boundary. In that case, the word-oriented
672 test below (*wp++ == 0) would read some uninitialized bytes
673 after the sentinel. To avoid false-positive reports about
674 this condition (e.g., from a tool like valgrind), set the
675 remaining bytes -- to any value. */
676 memset (buf + n_read + 1, 0, sizeof (word) - 1);
677 #endif
679 /* Find first nonzero *word*, or the word with the sentinel. */
681 wp = (word *) buf;
682 while (*wp++ == 0)
683 continue;
685 /* Find the first nonzero *byte*, or the sentinel. */
687 cp = (char *) (wp - 1);
688 while (*cp++ == 0)
689 continue;
691 if (cp <= buf + n_read)
692 /* Clear to indicate that a normal write is needed. */
693 wp = NULL;
694 else
696 /* We found the sentinel, so the whole input block was zero.
697 Make a hole. */
698 if (lseek (dest_desc, n_read, SEEK_CUR) < 0)
700 error (0, errno, _("cannot lseek %s"), quote (dst_name));
701 return_val = false;
702 goto close_src_and_dst_desc;
704 last_write_made_hole = true;
708 if (!wp)
710 size_t n = n_read;
711 if (full_write (dest_desc, buf, n) != n)
713 error (0, errno, _("writing %s"), quote (dst_name));
714 return_val = false;
715 goto close_src_and_dst_desc;
717 last_write_made_hole = false;
719 /* It is tempting to return early here upon a short read from a
720 regular file. That would save the final read syscall for each
721 file. Unfortunately that doesn't work for certain files in
722 /proc with linux kernels from at least 2.6.9 .. 2.6.29. */
726 /* If the file ends with a `hole', we need to do something to record
727 the length of the file. On modern systems, calling ftruncate does
728 the job. On systems without native ftruncate support, we have to
729 write a byte at the ending position. Otherwise the kernel would
730 truncate the file at the end of the last write operation. */
732 if (last_write_made_hole)
734 if (HAVE_FTRUNCATE
735 ? /* ftruncate sets the file size,
736 so there is no need for a write. */
737 ftruncate (dest_desc, n_read_total) < 0
738 : /* Seek backwards one character and write a null. */
739 (lseek (dest_desc, (off_t) -1, SEEK_CUR) < 0L
740 || full_write (dest_desc, "", 1) != 1))
742 error (0, errno, _("writing %s"), quote (dst_name));
743 return_val = false;
744 goto close_src_and_dst_desc;
749 if (x->preserve_timestamps)
751 struct timespec timespec[2];
752 timespec[0] = get_stat_atime (src_sb);
753 timespec[1] = get_stat_mtime (src_sb);
755 if (gl_futimens (dest_desc, dst_name, timespec) != 0)
757 error (0, errno, _("preserving times for %s"), quote (dst_name));
758 if (x->require_preserve)
760 return_val = false;
761 goto close_src_and_dst_desc;
766 if (x->preserve_ownership && ! SAME_OWNER_AND_GROUP (*src_sb, sb))
768 switch (set_owner (x, dst_name, dest_desc, src_sb, *new_dst, &sb))
770 case -1:
771 return_val = false;
772 goto close_src_and_dst_desc;
774 case 0:
775 src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX);
776 break;
780 set_author (dst_name, dest_desc, src_sb);
782 if (x->preserve_xattr && ! copy_attr_by_fd (src_name, source_desc,
783 dst_name, dest_desc, x)
784 && x->require_preserve_xattr)
785 return false;
787 if (x->preserve_mode || x->move_mode)
789 if (copy_acl (src_name, source_desc, dst_name, dest_desc, src_mode) != 0
790 && x->require_preserve)
791 return_val = false;
793 else if (x->set_mode)
795 if (set_acl (dst_name, dest_desc, x->mode) != 0)
796 return_val = false;
798 else if (omitted_permissions)
800 omitted_permissions &= ~ cached_umask ();
801 if (omitted_permissions
802 && fchmod_or_lchmod (dest_desc, dst_name, dst_mode) != 0)
804 error (0, errno, _("preserving permissions for %s"),
805 quote (dst_name));
806 if (x->require_preserve)
807 return_val = false;
811 close_src_and_dst_desc:
812 if (close (dest_desc) < 0)
814 error (0, errno, _("closing %s"), quote (dst_name));
815 return_val = false;
817 close_src_desc:
818 if (close (source_desc) < 0)
820 error (0, errno, _("closing %s"), quote (src_name));
821 return_val = false;
824 free (buf_alloc);
825 free (name_alloc);
826 return return_val;
829 /* Return true if it's ok that the source and destination
830 files are the `same' by some measure. The goal is to avoid
831 making the `copy' operation remove both copies of the file
832 in that case, while still allowing the user to e.g., move or
833 copy a regular file onto a symlink that points to it.
834 Try to minimize the cost of this function in the common case.
835 Set *RETURN_NOW if we've determined that the caller has no more
836 work to do and should return successfully, right away.
838 Set *UNLINK_SRC if we've determined that the caller wants to do
839 `rename (a, b)' where `a' and `b' are distinct hard links to the same
840 file. In that case, the caller should try to unlink `a' and then return
841 successfully. Ideally, we wouldn't have to do that, and we'd be
842 able to rely on rename to remove the source file. However, POSIX
843 mistakenly requires that such a rename call do *nothing* and return
844 successfully. */
846 static bool
847 same_file_ok (char const *src_name, struct stat const *src_sb,
848 char const *dst_name, struct stat const *dst_sb,
849 const struct cp_options *x, bool *return_now, bool *unlink_src)
851 const struct stat *src_sb_link;
852 const struct stat *dst_sb_link;
853 struct stat tmp_dst_sb;
854 struct stat tmp_src_sb;
856 bool same_link;
857 bool same = SAME_INODE (*src_sb, *dst_sb);
859 *return_now = false;
860 *unlink_src = false;
862 /* FIXME: this should (at the very least) be moved into the following
863 if-block. More likely, it should be removed, because it inhibits
864 making backups. But removing it will result in a change in behavior
865 that will probably have to be documented -- and tests will have to
866 be updated. */
867 if (same && x->hard_link)
869 *return_now = true;
870 return true;
873 if (x->dereference == DEREF_NEVER)
875 same_link = same;
877 /* If both the source and destination files are symlinks (and we'll
878 know this here IFF preserving symlinks), then it's ok -- as long
879 as they are distinct. */
880 if (S_ISLNK (src_sb->st_mode) && S_ISLNK (dst_sb->st_mode))
881 return ! same_name (src_name, dst_name);
883 src_sb_link = src_sb;
884 dst_sb_link = dst_sb;
886 else
888 if (!same)
889 return true;
891 if (lstat (dst_name, &tmp_dst_sb) != 0
892 || lstat (src_name, &tmp_src_sb) != 0)
893 return true;
895 src_sb_link = &tmp_src_sb;
896 dst_sb_link = &tmp_dst_sb;
898 same_link = SAME_INODE (*src_sb_link, *dst_sb_link);
900 /* If both are symlinks, then it's ok, but only if the destination
901 will be unlinked before being opened. This is like the test
902 above, but with the addition of the unlink_dest_before_opening
903 conjunct because otherwise, with two symlinks to the same target,
904 we'd end up truncating the source file. */
905 if (S_ISLNK (src_sb_link->st_mode) && S_ISLNK (dst_sb_link->st_mode)
906 && x->unlink_dest_before_opening)
907 return true;
910 /* The backup code ensures there's a copy, so it's usually ok to
911 remove any destination file. One exception is when both
912 source and destination are the same directory entry. In that
913 case, moving the destination file aside (in making the backup)
914 would also rename the source file and result in an error. */
915 if (x->backup_type != no_backups)
917 if (!same_link)
919 /* In copy mode when dereferencing symlinks, if the source is a
920 symlink and the dest is not, then backing up the destination
921 (moving it aside) would make it a dangling symlink, and the
922 subsequent attempt to open it in copy_reg would fail with
923 a misleading diagnostic. Avoid that by returning zero in
924 that case so the caller can make cp (or mv when it has to
925 resort to reading the source file) fail now. */
927 /* FIXME-note: even with the following kludge, we can still provoke
928 the offending diagnostic. It's just a little harder to do :-)
929 $ rm -f a b c; touch c; ln -s c b; ln -s b a; cp -b a b
930 cp: cannot open `a' for reading: No such file or directory
931 That's misleading, since a subsequent `ls' shows that `a'
932 is still there.
933 One solution would be to open the source file *before* moving
934 aside the destination, but that'd involve a big rewrite. */
935 if ( ! x->move_mode
936 && x->dereference != DEREF_NEVER
937 && S_ISLNK (src_sb_link->st_mode)
938 && ! S_ISLNK (dst_sb_link->st_mode))
939 return false;
941 return true;
944 return ! same_name (src_name, dst_name);
947 #if 0
948 /* FIXME: use or remove */
950 /* If we're making a backup, we'll detect the problem case in
951 copy_reg because SRC_NAME will no longer exist. Allowing
952 the test to be deferred lets cp do some useful things.
953 But when creating hardlinks and SRC_NAME is a symlink
954 but DST_NAME is not we must test anyway. */
955 if (x->hard_link
956 || !S_ISLNK (src_sb_link->st_mode)
957 || S_ISLNK (dst_sb_link->st_mode))
958 return true;
960 if (x->dereference != DEREF_NEVER)
961 return true;
962 #endif
964 /* They may refer to the same file if we're in move mode and the
965 target is a symlink. That is ok, since we remove any existing
966 destination file before opening it -- via `rename' if they're on
967 the same file system, via `unlink (DST_NAME)' otherwise.
968 It's also ok if they're distinct hard links to the same file. */
969 if (x->move_mode || x->unlink_dest_before_opening)
971 if (S_ISLNK (dst_sb_link->st_mode))
972 return true;
974 if (same_link
975 && 1 < dst_sb_link->st_nlink
976 && ! same_name (src_name, dst_name))
978 if (x->move_mode)
980 *unlink_src = true;
981 *return_now = true;
983 return true;
987 /* If neither is a symlink, then it's ok as long as they aren't
988 hard links to the same file. */
989 if (!S_ISLNK (src_sb_link->st_mode) && !S_ISLNK (dst_sb_link->st_mode))
991 if (!SAME_INODE (*src_sb_link, *dst_sb_link))
992 return true;
994 /* If they are the same file, it's ok if we're making hard links. */
995 if (x->hard_link)
997 *return_now = true;
998 return true;
1002 /* It's ok to remove a destination symlink. But that works only when we
1003 unlink before opening the destination and when the source and destination
1004 files are on the same partition. */
1005 if (x->unlink_dest_before_opening
1006 && S_ISLNK (dst_sb_link->st_mode))
1007 return dst_sb_link->st_dev == src_sb_link->st_dev;
1009 if (x->dereference == DEREF_NEVER)
1011 if ( ! S_ISLNK (src_sb_link->st_mode))
1012 tmp_src_sb = *src_sb_link;
1013 else if (stat (src_name, &tmp_src_sb) != 0)
1014 return true;
1016 if ( ! S_ISLNK (dst_sb_link->st_mode))
1017 tmp_dst_sb = *dst_sb_link;
1018 else if (stat (dst_name, &tmp_dst_sb) != 0)
1019 return true;
1021 if ( ! SAME_INODE (tmp_src_sb, tmp_dst_sb))
1022 return true;
1024 /* FIXME: shouldn't this be testing whether we're making symlinks? */
1025 if (x->hard_link)
1027 *return_now = true;
1028 return true;
1032 return false;
1035 /* Return true if FILE, with mode MODE, is writable in the sense of 'mv'.
1036 Always consider a symbolic link to be writable. */
1037 static bool
1038 writable_destination (char const *file, mode_t mode)
1040 return (S_ISLNK (mode)
1041 || can_write_any_file ()
1042 || euidaccess (file, W_OK) == 0);
1045 static void
1046 overwrite_prompt (char const *dst_name, struct stat const *dst_sb)
1048 if (! writable_destination (dst_name, dst_sb->st_mode))
1050 char perms[12]; /* "-rwxrwxrwx " ls-style modes. */
1051 strmode (dst_sb->st_mode, perms);
1052 perms[10] = '\0';
1053 fprintf (stderr,
1054 _("%s: try to overwrite %s, overriding mode %04lo (%s)? "),
1055 program_name, quote (dst_name),
1056 (unsigned long int) (dst_sb->st_mode & CHMOD_MODE_BITS),
1057 &perms[1]);
1059 else
1061 fprintf (stderr, _("%s: overwrite %s? "),
1062 program_name, quote (dst_name));
1066 /* Initialize the hash table implementing a set of F_triple entries
1067 corresponding to destination files. */
1068 extern void
1069 dest_info_init (struct cp_options *x)
1071 x->dest_info
1072 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
1073 NULL,
1074 triple_hash,
1075 triple_compare,
1076 triple_free);
1079 /* Initialize the hash table implementing a set of F_triple entries
1080 corresponding to source files listed on the command line. */
1081 extern void
1082 src_info_init (struct cp_options *x)
1085 /* Note that we use triple_hash_no_name here.
1086 Contrast with the use of triple_hash above.
1087 That is necessary because a source file may be specified
1088 in many different ways. We want to warn about this
1089 cp a a d/
1090 as well as this:
1091 cp a ./a d/
1093 x->src_info
1094 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
1095 NULL,
1096 triple_hash_no_name,
1097 triple_compare,
1098 triple_free);
1101 /* When effecting a move (e.g., for mv(1)), and given the name DST_NAME
1102 of the destination and a corresponding stat buffer, DST_SB, return
1103 true if the logical `move' operation should _not_ proceed.
1104 Otherwise, return false.
1105 Depending on options specified in X, this code may issue an
1106 interactive prompt asking whether it's ok to overwrite DST_NAME. */
1107 static bool
1108 abandon_move (const struct cp_options *x,
1109 char const *dst_name,
1110 struct stat const *dst_sb)
1112 assert (x->move_mode);
1113 return (x->interactive == I_ALWAYS_NO
1114 || ((x->interactive == I_ASK_USER
1115 || (x->interactive == I_UNSPECIFIED
1116 && x->stdin_tty
1117 && ! writable_destination (dst_name, dst_sb->st_mode)))
1118 && (overwrite_prompt (dst_name, dst_sb), 1)
1119 && ! yesno ()));
1122 /* Print --verbose output on standard output, e.g. `new' -> `old'.
1123 If BACKUP_DST_NAME is non-NULL, then also indicate that it is
1124 the name of a backup file. */
1125 static void
1126 emit_verbose (char const *src, char const *dst, char const *backup_dst_name)
1128 printf ("%s -> %s", quote_n (0, src), quote_n (1, dst));
1129 if (backup_dst_name)
1130 printf (_(" (backup: %s)"), quote (backup_dst_name));
1131 putchar ('\n');
1134 /* A wrapper around "setfscreatecon (NULL)" that exits upon failure. */
1135 static void
1136 restore_default_fscreatecon_or_die (void)
1138 if (setfscreatecon (NULL) != 0)
1139 error (EXIT_FAILURE, errno,
1140 _("failed to restore the default file creation context"));
1143 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
1144 any type. NEW_DST should be true if the file DST_NAME cannot
1145 exist because its parent directory was just created; NEW_DST should
1146 be false if DST_NAME might already exist. DEVICE is the device
1147 number of the parent directory, or 0 if the parent of this file is
1148 not known. ANCESTORS points to a linked, null terminated list of
1149 devices and inodes of parent directories of SRC_NAME. COMMAND_LINE_ARG
1150 is true iff SRC_NAME was specified on the command line.
1151 FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG is both input and output.
1152 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
1153 same as) DST_NAME; otherwise, clear it.
1154 Return true if successful. */
1155 static bool
1156 copy_internal (char const *src_name, char const *dst_name,
1157 bool new_dst,
1158 dev_t device,
1159 struct dir_list *ancestors,
1160 const struct cp_options *x,
1161 bool command_line_arg,
1162 bool *first_dir_created_per_command_line_arg,
1163 bool *copy_into_self,
1164 bool *rename_succeeded)
1166 struct stat src_sb;
1167 struct stat dst_sb;
1168 mode_t src_mode;
1169 mode_t dst_mode IF_LINT (= 0);
1170 mode_t dst_mode_bits;
1171 mode_t omitted_permissions;
1172 bool restore_dst_mode = false;
1173 char *earlier_file = NULL;
1174 char *dst_backup = NULL;
1175 bool backup_succeeded = false;
1176 bool delayed_ok;
1177 bool copied_as_regular = false;
1178 bool preserve_metadata;
1179 bool have_dst_lstat = false;
1181 if (x->move_mode && rename_succeeded)
1182 *rename_succeeded = false;
1184 *copy_into_self = false;
1186 if (XSTAT (x, src_name, &src_sb) != 0)
1188 error (0, errno, _("cannot stat %s"), quote (src_name));
1189 return false;
1192 src_mode = src_sb.st_mode;
1194 if (S_ISDIR (src_mode) && !x->recursive)
1196 error (0, 0, _("omitting directory %s"), quote (src_name));
1197 return false;
1200 /* Detect the case in which the same source file appears more than
1201 once on the command line and no backup option has been selected.
1202 If so, simply warn and don't copy it the second time.
1203 This check is enabled only if x->src_info is non-NULL. */
1204 if (command_line_arg)
1206 if ( ! S_ISDIR (src_sb.st_mode)
1207 && x->backup_type == no_backups
1208 && seen_file (x->src_info, src_name, &src_sb))
1210 error (0, 0, _("warning: source file %s specified more than once"),
1211 quote (src_name));
1212 return true;
1215 record_file (x->src_info, src_name, &src_sb);
1218 if (!new_dst)
1220 /* Regular files can be created by writing through symbolic
1221 links, but other files cannot. So use stat on the
1222 destination when copying a regular file, and lstat otherwise.
1223 However, if we intend to unlink or remove the destination
1224 first, use lstat, since a copy won't actually be made to the
1225 destination in that case. */
1226 bool use_stat =
1227 ((S_ISREG (src_mode)
1228 || (x->copy_as_regular
1229 && ! (S_ISDIR (src_mode) || S_ISLNK (src_mode))))
1230 && ! (x->move_mode || x->symbolic_link || x->hard_link
1231 || x->backup_type != no_backups
1232 || x->unlink_dest_before_opening));
1233 if ((use_stat
1234 ? stat (dst_name, &dst_sb)
1235 : lstat (dst_name, &dst_sb))
1236 != 0)
1238 if (errno != ENOENT)
1240 error (0, errno, _("cannot stat %s"), quote (dst_name));
1241 return false;
1243 else
1245 new_dst = true;
1248 else
1249 { /* Here, we know that dst_name exists, at least to the point
1250 that it is stat'able or lstat'able. */
1251 bool return_now;
1252 bool unlink_src;
1254 have_dst_lstat = !use_stat;
1255 if (! same_file_ok (src_name, &src_sb, dst_name, &dst_sb,
1256 x, &return_now, &unlink_src))
1258 error (0, 0, _("%s and %s are the same file"),
1259 quote_n (0, src_name), quote_n (1, dst_name));
1260 return false;
1263 if (!S_ISDIR (src_mode) && x->update)
1265 /* When preserving time stamps (but not moving within a file
1266 system), don't worry if the destination time stamp is
1267 less than the source merely because of time stamp
1268 truncation. */
1269 int options = ((x->preserve_timestamps
1270 && ! (x->move_mode
1271 && dst_sb.st_dev == src_sb.st_dev))
1272 ? UTIMECMP_TRUNCATE_SOURCE
1273 : 0);
1275 if (0 <= utimecmp (dst_name, &dst_sb, &src_sb, options))
1277 /* We're using --update and the destination is not older
1278 than the source, so do not copy or move. Pretend the
1279 rename succeeded, so the caller (if it's mv) doesn't
1280 end up removing the source file. */
1281 if (rename_succeeded)
1282 *rename_succeeded = true;
1283 return true;
1287 /* When there is an existing destination file, we may end up
1288 returning early, and hence not copying/moving the file.
1289 This may be due to an interactive `negative' reply to the
1290 prompt about the existing file. It may also be due to the
1291 use of the --reply=no option.
1293 cp and mv treat -i and -f differently. */
1294 if (x->move_mode)
1296 if (abandon_move (x, dst_name, &dst_sb)
1297 || (unlink_src && unlink (src_name) == 0))
1299 /* Pretend the rename succeeded, so the caller (mv)
1300 doesn't end up removing the source file. */
1301 if (rename_succeeded)
1302 *rename_succeeded = true;
1303 if (unlink_src && x->verbose)
1304 printf (_("removed %s\n"), quote (src_name));
1305 return true;
1307 if (unlink_src)
1309 error (0, errno, _("cannot remove %s"), quote (src_name));
1310 return false;
1313 else
1315 if (! S_ISDIR (src_mode)
1316 && (x->interactive == I_ALWAYS_NO
1317 || (x->interactive == I_ASK_USER
1318 && (overwrite_prompt (dst_name, &dst_sb), 1)
1319 && ! yesno ())))
1320 return true;
1323 if (return_now)
1324 return true;
1326 if (!S_ISDIR (dst_sb.st_mode))
1328 if (S_ISDIR (src_mode))
1330 if (x->move_mode && x->backup_type != no_backups)
1332 /* Moving a directory onto an existing
1333 non-directory is ok only with --backup. */
1335 else
1337 error (0, 0,
1338 _("cannot overwrite non-directory %s with directory %s"),
1339 quote_n (0, dst_name), quote_n (1, src_name));
1340 return false;
1344 /* Don't let the user destroy their data, even if they try hard:
1345 This mv command must fail (likewise for cp):
1346 rm -rf a b c; mkdir a b c; touch a/f b/f; mv a/f b/f c
1347 Otherwise, the contents of b/f would be lost.
1348 In the case of `cp', b/f would be lost if the user simulated
1349 a move using cp and rm.
1350 Note that it works fine if you use --backup=numbered. */
1351 if (command_line_arg
1352 && x->backup_type != numbered_backups
1353 && seen_file (x->dest_info, dst_name, &dst_sb))
1355 error (0, 0,
1356 _("will not overwrite just-created %s with %s"),
1357 quote_n (0, dst_name), quote_n (1, src_name));
1358 return false;
1362 if (!S_ISDIR (src_mode))
1364 if (S_ISDIR (dst_sb.st_mode))
1366 if (x->move_mode && x->backup_type != no_backups)
1368 /* Moving a non-directory onto an existing
1369 directory is ok only with --backup. */
1371 else
1373 error (0, 0,
1374 _("cannot overwrite directory %s with non-directory"),
1375 quote (dst_name));
1376 return false;
1381 if (x->move_mode)
1383 /* Don't allow user to move a directory onto a non-directory. */
1384 if (S_ISDIR (src_sb.st_mode) && !S_ISDIR (dst_sb.st_mode)
1385 && x->backup_type == no_backups)
1387 error (0, 0,
1388 _("cannot move directory onto non-directory: %s -> %s"),
1389 quote_n (0, src_name), quote_n (0, dst_name));
1390 return false;
1394 if (x->backup_type != no_backups
1395 /* Don't try to back up a destination if the last
1396 component of src_name is "." or "..". */
1397 && ! dot_or_dotdot (last_component (src_name))
1398 /* Create a backup of each destination directory in move mode,
1399 but not in copy mode. FIXME: it might make sense to add an
1400 option to suppress backup creation also for move mode.
1401 That would let one use mv to merge new content into an
1402 existing hierarchy. */
1403 && (x->move_mode || ! S_ISDIR (dst_sb.st_mode)))
1405 char *tmp_backup = find_backup_file_name (dst_name,
1406 x->backup_type);
1408 /* Detect (and fail) when creating the backup file would
1409 destroy the source file. Before, running the commands
1410 cd /tmp; rm -f a a~; : > a; echo A > a~; cp --b=simple a~ a
1411 would leave two zero-length files: a and a~. */
1412 /* FIXME: but simply change e.g., the final a~ to `./a~'
1413 and the source will still be destroyed. */
1414 if (STREQ (tmp_backup, src_name))
1416 const char *fmt;
1417 fmt = (x->move_mode
1418 ? _("backing up %s would destroy source; %s not moved")
1419 : _("backing up %s would destroy source; %s not copied"));
1420 error (0, 0, fmt,
1421 quote_n (0, dst_name),
1422 quote_n (1, src_name));
1423 free (tmp_backup);
1424 return false;
1427 /* FIXME: use fts:
1428 Using alloca for a file name that may be arbitrarily
1429 long is not recommended. In fact, even forming such a name
1430 should be discouraged. Eventually, this code will be rewritten
1431 to use fts, so using alloca here will be less of a problem. */
1432 ASSIGN_STRDUPA (dst_backup, tmp_backup);
1433 free (tmp_backup);
1434 if (rename (dst_name, dst_backup) != 0)
1436 if (errno != ENOENT)
1438 error (0, errno, _("cannot backup %s"), quote (dst_name));
1439 return false;
1441 else
1443 dst_backup = NULL;
1446 else
1448 backup_succeeded = true;
1450 new_dst = true;
1452 else if (! S_ISDIR (dst_sb.st_mode)
1453 /* Never unlink dst_name when in move mode. */
1454 && ! x->move_mode
1455 && (x->unlink_dest_before_opening
1456 || (x->preserve_links && 1 < dst_sb.st_nlink)
1457 || (x->dereference == DEREF_NEVER
1458 && ! S_ISREG (src_sb.st_mode))
1461 if (unlink (dst_name) != 0 && errno != ENOENT)
1463 error (0, errno, _("cannot remove %s"), quote (dst_name));
1464 return false;
1466 new_dst = true;
1467 if (x->verbose)
1468 printf (_("removed %s\n"), quote (dst_name));
1473 /* Ensure we don't try to copy through a symlink that was
1474 created by a prior call to this function. */
1475 if (command_line_arg
1476 && x->dest_info
1477 && ! x->move_mode
1478 && x->backup_type == no_backups)
1480 bool lstat_ok = true;
1481 struct stat tmp_buf;
1482 struct stat *dst_lstat_sb;
1484 /* If we called lstat above, good: use that data.
1485 Otherwise, call lstat here, in case dst_name is a symlink. */
1486 if (have_dst_lstat)
1487 dst_lstat_sb = &dst_sb;
1488 else
1490 if (lstat (dst_name, &tmp_buf) == 0)
1491 dst_lstat_sb = &tmp_buf;
1492 else
1493 lstat_ok = false;
1496 /* Never copy through a symlink we've just created. */
1497 if (lstat_ok
1498 && S_ISLNK (dst_lstat_sb->st_mode)
1499 && seen_file (x->dest_info, dst_name, dst_lstat_sb))
1501 error (0, 0,
1502 _("will not copy %s through just-created symlink %s"),
1503 quote_n (0, src_name), quote_n (1, dst_name));
1504 return false;
1508 /* If the source is a directory, we don't always create the destination
1509 directory. So --verbose should not announce anything until we're
1510 sure we'll create a directory. */
1511 if (x->verbose && !S_ISDIR (src_mode))
1512 emit_verbose (src_name, dst_name, backup_succeeded ? dst_backup : NULL);
1514 /* Associate the destination file name with the source device and inode
1515 so that if we encounter a matching dev/ino pair in the source tree
1516 we can arrange to create a hard link between the corresponding names
1517 in the destination tree.
1519 When using the --link (-l) option, there is no need to take special
1520 measures, because (barring race conditions) files that are hard-linked
1521 in the source tree will also be hard-linked in the destination tree.
1523 Sometimes, when preserving links, we have to record dev/ino even
1524 though st_nlink == 1:
1525 - when in move_mode, since we may be moving a group of N hard-linked
1526 files (via two or more command line arguments) to a different
1527 partition; the links may be distributed among the command line
1528 arguments (possibly hierarchies) so that the link count of
1529 the final, once-linked source file is reduced to 1 when it is
1530 considered below. But in this case (for mv) we don't need to
1531 incur the expense of recording the dev/ino => name mapping; all we
1532 really need is a lookup, to see if the dev/ino pair has already
1533 been copied.
1534 - when using -H and processing a command line argument;
1535 that command line argument could be a symlink pointing to another
1536 command line argument. With `cp -H --preserve=link', we hard-link
1537 those two destination files.
1538 - likewise for -L except that it applies to all files, not just
1539 command line arguments.
1541 Also, with --recursive, record dev/ino of each command-line directory.
1542 We'll use that info to detect this problem: cp -R dir dir. */
1544 if (x->move_mode && src_sb.st_nlink == 1)
1546 earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev);
1548 else if (x->preserve_links
1549 && !x->hard_link
1550 && (1 < src_sb.st_nlink
1551 || (command_line_arg
1552 && x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
1553 || x->dereference == DEREF_ALWAYS))
1555 earlier_file = remember_copied (dst_name, src_sb.st_ino, src_sb.st_dev);
1557 else if (x->recursive && S_ISDIR (src_mode))
1559 if (command_line_arg)
1560 earlier_file = remember_copied (dst_name, src_sb.st_ino, src_sb.st_dev);
1561 else
1562 earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev);
1565 /* Did we copy this inode somewhere else (in this command line argument)
1566 and therefore this is a second hard link to the inode? */
1568 if (earlier_file)
1570 /* Avoid damaging the destination file system by refusing to preserve
1571 hard-linked directories (which are found at least in Netapp snapshot
1572 directories). */
1573 if (S_ISDIR (src_mode))
1575 /* If src_name and earlier_file refer to the same directory entry,
1576 then warn about copying a directory into itself. */
1577 if (same_name (src_name, earlier_file))
1579 error (0, 0, _("cannot copy a directory, %s, into itself, %s"),
1580 quote_n (0, top_level_src_name),
1581 quote_n (1, top_level_dst_name));
1582 *copy_into_self = true;
1583 goto un_backup;
1585 else if (x->dereference == DEREF_ALWAYS)
1587 /* This happens when e.g., encountering a directory for the
1588 second or subsequent time via symlinks when cp is invoked
1589 with -R and -L. E.g.,
1590 rm -rf a b c d; mkdir a b c d; ln -s ../c a; ln -s ../c b;
1591 cp -RL a b d
1594 else
1596 error (0, 0, _("will not create hard link %s to directory %s"),
1597 quote_n (0, dst_name), quote_n (1, earlier_file));
1598 goto un_backup;
1601 else
1603 bool link_failed = (link (earlier_file, dst_name) != 0);
1605 /* If the link failed because of an existing destination,
1606 remove that file and then call link again. */
1607 if (link_failed && errno == EEXIST)
1609 if (unlink (dst_name) != 0)
1611 error (0, errno, _("cannot remove %s"), quote (dst_name));
1612 goto un_backup;
1614 if (x->verbose)
1615 printf (_("removed %s\n"), quote (dst_name));
1616 link_failed = (link (earlier_file, dst_name) != 0);
1619 if (link_failed)
1621 error (0, errno, _("cannot create hard link %s to %s"),
1622 quote_n (0, dst_name), quote_n (1, earlier_file));
1623 goto un_backup;
1626 return true;
1630 if (x->move_mode)
1632 if (rename (src_name, dst_name) == 0)
1634 if (x->verbose && S_ISDIR (src_mode))
1635 emit_verbose (src_name, dst_name,
1636 backup_succeeded ? dst_backup : NULL);
1638 if (rename_succeeded)
1639 *rename_succeeded = true;
1641 if (command_line_arg)
1643 /* Record destination dev/ino/name, so that if we are asked
1644 to overwrite that file again, we can detect it and fail. */
1645 /* It's fine to use the _source_ stat buffer (src_sb) to get the
1646 _destination_ dev/ino, since the rename above can't have
1647 changed those, and `mv' always uses lstat.
1648 We could limit it further by operating
1649 only on non-directories. */
1650 record_file (x->dest_info, dst_name, &src_sb);
1653 return true;
1656 /* FIXME: someday, consider what to do when moving a directory into
1657 itself but when source and destination are on different devices. */
1659 /* This happens when attempting to rename a directory to a
1660 subdirectory of itself. */
1661 if (errno == EINVAL)
1663 /* FIXME: this is a little fragile in that it relies on rename(2)
1664 failing with a specific errno value. Expect problems on
1665 non-POSIX systems. */
1666 error (0, 0, _("cannot move %s to a subdirectory of itself, %s"),
1667 quote_n (0, top_level_src_name),
1668 quote_n (1, top_level_dst_name));
1670 /* Note that there is no need to call forget_created here,
1671 (compare with the other calls in this file) since the
1672 destination directory didn't exist before. */
1674 *copy_into_self = true;
1675 /* FIXME-cleanup: Don't return true here; adjust mv.c accordingly.
1676 The only caller that uses this code (mv.c) ends up setting its
1677 exit status to nonzero when copy_into_self is nonzero. */
1678 return true;
1681 /* WARNING: there probably exist systems for which an inter-device
1682 rename fails with a value of errno not handled here.
1683 If/as those are reported, add them to the condition below.
1684 If this happens to you, please do the following and send the output
1685 to the bug-reporting address (e.g., in the output of cp --help):
1686 touch k; perl -e 'rename "k","/tmp/k" or print "$!(",$!+0,")\n"'
1687 where your current directory is on one partion and /tmp is the other.
1688 Also, please try to find the E* errno macro name corresponding to
1689 the diagnostic and parenthesized integer, and include that in your
1690 e-mail. One way to do that is to run a command like this
1691 find /usr/include/. -type f \
1692 | xargs grep 'define.*\<E[A-Z]*\>.*\<18\>' /dev/null
1693 where you'd replace `18' with the integer in parentheses that
1694 was output from the perl one-liner above.
1695 If necessary, of course, change `/tmp' to some other directory. */
1696 if (errno != EXDEV)
1698 /* There are many ways this can happen due to a race condition.
1699 When something happens between the initial XSTAT and the
1700 subsequent rename, we can get many different types of errors.
1701 For example, if the destination is initially a non-directory
1702 or non-existent, but it is created as a directory, the rename
1703 fails. If two `mv' commands try to rename the same file at
1704 about the same time, one will succeed and the other will fail.
1705 If the permissions on the directory containing the source or
1706 destination file are made too restrictive, the rename will
1707 fail. Etc. */
1708 error (0, errno,
1709 _("cannot move %s to %s"),
1710 quote_n (0, src_name), quote_n (1, dst_name));
1711 forget_created (src_sb.st_ino, src_sb.st_dev);
1712 return false;
1715 /* The rename attempt has failed. Remove any existing destination
1716 file so that a cross-device `mv' acts as if it were really using
1717 the rename syscall. */
1718 if (unlink (dst_name) != 0 && errno != ENOENT)
1720 error (0, errno,
1721 _("inter-device move failed: %s to %s; unable to remove target"),
1722 quote_n (0, src_name), quote_n (1, dst_name));
1723 forget_created (src_sb.st_ino, src_sb.st_dev);
1724 return false;
1727 new_dst = true;
1730 /* If the ownership might change, or if it is a directory (whose
1731 special mode bits may change after the directory is created),
1732 omit some permissions at first, so unauthorized users cannot nip
1733 in before the file is ready. */
1734 dst_mode_bits = (x->set_mode ? x->mode : src_mode) & CHMOD_MODE_BITS;
1735 omitted_permissions =
1736 (dst_mode_bits
1737 & (x->preserve_ownership ? S_IRWXG | S_IRWXO
1738 : S_ISDIR (src_mode) ? S_IWGRP | S_IWOTH
1739 : 0));
1741 delayed_ok = true;
1743 if (x->preserve_security_context)
1745 security_context_t con;
1747 if (0 <= lgetfilecon (src_name, &con))
1749 if (setfscreatecon (con) < 0)
1751 if (!x->reduce_diagnostics)
1752 error (0, errno,
1753 _("failed to set default file creation context to %s"),
1754 quote (con));
1755 if (x->require_preserve_context)
1757 freecon (con);
1758 return false;
1761 freecon (con);
1763 else
1765 if (errno != ENOTSUP && errno != ENODATA)
1767 if (!x->reduce_diagnostics)
1768 error (0, errno,
1769 _("failed to get security context of %s"),
1770 quote (src_name));
1771 if (x->require_preserve_context)
1772 return false;
1777 /* In certain modes (cp's --symbolic-link), and for certain file types
1778 (symlinks and hard links) it doesn't make sense to preserve metadata,
1779 or it's possible to preserve only some of it.
1780 In such cases, set this variable to zero. */
1781 preserve_metadata = true;
1783 if (S_ISDIR (src_mode))
1785 struct dir_list *dir;
1787 /* If this directory has been copied before during the
1788 recursion, there is a symbolic link to an ancestor
1789 directory of the symbolic link. It is impossible to
1790 continue to copy this, unless we've got an infinite disk. */
1792 if (is_ancestor (&src_sb, ancestors))
1794 error (0, 0, _("cannot copy cyclic symbolic link %s"),
1795 quote (src_name));
1796 goto un_backup;
1799 /* Insert the current directory in the list of parents. */
1801 dir = alloca (sizeof *dir);
1802 dir->parent = ancestors;
1803 dir->ino = src_sb.st_ino;
1804 dir->dev = src_sb.st_dev;
1806 if (new_dst || !S_ISDIR (dst_sb.st_mode))
1808 /* POSIX says mkdir's behavior is implementation-defined when
1809 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
1810 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
1811 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
1812 if (mkdir (dst_name, dst_mode_bits & ~omitted_permissions) != 0)
1814 error (0, errno, _("cannot create directory %s"),
1815 quote (dst_name));
1816 goto un_backup;
1819 /* We need search and write permissions to the new directory
1820 for writing the directory's contents. Check if these
1821 permissions are there. */
1823 if (lstat (dst_name, &dst_sb) != 0)
1825 error (0, errno, _("cannot stat %s"), quote (dst_name));
1826 goto un_backup;
1828 else if ((dst_sb.st_mode & S_IRWXU) != S_IRWXU)
1830 /* Make the new directory searchable and writable. */
1832 dst_mode = dst_sb.st_mode;
1833 restore_dst_mode = true;
1835 if (lchmod (dst_name, dst_mode | S_IRWXU) != 0)
1837 error (0, errno, _("setting permissions for %s"),
1838 quote (dst_name));
1839 goto un_backup;
1843 /* Record the created directory's inode and device numbers into
1844 the search structure, so that we can avoid copying it again.
1845 Do this only for the first directory that is created for each
1846 source command line argument. */
1847 if (!*first_dir_created_per_command_line_arg)
1849 remember_copied (dst_name, dst_sb.st_ino, dst_sb.st_dev);
1850 *first_dir_created_per_command_line_arg = true;
1853 if (x->verbose)
1854 emit_verbose (src_name, dst_name, NULL);
1857 /* Decide whether to copy the contents of the directory. */
1858 if (x->one_file_system && device != 0 && device != src_sb.st_dev)
1860 /* Here, we are crossing a file system boundary and cp's -x option
1861 is in effect: so don't copy the contents of this directory. */
1863 else
1865 /* Copy the contents of the directory. Don't just return if
1866 this fails -- otherwise, the failure to read a single file
1867 in a source directory would cause the containing destination
1868 directory not to have owner/perms set properly. */
1869 delayed_ok = copy_dir (src_name, dst_name, new_dst, &src_sb, dir, x,
1870 first_dir_created_per_command_line_arg,
1871 copy_into_self);
1874 else if (x->symbolic_link)
1876 preserve_metadata = false;
1878 if (*src_name != '/')
1880 /* Check that DST_NAME denotes a file in the current directory. */
1881 struct stat dot_sb;
1882 struct stat dst_parent_sb;
1883 char *dst_parent;
1884 bool in_current_dir;
1886 dst_parent = dir_name (dst_name);
1888 in_current_dir = (STREQ (".", dst_parent)
1889 /* If either stat call fails, it's ok not to report
1890 the failure and say dst_name is in the current
1891 directory. Other things will fail later. */
1892 || stat (".", &dot_sb) != 0
1893 || stat (dst_parent, &dst_parent_sb) != 0
1894 || SAME_INODE (dot_sb, dst_parent_sb));
1895 free (dst_parent);
1897 if (! in_current_dir)
1899 error (0, 0,
1900 _("%s: can make relative symbolic links only in current directory"),
1901 quote (dst_name));
1902 goto un_backup;
1905 if (symlink (src_name, dst_name) != 0)
1907 error (0, errno, _("cannot create symbolic link %s to %s"),
1908 quote_n (0, dst_name), quote_n (1, src_name));
1909 goto un_backup;
1913 else if (x->hard_link
1914 #ifdef LINK_FOLLOWS_SYMLINKS
1915 /* A POSIX-conforming link syscall dereferences a symlink, yet cp,
1916 invoked with `--link --no-dereference', should not. Thus, with
1917 a POSIX-conforming link system call, we can't use link() here,
1918 since that would create a hard link to the referent (effectively
1919 dereferencing the symlink), rather than to the symlink itself.
1920 We can approximate the desired behavior by skipping this hard-link
1921 creating block and instead copying the symlink, via the `S_ISLNK'-
1922 copying code below.
1923 When link operates on the symlinks themselves, we use this block
1924 and just call link(). */
1925 && !(S_ISLNK (src_mode) && x->dereference == DEREF_NEVER)
1926 #endif
1929 preserve_metadata = false;
1930 if (link (src_name, dst_name))
1932 error (0, errno, _("cannot create link %s"), quote (dst_name));
1933 goto un_backup;
1936 else if (S_ISREG (src_mode)
1937 || (x->copy_as_regular && !S_ISLNK (src_mode)))
1939 copied_as_regular = true;
1940 /* POSIX says the permission bits of the source file must be
1941 used as the 3rd argument in the open call. Historical
1942 practice passed all the source mode bits to 'open', but the extra
1943 bits were ignored, so it should be the same either way. */
1944 if (! copy_reg (src_name, dst_name, x, src_mode & S_IRWXUGO,
1945 omitted_permissions, &new_dst, &src_sb))
1946 goto un_backup;
1948 else if (S_ISFIFO (src_mode))
1950 /* Use mknod, rather than mkfifo, because the former preserves
1951 the special mode bits of a fifo on Solaris 10, while mkfifo
1952 does not. But fall back on mkfifo, because on some BSD systems,
1953 mknod always fails when asked to create a FIFO. */
1954 if (mknod (dst_name, src_mode & ~omitted_permissions, 0) != 0)
1955 if (mkfifo (dst_name, src_mode & ~S_IFIFO & ~omitted_permissions) != 0)
1957 error (0, errno, _("cannot create fifo %s"), quote (dst_name));
1958 goto un_backup;
1961 else if (S_ISBLK (src_mode) || S_ISCHR (src_mode) || S_ISSOCK (src_mode))
1963 if (mknod (dst_name, src_mode & ~omitted_permissions, src_sb.st_rdev)
1964 != 0)
1966 error (0, errno, _("cannot create special file %s"),
1967 quote (dst_name));
1968 goto un_backup;
1971 else if (S_ISLNK (src_mode))
1973 char *src_link_val = areadlink_with_size (src_name, src_sb.st_size);
1974 if (src_link_val == NULL)
1976 error (0, errno, _("cannot read symbolic link %s"), quote (src_name));
1977 goto un_backup;
1980 if (symlink (src_link_val, dst_name) == 0)
1981 free (src_link_val);
1982 else
1984 int saved_errno = errno;
1985 bool same_link = false;
1986 if (x->update && !new_dst && S_ISLNK (dst_sb.st_mode)
1987 && dst_sb.st_size == strlen (src_link_val))
1989 /* See if the destination is already the desired symlink.
1990 FIXME: This behavior isn't documented, and seems wrong
1991 in some cases, e.g., if the destination symlink has the
1992 wrong ownership, permissions, or time stamps. */
1993 char *dest_link_val =
1994 areadlink_with_size (dst_name, dst_sb.st_size);
1995 if (dest_link_val && STREQ (dest_link_val, src_link_val))
1996 same_link = true;
1997 free (dest_link_val);
1999 free (src_link_val);
2001 if (! same_link)
2003 error (0, saved_errno, _("cannot create symbolic link %s"),
2004 quote (dst_name));
2005 goto un_backup;
2009 if (x->preserve_security_context)
2010 restore_default_fscreatecon_or_die ();
2012 /* There's no need to preserve timestamps or permissions. */
2013 preserve_metadata = false;
2015 if (x->preserve_ownership)
2017 /* Preserve the owner and group of the just-`copied'
2018 symbolic link, if possible. */
2019 if (HAVE_LCHOWN
2020 && lchown (dst_name, src_sb.st_uid, src_sb.st_gid) != 0
2021 && ! chown_failure_ok (x))
2023 error (0, errno, _("failed to preserve ownership for %s"),
2024 dst_name);
2025 goto un_backup;
2027 else
2029 /* Can't preserve ownership of symlinks.
2030 FIXME: maybe give a warning or even error for symlinks
2031 in directories with the sticky bit set -- there, not
2032 preserving owner/group is a potential security problem. */
2036 else
2038 error (0, 0, _("%s has unknown file type"), quote (src_name));
2039 goto un_backup;
2042 if (command_line_arg && x->dest_info)
2044 /* Now that the destination file is very likely to exist,
2045 add its info to the set. */
2046 struct stat sb;
2047 if (lstat (dst_name, &sb) == 0)
2048 record_file (x->dest_info, dst_name, &sb);
2051 if ( ! preserve_metadata)
2052 return true;
2054 if (copied_as_regular)
2055 return delayed_ok;
2057 /* POSIX says that `cp -p' must restore the following:
2058 - permission bits
2059 - setuid, setgid bits
2060 - owner and group
2061 If it fails to restore any of those, we may give a warning but
2062 the destination must not be removed.
2063 FIXME: implement the above. */
2065 /* Adjust the times (and if possible, ownership) for the copy.
2066 chown turns off set[ug]id bits for non-root,
2067 so do the chmod last. */
2069 if (x->preserve_timestamps)
2071 struct timespec timespec[2];
2072 timespec[0] = get_stat_atime (&src_sb);
2073 timespec[1] = get_stat_mtime (&src_sb);
2075 if (utimens (dst_name, timespec) != 0)
2077 error (0, errno, _("preserving times for %s"), quote (dst_name));
2078 if (x->require_preserve)
2079 return false;
2083 /* Avoid calling chown if we know it's not necessary. */
2084 if (x->preserve_ownership
2085 && (new_dst || !SAME_OWNER_AND_GROUP (src_sb, dst_sb)))
2087 switch (set_owner (x, dst_name, -1, &src_sb, new_dst, &dst_sb))
2089 case -1:
2090 return false;
2092 case 0:
2093 src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX);
2094 break;
2098 set_author (dst_name, -1, &src_sb);
2100 if (x->preserve_xattr && ! copy_attr_by_name (src_name, dst_name, x)
2101 && x->require_preserve_xattr)
2102 return false;
2104 if (x->preserve_mode || x->move_mode)
2106 if (copy_acl (src_name, -1, dst_name, -1, src_mode) != 0
2107 && x->require_preserve)
2108 return false;
2110 else if (x->set_mode)
2112 if (set_acl (dst_name, -1, x->mode) != 0)
2113 return false;
2115 else
2117 if (omitted_permissions)
2119 omitted_permissions &= ~ cached_umask ();
2121 if (omitted_permissions && !restore_dst_mode)
2123 /* Permissions were deliberately omitted when the file
2124 was created due to security concerns. See whether
2125 they need to be re-added now. It'd be faster to omit
2126 the lstat, but deducing the current destination mode
2127 is tricky in the presence of implementation-defined
2128 rules for special mode bits. */
2129 if (new_dst && lstat (dst_name, &dst_sb) != 0)
2131 error (0, errno, _("cannot stat %s"), quote (dst_name));
2132 return false;
2134 dst_mode = dst_sb.st_mode;
2135 if (omitted_permissions & ~dst_mode)
2136 restore_dst_mode = true;
2140 if (restore_dst_mode)
2142 if (lchmod (dst_name, dst_mode | omitted_permissions) != 0)
2144 error (0, errno, _("preserving permissions for %s"),
2145 quote (dst_name));
2146 if (x->require_preserve)
2147 return false;
2152 return delayed_ok;
2154 un_backup:
2156 if (x->preserve_security_context)
2157 restore_default_fscreatecon_or_die ();
2159 /* We have failed to create the destination file.
2160 If we've just added a dev/ino entry via the remember_copied
2161 call above (i.e., unless we've just failed to create a hard link),
2162 remove the entry associating the source dev/ino with the
2163 destination file name, so we don't try to `preserve' a link
2164 to a file we didn't create. */
2165 if (earlier_file == NULL)
2166 forget_created (src_sb.st_ino, src_sb.st_dev);
2168 if (dst_backup)
2170 if (rename (dst_backup, dst_name) != 0)
2171 error (0, errno, _("cannot un-backup %s"), quote (dst_name));
2172 else
2174 if (x->verbose)
2175 printf (_("%s -> %s (unbackup)\n"),
2176 quote_n (0, dst_backup), quote_n (1, dst_name));
2179 return false;
2182 static bool
2183 valid_options (const struct cp_options *co)
2185 assert (co != NULL);
2186 assert (VALID_BACKUP_TYPE (co->backup_type));
2187 assert (VALID_SPARSE_MODE (co->sparse_mode));
2188 assert (!(co->hard_link && co->symbolic_link));
2189 return true;
2192 /* Copy the file SRC_NAME to the file DST_NAME. The files may be of
2193 any type. NONEXISTENT_DST should be true if the file DST_NAME
2194 is known not to exist (e.g., because its parent directory was just
2195 created); NONEXISTENT_DST should be false if DST_NAME might already
2196 exist. OPTIONS is ... FIXME-describe
2197 Set *COPY_INTO_SELF if SRC_NAME is a parent of (or the
2198 same as) DST_NAME; otherwise, set clear it.
2199 Return true if successful. */
2201 extern bool
2202 copy (char const *src_name, char const *dst_name,
2203 bool nonexistent_dst, const struct cp_options *options,
2204 bool *copy_into_self, bool *rename_succeeded)
2206 assert (valid_options (options));
2208 /* Record the file names: they're used in case of error, when copying
2209 a directory into itself. I don't like to make these tools do *any*
2210 extra work in the common case when that work is solely to handle
2211 exceptional cases, but in this case, I don't see a way to derive the
2212 top level source and destination directory names where they're used.
2213 An alternative is to use COPY_INTO_SELF and print the diagnostic
2214 from every caller -- but I don't want to do that. */
2215 top_level_src_name = src_name;
2216 top_level_dst_name = dst_name;
2218 bool first_dir_created_per_command_line_arg = false;
2219 return copy_internal (src_name, dst_name, nonexistent_dst, 0, NULL,
2220 options, true,
2221 &first_dir_created_per_command_line_arg,
2222 copy_into_self, rename_succeeded);
2225 /* Set *X to the default options for a value of type struct cp_options. */
2227 extern void
2228 cp_options_default (struct cp_options *x)
2230 memset (x, 0, sizeof *x);
2231 #ifdef PRIV_FILE_CHOWN
2233 priv_set_t *pset = priv_allocset ();
2234 if (!pset)
2235 xalloc_die ();
2236 if (getppriv (PRIV_EFFECTIVE, pset) == 0)
2238 x->chown_privileges = priv_ismember (pset, PRIV_FILE_CHOWN);
2239 x->owner_privileges = priv_ismember (pset, PRIV_FILE_OWNER);
2241 priv_freeset (pset);
2243 #else
2244 x->chown_privileges = x->owner_privileges = (geteuid () == 0);
2245 #endif
2248 /* Return true if it's OK for chown to fail, where errno is
2249 the error number that chown failed with and X is the copying
2250 option set. */
2252 extern bool
2253 chown_failure_ok (struct cp_options const *x)
2255 /* If non-root uses -p, it's ok if we can't preserve ownership.
2256 But root probably wants to know, e.g. if NFS disallows it,
2257 or if the target system doesn't support file ownership. */
2259 return ((errno == EPERM || errno == EINVAL) && !x->chown_privileges);
2262 /* Similarly, return true if it's OK for chmod and similar operations
2263 to fail, where errno is the error number that chmod failed with and
2264 X is the copying option set. */
2266 static bool
2267 owner_failure_ok (struct cp_options const *x)
2269 return ((errno == EPERM || errno == EINVAL) && !x->owner_privileges);
2272 /* Return the user's umask, caching the result. */
2274 extern mode_t
2275 cached_umask (void)
2277 static mode_t mask = (mode_t) -1;
2278 if (mask == (mode_t) -1)
2280 mask = umask (0);
2281 umask (mask);
2283 return mask;