(getloadavg): Use `true', not `1'.
[coreutils.git] / src / copy.c
blobb38b535ae863d49f34d79ec31c2e4b7aa8334de5
1 /* copy.c -- core functions for copying files and directories
2 Copyright (C) 89, 90, 91, 1995-2004 Free Software Foundation.
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.
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, write to the Free Software Foundation,
16 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 /* Extracted from cp.c and librarified by Jim Meyering. */
20 #include <config.h>
21 #include <stdio.h>
22 #include <assert.h>
23 #include <sys/types.h>
25 #if HAVE_HURD_H
26 # include <hurd.h>
27 #endif
29 #include "system.h"
30 #include "backupfile.h"
31 #include "copy.h"
32 #include "cp-hash.h"
33 #include "dirname.h"
34 #include "error.h"
35 #include "full-write.h"
36 #include "hash.h"
37 #include "hash-pjw.h"
38 #include "path-concat.h"
39 #include "quote.h"
40 #include "same.h"
41 #include "savedir.h"
42 #include "utimens.h"
43 #include "xreadlink.h"
45 #define DO_CHOWN(Chown, File, New_uid, New_gid) \
46 (Chown (File, New_uid, New_gid) \
47 /* If non-root uses -p, it's ok if we can't preserve ownership. \
48 But root probably wants to know, e.g. if NFS disallows it, \
49 or if the target system doesn't support file ownership. */ \
50 && ((errno != EPERM && errno != EINVAL) || x->myeuid == 0))
52 #define SAME_OWNER(A, B) ((A).st_uid == (B).st_uid)
53 #define SAME_GROUP(A, B) ((A).st_gid == (B).st_gid)
54 #define SAME_OWNER_AND_GROUP(A, B) (SAME_OWNER (A, B) && SAME_GROUP (A, B))
56 #define UNWRITABLE(File_name, File_mode) \
57 ( /* euidaccess is not meaningful for symlinks */ \
58 ! S_ISLNK (File_mode) \
59 && euidaccess (File_name, W_OK) != 0)
61 struct dir_list
63 struct dir_list *parent;
64 ino_t ino;
65 dev_t dev;
68 /* Describe a just-created or just-renamed destination file. */
69 struct F_triple
71 char *name;
72 ino_t st_ino;
73 dev_t st_dev;
76 /* Initial size of the above hash table. */
77 #define DEST_INFO_INITIAL_CAPACITY 61
79 int euidaccess ();
80 int yesno ();
82 static int copy_internal (const char *src_path, const char *dst_path,
83 int new_dst, dev_t device,
84 struct dir_list *ancestors,
85 const struct cp_options *x,
86 int command_line_arg,
87 int *copy_into_self,
88 int *rename_succeeded);
90 /* Pointers to the file names: they're used in the diagnostic that is issued
91 when we detect the user is trying to copy a directory into itself. */
92 static char const *top_level_src_path;
93 static char const *top_level_dst_path;
95 /* The invocation name of this program. */
96 extern char *program_name;
98 /* Encapsulate selection of the file mode to be applied to
99 new non-directories. */
101 static mode_t
102 get_dest_mode (const struct cp_options *option, mode_t mode)
104 /* In some applications (e.g., install), use precisely the
105 specified mode. */
106 if (option->set_mode)
107 return option->mode;
109 /* Honor the umask for `cp', but not for `mv' or `cp -p'.
110 In addition, `cp' without -p must clear the set-user-ID and set-group-ID
111 bits. POSIX requires it do that when creating new files. */
112 if (!option->move_mode && !option->preserve_mode)
113 mode &= (option->umask_kill & ~(S_ISUID | S_ISGID));
115 return mode;
118 /* FIXME: describe */
119 /* FIXME: rewrite this to use a hash table so we avoid the quadratic
120 performance hit that's probably noticeable only on trees deeper
121 than a few hundred levels. See use of active_dir_map in remove.c */
123 static int
124 is_ancestor (const struct stat *sb, const struct dir_list *ancestors)
126 while (ancestors != 0)
128 if (ancestors->ino == sb->st_ino && ancestors->dev == sb->st_dev)
129 return 1;
130 ancestors = ancestors->parent;
132 return 0;
135 /* Read the contents of the directory SRC_PATH_IN, and recursively
136 copy the contents to DST_PATH_IN. NEW_DST is nonzero if
137 DST_PATH_IN is a directory that was created previously in the
138 recursion. SRC_SB and ANCESTORS describe SRC_PATH_IN.
139 Set *COPY_INTO_SELF to nonzero if SRC_PATH_IN is a parent of
140 (or the same as) DST_PATH_IN; otherwise, set it to zero.
141 Return 0 if successful, -1 if an error occurs. */
143 static int
144 copy_dir (const char *src_path_in, const char *dst_path_in, int new_dst,
145 const struct stat *src_sb, struct dir_list *ancestors,
146 const struct cp_options *x, int *copy_into_self)
148 char *name_space;
149 char *namep;
150 struct cp_options non_command_line_options = *x;
151 int ret = 0;
153 name_space = savedir (src_path_in);
154 if (name_space == NULL)
156 /* This diagnostic is a bit vague because savedir can fail in
157 several different ways. */
158 error (0, errno, _("cannot access %s"), quote (src_path_in));
159 return -1;
162 /* For cp's -H option, dereference command line arguments, but do not
163 dereference symlinks that are found via recursive traversal. */
164 if (x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
165 non_command_line_options.dereference = DEREF_NEVER;
167 namep = name_space;
168 while (*namep != '\0')
170 int local_copy_into_self;
171 char *src_path = path_concat (src_path_in, namep, NULL);
172 char *dst_path = path_concat (dst_path_in, namep, NULL);
174 if (dst_path == NULL || src_path == NULL)
175 xalloc_die ();
177 ret |= copy_internal (src_path, dst_path, new_dst, src_sb->st_dev,
178 ancestors, &non_command_line_options, 0,
179 &local_copy_into_self, NULL);
180 *copy_into_self |= local_copy_into_self;
182 free (dst_path);
183 free (src_path);
185 namep += strlen (namep) + 1;
187 free (name_space);
188 return -ret;
191 /* Copy a regular file from SRC_PATH to DST_PATH.
192 If the source file contains holes, copies holes and blocks of zeros
193 in the source file as holes in the destination file.
194 (Holes are read as zeroes by the `read' system call.)
195 Use DST_MODE as the 3rd argument in the call to open.
196 X provides many option settings.
197 Return 0 if successful, -1 if an error occurred.
198 *NEW_DST is as in copy_internal. SRC_SB is the result
199 of calling xstat (aka stat in this case) on SRC_PATH. */
201 static int
202 copy_reg (const char *src_path, const char *dst_path,
203 const struct cp_options *x, mode_t dst_mode, int *new_dst,
204 struct stat const *src_sb)
206 char *buf;
207 int buf_size;
208 int dest_desc;
209 int source_desc;
210 struct stat sb;
211 struct stat src_open_sb;
212 char *cp;
213 int *ip;
214 int return_val = 0;
215 off_t n_read_total = 0;
216 int last_write_made_hole = 0;
217 int make_holes = (x->sparse_mode == SPARSE_ALWAYS);
219 source_desc = open (src_path, O_RDONLY);
220 if (source_desc < 0)
222 error (0, errno, _("cannot open %s for reading"), quote (src_path));
223 return -1;
226 if (fstat (source_desc, &src_open_sb))
228 error (0, errno, _("cannot fstat %s"), quote (src_path));
229 return_val = -1;
230 goto close_src_desc;
233 /* Compare the source dev/ino from the open file to the incoming,
234 saved ones obtained via a previous call to stat. */
235 if (! SAME_INODE (*src_sb, src_open_sb))
237 error (0, 0,
238 _("skipping file %s, as it was replaced while being copied"),
239 quote (src_path));
240 return_val = -1;
241 goto close_src_desc;
244 /* These semantics are required for cp.
245 The if-block will be taken in move_mode. */
246 if (*new_dst)
248 dest_desc = open (dst_path, O_WRONLY | O_CREAT, dst_mode);
250 else
252 dest_desc = open (dst_path, O_WRONLY | O_TRUNC, dst_mode);
254 if (dest_desc < 0 && x->unlink_dest_after_failed_open)
256 if (unlink (dst_path))
258 error (0, errno, _("cannot remove %s"), quote (dst_path));
259 return_val = -1;
260 goto close_src_desc;
263 /* Tell caller that the destination file was unlinked. */
264 *new_dst = 1;
266 /* Try the open again, but this time with different flags. */
267 dest_desc = open (dst_path, O_WRONLY | O_CREAT, dst_mode);
271 if (dest_desc < 0)
273 error (0, errno, _("cannot create regular file %s"), quote (dst_path));
274 return_val = -1;
275 goto close_src_desc;
278 /* Determine the optimal buffer size. */
280 if (fstat (dest_desc, &sb))
282 error (0, errno, _("cannot fstat %s"), quote (dst_path));
283 return_val = -1;
284 goto close_src_and_dst_desc;
287 buf_size = ST_BLKSIZE (sb);
289 #if HAVE_STRUCT_STAT_ST_BLOCKS
290 if (x->sparse_mode == SPARSE_AUTO && S_ISREG (sb.st_mode))
292 /* Use a heuristic to determine whether SRC_PATH contains any
293 sparse blocks. */
295 if (fstat (source_desc, &sb))
297 error (0, errno, _("cannot fstat %s"), quote (src_path));
298 return_val = -1;
299 goto close_src_and_dst_desc;
302 /* If the file has fewer blocks than would normally
303 be needed for a file of its size, then
304 at least one of the blocks in the file is a hole. */
305 if (S_ISREG (sb.st_mode)
306 && sb.st_size / ST_NBLOCKSIZE > ST_NBLOCKS (sb))
307 make_holes = 1;
309 #endif
311 /* Make a buffer with space for a sentinel at the end. */
313 buf = alloca (buf_size + sizeof (int));
315 for (;;)
317 ssize_t n_read = read (source_desc, buf, buf_size);
318 if (n_read < 0)
320 #ifdef EINTR
321 if (errno == EINTR)
322 continue;
323 #endif
324 error (0, errno, _("reading %s"), quote (src_path));
325 return_val = -1;
326 goto close_src_and_dst_desc;
328 if (n_read == 0)
329 break;
331 n_read_total += n_read;
333 ip = 0;
334 if (make_holes)
336 buf[n_read] = 1; /* Sentinel to stop loop. */
338 /* Find first nonzero *word*, or the word with the sentinel. */
340 ip = (int *) buf;
341 while (*ip++ == 0)
344 /* Find the first nonzero *byte*, or the sentinel. */
346 cp = (char *) (ip - 1);
347 while (*cp++ == 0)
350 /* If we found the sentinel, the whole input block was zero,
351 and we can make a hole. */
353 if (cp > buf + n_read)
355 /* Make a hole. */
356 if (lseek (dest_desc, (off_t) n_read, SEEK_CUR) < 0L)
358 error (0, errno, _("cannot lseek %s"), quote (dst_path));
359 return_val = -1;
360 goto close_src_and_dst_desc;
362 last_write_made_hole = 1;
364 else
365 /* Clear to indicate that a normal write is needed. */
366 ip = 0;
368 if (ip == 0)
370 size_t n = n_read;
371 if (full_write (dest_desc, buf, n) != n)
373 error (0, errno, _("writing %s"), quote (dst_path));
374 return_val = -1;
375 goto close_src_and_dst_desc;
377 last_write_made_hole = 0;
381 /* If the file ends with a `hole', something needs to be written at
382 the end. Otherwise the kernel would truncate the file at the end
383 of the last write operation. */
385 if (last_write_made_hole)
387 #if HAVE_FTRUNCATE
388 /* Write a null character and truncate it again. */
389 if (full_write (dest_desc, "", 1) != 1
390 || ftruncate (dest_desc, n_read_total) < 0)
391 #else
392 /* Seek backwards one character and write a null. */
393 if (lseek (dest_desc, (off_t) -1, SEEK_CUR) < 0L
394 || full_write (dest_desc, "", 1) != 1)
395 #endif
397 error (0, errno, _("writing %s"), quote (dst_path));
398 return_val = -1;
402 close_src_and_dst_desc:
403 if (close (dest_desc) < 0)
405 error (0, errno, _("closing %s"), quote (dst_path));
406 return_val = -1;
408 close_src_desc:
409 if (close (source_desc) < 0)
411 error (0, errno, _("closing %s"), quote (src_path));
412 return_val = -1;
415 return return_val;
418 /* Return nonzero if it's ok that the source and destination
419 files are the `same' by some measure. The goal is to avoid
420 making the `copy' operation remove both copies of the file
421 in that case, while still allowing the user to e.g., move or
422 copy a regular file onto a symlink that points to it.
423 Try to minimize the cost of this function in the common case.
424 Set *RETURN_NOW if we've determined that the caller has no more
425 work to do and should return successfully, right away.
427 Set *UNLINK_SRC if we've determined that the caller wants to do
428 `rename (a, b)' where `a' and `b' are distinct hard links to the same
429 file. In that case, the caller should try to unlink `a' and then return
430 successfully. Ideally, we wouldn't have to do that, and we'd be
431 able to rely on rename to remove the source file. However, POSIX
432 mistakenly requires that such a rename call do *nothing* and return
433 successfully. */
435 static int
436 same_file_ok (const char *src_path, const struct stat *src_sb,
437 const char *dst_path, const struct stat *dst_sb,
438 const struct cp_options *x, int *return_now, int *unlink_src)
440 const struct stat *src_sb_link;
441 const struct stat *dst_sb_link;
442 struct stat tmp_dst_sb;
443 struct stat tmp_src_sb;
445 int same_link;
446 int same = (SAME_INODE (*src_sb, *dst_sb));
448 *return_now = 0;
449 *unlink_src = 0;
451 /* FIXME: this should (at the very least) be moved into the following
452 if-block. More likely, it should be removed, because it inhibits
453 making backups. But removing it will result in a change in behavior
454 that will probably have to be documented -- and tests will have to
455 be updated. */
456 if (same && x->hard_link)
458 *return_now = 1;
459 return 1;
462 if (x->dereference == DEREF_NEVER)
464 same_link = same;
466 /* If both the source and destination files are symlinks (and we'll
467 know this here IFF preserving symlinks (aka xstat == lstat),
468 then it's ok -- as long as they are distinct. */
469 if (S_ISLNK (src_sb->st_mode) && S_ISLNK (dst_sb->st_mode))
470 return ! same_name (src_path, dst_path);
472 src_sb_link = src_sb;
473 dst_sb_link = dst_sb;
475 else
477 if (!same)
478 return 1;
480 if (lstat (dst_path, &tmp_dst_sb)
481 || lstat (src_path, &tmp_src_sb))
482 return 1;
484 src_sb_link = &tmp_src_sb;
485 dst_sb_link = &tmp_dst_sb;
487 same_link = SAME_INODE (*src_sb_link, *dst_sb_link);
489 /* If both are symlinks, then it's ok, but only if the destination
490 will be unlinked before being opened. This is like the test
491 above, but with the addition of the unlink_dest_before_opening
492 conjunct because otherwise, with two symlinks to the same target,
493 we'd end up truncating the source file. */
494 if (S_ISLNK (src_sb_link->st_mode) && S_ISLNK (dst_sb_link->st_mode)
495 && x->unlink_dest_before_opening)
496 return 1;
499 /* The backup code ensures there's a copy, so it's usually ok to
500 remove any destination file. One exception is when both
501 source and destination are the same directory entry. In that
502 case, moving the destination file aside (in making the backup)
503 would also rename the source file and result in an error. */
504 if (x->backup_type != none)
506 if (!same_link)
508 /* In copy mode when dereferencing symlinks, if the source is a
509 symlink and the dest is not, then backing up the destination
510 (moving it aside) would make it a dangling symlink, and the
511 subsequent attempt to open it in copy_reg would fail with
512 a misleading diagnostic. Avoid that by returning zero in
513 that case so the caller can make cp (or mv when it has to
514 resort to reading the source file) fail now. */
516 /* FIXME-note: even with the following kludge, we can still provoke
517 the offending diagnostic. It's just a little harder to do :-)
518 $ rm -f a b c; touch c; ln -s c b; ln -s b a; cp -b a b
519 cp: cannot open `a' for reading: No such file or directory
520 That's misleading, since a subsequent `ls' shows that `a'
521 is still there.
522 One solution would be to open the source file *before* moving
523 aside the destination, but that'd involve a big rewrite. */
524 if ( ! x->move_mode
525 && x->dereference != DEREF_NEVER
526 && S_ISLNK (src_sb_link->st_mode)
527 && ! S_ISLNK (dst_sb_link->st_mode))
528 return 0;
530 return 1;
533 return ! same_name (src_path, dst_path);
536 #if 0
537 /* FIXME: use or remove */
539 /* If we're making a backup, we'll detect the problem case in
540 copy_reg because SRC_PATH will no longer exist. Allowing
541 the test to be deferred lets cp do some useful things.
542 But when creating hardlinks and SRC_PATH is a symlink
543 but DST_PATH is not we must test anyway. */
544 if (x->hard_link
545 || !S_ISLNK (src_sb_link->st_mode)
546 || S_ISLNK (dst_sb_link->st_mode))
547 return 1;
549 if (x->dereference != DEREF_NEVER)
550 return 1;
551 #endif
553 /* They may refer to the same file if we're in move mode and the
554 target is a symlink. That is ok, since we remove any existing
555 destination file before opening it -- via `rename' if they're on
556 the same file system, via `unlink (DST_PATH)' otherwise.
557 It's also ok if they're distinct hard links to the same file. */
558 if (x->move_mode || x->unlink_dest_before_opening)
560 if (S_ISLNK (dst_sb_link->st_mode))
561 return 1;
563 if (same_link
564 && 1 < dst_sb_link->st_nlink
565 && ! same_name (src_path, dst_path))
567 if (x->move_mode)
569 *unlink_src = 1;
570 *return_now = 1;
572 return 1;
576 /* If neither is a symlink, then it's ok as long as they aren't
577 hard links to the same file. */
578 if (!S_ISLNK (src_sb_link->st_mode) && !S_ISLNK (dst_sb_link->st_mode))
580 if (!SAME_INODE (*src_sb_link, *dst_sb_link))
581 return 1;
583 /* If they are the same file, it's ok if we're making hard links. */
584 if (x->hard_link)
586 *return_now = 1;
587 return 1;
591 /* It's ok to remove a destination symlink. But that works only when we
592 unlink before opening the destination and when the source and destination
593 files are on the same partition. */
594 if (x->unlink_dest_before_opening
595 && S_ISLNK (dst_sb_link->st_mode))
596 return dst_sb_link->st_dev == src_sb_link->st_dev;
598 if (x->dereference == DEREF_NEVER)
600 if ( ! S_ISLNK (src_sb_link->st_mode))
601 tmp_src_sb = *src_sb_link;
602 else if (stat (src_path, &tmp_src_sb))
603 return 1;
605 if ( ! S_ISLNK (dst_sb_link->st_mode))
606 tmp_dst_sb = *dst_sb_link;
607 else if (stat (dst_path, &tmp_dst_sb))
608 return 1;
610 if ( ! SAME_INODE (tmp_src_sb, tmp_dst_sb))
611 return 1;
613 /* FIXME: shouldn't this be testing whether we're making symlinks? */
614 if (x->hard_link)
616 *return_now = 1;
617 return 1;
621 return 0;
624 static void
625 overwrite_prompt (char const *dst_path, struct stat const *dst_sb)
627 if (euidaccess (dst_path, W_OK) != 0)
629 fprintf (stderr,
630 _("%s: overwrite %s, overriding mode %04lo? "),
631 program_name, quote (dst_path),
632 (unsigned long) (dst_sb->st_mode & CHMOD_MODE_BITS));
634 else
636 fprintf (stderr, _("%s: overwrite %s? "),
637 program_name, quote (dst_path));
641 /* Hash an F_triple. */
642 static size_t
643 triple_hash (void const *x, size_t table_size)
645 struct F_triple const *p = x;
647 /* Also take the name into account, so that when moving N hard links to the
648 same file (all listed on the command line) all into the same directory,
649 we don't experience any N^2 behavior. */
650 /* FIXME-maybe: is it worth the overhead of doing this
651 just to avoid N^2 in such an unusual case? N would have
652 to be very large to make the N^2 factor noticable, and
653 one would probably encounter a limit on the length of
654 a command line before it became a problem. */
655 size_t tmp = hash_pjw (p->name, table_size);
657 /* Ignoring the device number here should be fine. */
658 return (tmp | p->st_ino) % table_size;
661 /* Hash an F_triple. */
662 static size_t
663 triple_hash_no_name (void const *x, size_t table_size)
665 struct F_triple const *p = x;
667 /* Ignoring the device number here should be fine. */
668 return p->st_ino % table_size;
671 /* Compare two F_triple structs. */
672 static bool
673 triple_compare (void const *x, void const *y)
675 struct F_triple const *a = x;
676 struct F_triple const *b = y;
677 return (SAME_INODE (*a, *b) && same_name (a->name, b->name)) ? true : false;
680 /* Free an F_triple. */
681 static void
682 triple_free (void *x)
684 struct F_triple *a = x;
685 free (a->name);
686 free (a);
689 /* Initialize the hash table implementing a set of F_triple entries
690 corresponding to destination files. */
691 void
692 dest_info_init (struct cp_options *x)
694 x->dest_info
695 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
696 NULL,
697 triple_hash,
698 triple_compare,
699 triple_free);
702 /* Initialize the hash table implementing a set of F_triple entries
703 corresponding to source files listed on the command line. */
704 void
705 src_info_init (struct cp_options *x)
708 /* Note that we use triple_hash_no_name here.
709 Contrast with the use of triple_hash above.
710 That is necessary because a source file may be specified
711 in many different ways. We want to warn about this
712 cp a a d/
713 as well as this:
714 cp a ./a d/
716 x->src_info
717 = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
718 NULL,
719 triple_hash_no_name,
720 triple_compare,
721 triple_free);
724 /* Return nonzero if there is an entry in hash table, HT,
725 for the file described by FILENAME and STATS.
726 Otherwise, return zero. */
727 static int
728 seen_file (Hash_table const *ht, char const *filename,
729 struct stat const *stats)
731 struct F_triple new_ent;
733 if (ht == NULL)
734 return 0;
736 new_ent.name = (char *) filename;
737 new_ent.st_ino = stats->st_ino;
738 new_ent.st_dev = stats->st_dev;
740 return !!hash_lookup (ht, &new_ent);
743 /* Record destination filename, FILENAME, and dev/ino from *STATS,
744 in the hash table, HT. If HT is NULL, return immediately.
745 If STATS is NULL, call lstat on FILENAME to get the device
746 and inode numbers. If that lstat fails, simply return.
747 If memory allocation fails, exit immediately. */
748 static void
749 record_file (Hash_table *ht, char const *filename,
750 struct stat const *stats)
752 struct F_triple *ent;
754 if (ht == NULL)
755 return;
757 ent = xmalloc (sizeof *ent);
758 ent->name = xstrdup (filename);
759 if (stats)
761 ent->st_ino = stats->st_ino;
762 ent->st_dev = stats->st_dev;
764 else
766 struct stat sb;
767 if (lstat (filename, &sb))
768 return;
769 ent->st_ino = sb.st_ino;
770 ent->st_dev = sb.st_dev;
774 struct F_triple *ent_from_table = hash_insert (ht, ent);
775 if (ent_from_table == NULL)
777 /* Insertion failed due to lack of memory. */
778 xalloc_die ();
781 if (ent_from_table != ent)
783 /* There was alread a matching entry in the table, so ENT was
784 not inserted. Free it. */
785 triple_free (ent);
790 /* Copy the file SRC_PATH to the file DST_PATH. The files may be of
791 any type. NEW_DST should be nonzero if the file DST_PATH cannot
792 exist because its parent directory was just created; NEW_DST should
793 be zero if DST_PATH might already exist. DEVICE is the device
794 number of the parent directory, or 0 if the parent of this file is
795 not known. ANCESTORS points to a linked, null terminated list of
796 devices and inodes of parent directories of SRC_PATH. COMMAND_LINE_ARG
797 is nonzero iff SRC_PATH was specified on the command line.
798 Set *COPY_INTO_SELF to nonzero if SRC_PATH is a parent of (or the
799 same as) DST_PATH; otherwise, set it to zero.
800 Return 0 if successful, 1 if an error occurs. */
802 static int
803 copy_internal (const char *src_path, const char *dst_path,
804 int new_dst,
805 dev_t device,
806 struct dir_list *ancestors,
807 const struct cp_options *x,
808 int command_line_arg,
809 int *copy_into_self,
810 int *rename_succeeded)
812 struct stat src_sb;
813 struct stat dst_sb;
814 mode_t src_mode;
815 mode_t src_type;
816 char *earlier_file = NULL;
817 char *dst_backup = NULL;
818 int backup_succeeded = 0;
819 int delayed_fail;
820 int copied_as_regular = 0;
821 int ran_chown = 0;
822 int preserve_metadata;
824 if (x->move_mode && rename_succeeded)
825 *rename_succeeded = 0;
827 *copy_into_self = 0;
829 if (XSTAT (x, src_path, &src_sb))
831 error (0, errno, _("cannot stat %s"), quote (src_path));
832 return 1;
835 src_type = src_sb.st_mode;
837 src_mode = src_sb.st_mode;
839 if (S_ISDIR (src_type) && !x->recursive)
841 error (0, 0, _("omitting directory %s"), quote (src_path));
842 return 1;
845 /* Detect the case in which the same source file appears more than
846 once on the command line and no backup option has been selected.
847 If so, simply warn and don't copy it the second time.
848 This check is enabled only if x->src_info is non-NULL. */
849 if (command_line_arg)
851 if ( ! S_ISDIR (src_sb.st_mode)
852 && x->backup_type == none
853 && seen_file (x->src_info, src_path, &src_sb))
855 error (0, 0, _("warning: source file %s specified more than once"),
856 quote (src_path));
857 return 0;
860 record_file (x->src_info, src_path, &src_sb);
863 if (!new_dst)
865 if (XSTAT (x, dst_path, &dst_sb))
867 if (errno != ENOENT)
869 error (0, errno, _("cannot stat %s"), quote (dst_path));
870 return 1;
872 else
874 new_dst = 1;
877 else
879 int return_now;
880 int unlink_src;
881 int ok = same_file_ok (src_path, &src_sb, dst_path, &dst_sb,
882 x, &return_now, &unlink_src);
883 if (unlink_src)
885 if (unlink (src_path))
887 error (0, errno, _("cannot remove %s"), quote (src_path));
888 return 1;
890 /* Tell the caller that there's no need to remove src_path. */
891 if (rename_succeeded)
892 *rename_succeeded = 1;
895 if (return_now)
896 return 0;
898 if (! ok)
900 error (0, 0, _("%s and %s are the same file"),
901 quote_n (0, src_path), quote_n (1, dst_path));
902 return 1;
905 if (!S_ISDIR (dst_sb.st_mode))
907 if (S_ISDIR (src_type))
909 error (0, 0,
910 _("cannot overwrite non-directory %s with directory %s"),
911 quote_n (0, dst_path), quote_n (1, src_path));
912 return 1;
915 /* Don't let the user destroy their data, even if they try hard:
916 This mv command must fail (likewise for cp):
917 rm -rf a b c; mkdir a b c; touch a/f b/f; mv a/f b/f c
918 Otherwise, the contents of b/f would be lost.
919 In the case of `cp', b/f would be lost if the user simulated
920 a move using cp and rm.
921 Note that it works fine if you use --backup=numbered. */
922 if (command_line_arg
923 && x->backup_type != numbered
924 && seen_file (x->dest_info, dst_path, &dst_sb))
926 error (0, 0,
927 _("will not overwrite just-created %s with %s"),
928 quote_n (0, dst_path), quote_n (1, src_path));
929 return 1;
933 if (!S_ISDIR (src_type))
935 if (S_ISDIR (dst_sb.st_mode))
937 error (0, 0,
938 _("cannot overwrite directory %s with non-directory"),
939 quote (dst_path));
940 return 1;
943 if (x->update && MTIME_CMP (src_sb, dst_sb) <= 0)
945 /* We're using --update and the source file is older
946 than the destination file, so there is no need to
947 copy or move. */
948 /* Pretend the rename succeeded, so the caller (mv)
949 doesn't end up removing the source file. */
950 if (rename_succeeded)
951 *rename_succeeded = 1;
952 return 0;
956 /* When there is an existing destination file, we may end up
957 returning early, and hence not copying/moving the file.
958 This may be due to an interactive `negative' reply to the
959 prompt about the existing file. It may also be due to the
960 use of the --reply=no option. */
961 if (!S_ISDIR (src_type))
963 /* cp and mv treat -i and -f differently. */
964 if (x->move_mode)
966 if ((x->interactive == I_ALWAYS_NO
967 && UNWRITABLE (dst_path, dst_sb.st_mode))
968 || ((x->interactive == I_ASK_USER
969 || (x->interactive == I_UNSPECIFIED
970 && x->stdin_tty
971 && UNWRITABLE (dst_path, dst_sb.st_mode)))
972 && (overwrite_prompt (dst_path, &dst_sb), 1)
973 && ! yesno ()))
975 /* Pretend the rename succeeded, so the caller (mv)
976 doesn't end up removing the source file. */
977 if (rename_succeeded)
978 *rename_succeeded = 1;
979 return 0;
982 else
984 if (x->interactive == I_ALWAYS_NO
985 || (x->interactive == I_ASK_USER
986 && (overwrite_prompt (dst_path, &dst_sb), 1)
987 && ! yesno ()))
989 return 0;
994 if (x->move_mode)
996 /* In move_mode, DEST may not be an existing directory. */
997 if (S_ISDIR (dst_sb.st_mode))
999 error (0, 0, _("cannot overwrite directory %s"),
1000 quote (dst_path));
1001 return 1;
1004 /* Don't allow user to move a directory onto a non-directory. */
1005 if (S_ISDIR (src_sb.st_mode) && !S_ISDIR (dst_sb.st_mode))
1007 error (0, 0,
1008 _("cannot move directory onto non-directory: %s -> %s"),
1009 quote_n (0, src_path), quote_n (0, dst_path));
1010 return 1;
1014 if (x->backup_type != none && !S_ISDIR (dst_sb.st_mode))
1016 char *tmp_backup = find_backup_file_name (dst_path,
1017 x->backup_type);
1018 if (tmp_backup == NULL)
1019 xalloc_die ();
1021 /* Detect (and fail) when creating the backup file would
1022 destroy the source file. Before, running the commands
1023 cd /tmp; rm -f a a~; : > a; echo A > a~; cp --b=simple a~ a
1024 would leave two zero-length files: a and a~. */
1025 /* FIXME: but simply change e.g., the final a~ to `./a~'
1026 and the source will still be destroyed. */
1027 if (STREQ (tmp_backup, src_path))
1029 const char *fmt;
1030 fmt = (x->move_mode
1031 ? _("backing up %s would destroy source; %s not moved")
1032 : _("backing up %s would destroy source; %s not copied"));
1033 error (0, 0, fmt,
1034 quote_n (0, dst_path),
1035 quote_n (1, src_path));
1036 free (tmp_backup);
1037 return 1;
1040 /* Using alloca for a pathname that may be (in theory) arbitrarily
1041 long is not recommended. In fact, even forming such a name
1042 should be discouraged. Eventually, this code will be rewritten
1043 to use fts, so using alloca here will be less of a problem. */
1044 ASSIGN_STRDUPA (dst_backup, tmp_backup);
1045 free (tmp_backup);
1046 if (rename (dst_path, dst_backup))
1048 if (errno != ENOENT)
1050 error (0, errno, _("cannot backup %s"), quote (dst_path));
1051 return 1;
1053 else
1055 dst_backup = NULL;
1058 else
1060 backup_succeeded = 1;
1062 new_dst = 1;
1064 else if (! S_ISDIR (dst_sb.st_mode)
1065 && (x->unlink_dest_before_opening
1066 || (x->dereference == DEREF_NEVER
1067 && ! S_ISREG (src_sb.st_mode))))
1069 if (unlink (dst_path) && errno != ENOENT)
1071 error (0, errno, _("cannot remove %s"), quote (dst_path));
1072 return 1;
1074 new_dst = 1;
1079 /* If the source is a directory, we don't always create the destination
1080 directory. So --verbose should not announce anything until we're
1081 sure we'll create a directory. */
1082 if (x->verbose && !S_ISDIR (src_type))
1084 printf ("%s -> %s", quote_n (0, src_path), quote_n (1, dst_path));
1085 if (backup_succeeded)
1086 printf (_(" (backup: %s)"), quote (dst_backup));
1087 putchar ('\n');
1090 /* Associate the destination path with the source device and inode
1091 so that if we encounter a matching dev/ino pair in the source tree
1092 we can arrange to create a hard link between the corresponding names
1093 in the destination tree.
1095 Sometimes, when preserving links, we have to record dev/ino even
1096 though st_nlink == 1:
1097 - when using -H and processing a command line argument;
1098 that command line argument could be a symlink pointing to another
1099 command line argument. With `cp -H --preserve=link', we hard-link
1100 those two destination files.
1101 - likewise for -L except that it applies to all files, not just
1102 command line arguments.
1104 Also record directory dev/ino when using --recursive. We'll use that
1105 info to detect this problem: cp -R dir dir. FIXME-maybe: ideally,
1106 directory info would be recorded in a separate hash table, since
1107 such entries are useful only while a single command line hierarchy
1108 is being copied -- so that separate table could be cleared between
1109 command line args. Using the same hash table to preserve hard
1110 links means that it may not be cleared. */
1112 if ((x->preserve_links
1113 && (1 < src_sb.st_nlink
1114 || (command_line_arg
1115 && x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
1116 || x->dereference == DEREF_ALWAYS))
1117 || (x->recursive && S_ISDIR (src_type)))
1119 earlier_file = remember_copied (dst_path, src_sb.st_ino, src_sb.st_dev);
1122 /* Did we copy this inode somewhere else (in this command line argument)
1123 and therefore this is a second hard link to the inode? */
1125 if (earlier_file)
1127 /* Avoid damaging the destination filesystem by refusing to preserve
1128 hard-linked directories (which are found at least in Netapp snapshot
1129 directories). */
1130 if (S_ISDIR (src_type))
1132 /* If src_path and earlier_file refer to the same directory entry,
1133 then warn about copying a directory into itself. */
1134 if (same_name (src_path, earlier_file))
1136 error (0, 0, _("cannot copy a directory, %s, into itself, %s"),
1137 quote_n (0, top_level_src_path),
1138 quote_n (1, top_level_dst_path));
1139 *copy_into_self = 1;
1141 else
1143 error (0, 0, _("will not create hard link %s to directory %s"),
1144 quote_n (0, dst_path), quote_n (1, earlier_file));
1147 goto un_backup;
1151 int link_failed;
1153 link_failed = link (earlier_file, dst_path);
1155 /* If the link failed because of an existing destination,
1156 remove that file and then call link again. */
1157 if (link_failed && errno == EEXIST)
1159 if (unlink (dst_path))
1161 error (0, errno, _("cannot remove %s"), quote (dst_path));
1162 goto un_backup;
1164 link_failed = link (earlier_file, dst_path);
1167 if (link_failed)
1169 error (0, errno, _("cannot create hard link %s to %s"),
1170 quote_n (0, dst_path), quote_n (1, earlier_file));
1171 goto un_backup;
1174 return 0;
1178 if (x->move_mode)
1180 if (rename (src_path, dst_path) == 0)
1182 if (x->verbose && S_ISDIR (src_type))
1183 printf ("%s -> %s\n", quote_n (0, src_path), quote_n (1, dst_path));
1184 if (rename_succeeded)
1185 *rename_succeeded = 1;
1187 if (command_line_arg)
1189 /* Record destination dev/ino/filename, so that if we are asked
1190 to overwrite that file again, we can detect it and fail. */
1191 /* It's fine to use the _source_ stat buffer (src_sb) to get the
1192 _destination_ dev/ino, since the rename above can't have
1193 changed those, and `mv' always uses lstat.
1194 We could limit it further by operating
1195 only on non-directories. */
1196 record_file (x->dest_info, dst_path, &src_sb);
1199 return 0;
1202 /* FIXME: someday, consider what to do when moving a directory into
1203 itself but when source and destination are on different devices. */
1205 /* This happens when attempting to rename a directory to a
1206 subdirectory of itself. */
1207 if (errno == EINVAL
1209 /* When src_path is on an NFS file system, some types of
1210 clients, e.g., SunOS4.1.4 and IRIX-5.3, set errno to EIO
1211 instead. Testing for this here risks misinterpreting a real
1212 I/O error as an attempt to move a directory into itself, so
1213 FIXME: consider not doing this. */
1214 || errno == EIO
1216 /* And with SunOS-4.1.4 client and OpenBSD-2.3 server,
1217 we get ENOTEMPTY. */
1218 || errno == ENOTEMPTY)
1220 /* FIXME: this is a little fragile in that it relies on rename(2)
1221 failing with a specific errno value. Expect problems on
1222 non-POSIX systems. */
1223 error (0, 0, _("cannot move %s to a subdirectory of itself, %s"),
1224 quote_n (0, top_level_src_path),
1225 quote_n (1, top_level_dst_path));
1227 /* Note that there is no need to call forget_created here,
1228 (compare with the other calls in this file) since the
1229 destination directory didn't exist before. */
1231 *copy_into_self = 1;
1232 /* FIXME-cleanup: Don't return zero here; adjust mv.c accordingly.
1233 The only caller that uses this code (mv.c) ends up setting its
1234 exit status to nonzero when copy_into_self is nonzero. */
1235 return 0;
1238 /* WARNING: there probably exist systems for which an inter-device
1239 rename fails with a value of errno not handled here.
1240 If/as those are reported, add them to the condition below.
1241 If this happens to you, please do the following and send the output
1242 to the bug-reporting address (e.g., in the output of cp --help):
1243 touch k; perl -e 'rename "k","/tmp/k" or print "$!(",$!+0,")\n"'
1244 where your current directory is on one partion and /tmp is the other.
1245 Also, please try to find the E* errno macro name corresponding to
1246 the diagnostic and parenthesized integer, and include that in your
1247 e-mail. One way to do that is to run a command like this
1248 find /usr/include/. -type f \
1249 | xargs grep 'define.*\<E[A-Z]*\>.*\<18\>' /dev/null
1250 where you'd replace `18' with the integer in parentheses that
1251 was output from the perl one-liner above.
1252 If necessary, of course, change `/tmp' to some other directory. */
1253 if (errno != EXDEV)
1255 /* There are many ways this can happen due to a race condition.
1256 When something happens between the initial xstat and the
1257 subsequent rename, we can get many different types of errors.
1258 For example, if the destination is initially a non-directory
1259 or non-existent, but it is created as a directory, the rename
1260 fails. If two `mv' commands try to rename the same file at
1261 about the same time, one will succeed and the other will fail.
1262 If the permissions on the directory containing the source or
1263 destination file are made too restrictive, the rename will
1264 fail. Etc. */
1265 error (0, errno,
1266 _("cannot move %s to %s"),
1267 quote_n (0, src_path), quote_n (1, dst_path));
1268 forget_created (src_sb.st_ino, src_sb.st_dev);
1269 return 1;
1272 /* The rename attempt has failed. Remove any existing destination
1273 file so that a cross-device `mv' acts as if it were really using
1274 the rename syscall. */
1275 if (unlink (dst_path) && errno != ENOENT)
1277 error (0, errno,
1278 _("inter-device move failed: %s to %s; unable to remove target"),
1279 quote_n (0, src_path), quote_n (1, dst_path));
1280 forget_created (src_sb.st_ino, src_sb.st_dev);
1281 return 1;
1284 new_dst = 1;
1287 delayed_fail = 0;
1289 /* In certain modes (cp's --symbolic-link), and for certain file types
1290 (symlinks and hard links) it doesn't make sense to preserve metadata,
1291 or it's possible to preserve only some of it.
1292 In such cases, set this variable to zero. */
1293 preserve_metadata = 1;
1295 if (S_ISDIR (src_type))
1297 struct dir_list *dir;
1299 /* If this directory has been copied before during the
1300 recursion, there is a symbolic link to an ancestor
1301 directory of the symbolic link. It is impossible to
1302 continue to copy this, unless we've got an infinite disk. */
1304 if (is_ancestor (&src_sb, ancestors))
1306 error (0, 0, _("cannot copy cyclic symbolic link %s"),
1307 quote (src_path));
1308 goto un_backup;
1311 /* Insert the current directory in the list of parents. */
1313 dir = alloca (sizeof *dir);
1314 dir->parent = ancestors;
1315 dir->ino = src_sb.st_ino;
1316 dir->dev = src_sb.st_dev;
1318 if (new_dst || !S_ISDIR (dst_sb.st_mode))
1320 /* Create the new directory writable and searchable, so
1321 we can create new entries in it. */
1323 if (mkdir (dst_path, (src_mode & x->umask_kill) | S_IRWXU))
1325 error (0, errno, _("cannot create directory %s"),
1326 quote (dst_path));
1327 goto un_backup;
1330 /* Insert the created directory's inode and device
1331 numbers into the search structure, so that we can
1332 avoid copying it again. */
1334 if (remember_created (dst_path))
1335 goto un_backup;
1337 if (x->verbose)
1338 printf ("%s -> %s\n", quote_n (0, src_path), quote_n (1, dst_path));
1341 /* Are we crossing a file system boundary? */
1342 if (x->one_file_system && device != 0 && device != src_sb.st_dev)
1343 return 0;
1345 /* Copy the contents of the directory. */
1347 if (copy_dir (src_path, dst_path, new_dst, &src_sb, dir, x,
1348 copy_into_self))
1350 /* Don't just return here -- otherwise, the failure to read a
1351 single file in a source directory would cause the containing
1352 destination directory not to have owner/perms set properly. */
1353 delayed_fail = 1;
1356 #ifdef S_ISLNK
1357 else if (x->symbolic_link)
1359 preserve_metadata = 0;
1361 if (*src_path != '/')
1363 /* Check that DST_PATH denotes a file in the current directory. */
1364 struct stat dot_sb;
1365 struct stat dst_parent_sb;
1366 char *dst_parent;
1367 int in_current_dir;
1369 dst_parent = dir_name (dst_path);
1371 in_current_dir = (STREQ (".", dst_parent)
1372 /* If either stat call fails, it's ok not to report
1373 the failure and say dst_path is in the current
1374 directory. Other things will fail later. */
1375 || stat (".", &dot_sb)
1376 || stat (dst_parent, &dst_parent_sb)
1377 || SAME_INODE (dot_sb, dst_parent_sb));
1378 free (dst_parent);
1380 if (! in_current_dir)
1382 error (0, 0,
1383 _("%s: can make relative symbolic links only in current directory"),
1384 quote (dst_path));
1385 goto un_backup;
1388 if (symlink (src_path, dst_path))
1390 error (0, errno, _("cannot create symbolic link %s to %s"),
1391 quote_n (0, dst_path), quote_n (1, src_path));
1392 goto un_backup;
1395 #endif
1396 else if (x->hard_link)
1398 preserve_metadata = 0;
1399 if (link (src_path, dst_path))
1401 error (0, errno, _("cannot create link %s"), quote (dst_path));
1402 goto un_backup;
1405 else if (S_ISREG (src_type)
1406 || (x->copy_as_regular && !S_ISDIR (src_type)
1407 && !S_ISLNK (src_type)))
1409 copied_as_regular = 1;
1410 /* POSIX says the permission bits of the source file must be
1411 used as the 3rd argument in the open call, but that's not consistent
1412 with historical practice. */
1413 if (copy_reg (src_path, dst_path, x,
1414 get_dest_mode (x, src_mode), &new_dst, &src_sb))
1415 goto un_backup;
1417 else
1418 #ifdef S_ISFIFO
1419 if (S_ISFIFO (src_type))
1421 if (mkfifo (dst_path, get_dest_mode (x, src_mode)))
1423 error (0, errno, _("cannot create fifo %s"), quote (dst_path));
1424 goto un_backup;
1427 else
1428 #endif
1429 if (S_ISBLK (src_type) || S_ISCHR (src_type)
1430 || S_ISSOCK (src_type))
1432 if (mknod (dst_path, get_dest_mode (x, src_mode), src_sb.st_rdev))
1434 error (0, errno, _("cannot create special file %s"),
1435 quote (dst_path));
1436 goto un_backup;
1439 else
1440 #ifdef S_ISLNK
1441 if (S_ISLNK (src_type))
1443 char *src_link_val = xreadlink (src_path);
1444 if (src_link_val == NULL)
1446 error (0, errno, _("cannot read symbolic link %s"), quote (src_path));
1447 goto un_backup;
1450 if (!symlink (src_link_val, dst_path))
1451 free (src_link_val);
1452 else
1454 int saved_errno = errno;
1455 int same_link = 0;
1456 if (x->update && !new_dst && S_ISLNK (dst_sb.st_mode))
1458 /* See if the destination is already the desired symlink. */
1459 size_t src_link_len = strlen (src_link_val);
1460 char *dest_link_val = alloca (src_link_len + 1);
1461 int dest_link_len = readlink (dst_path, dest_link_val,
1462 src_link_len + 1);
1463 if ((size_t) dest_link_len == src_link_len
1464 && strncmp (dest_link_val, src_link_val, src_link_len) == 0)
1465 same_link = 1;
1467 free (src_link_val);
1469 if (! same_link)
1471 error (0, saved_errno, _("cannot create symbolic link %s"),
1472 quote (dst_path));
1473 goto un_backup;
1477 /* There's no need to preserve timestamps or permissions. */
1478 preserve_metadata = 0;
1480 if (x->preserve_ownership)
1482 /* Preserve the owner and group of the just-`copied'
1483 symbolic link, if possible. */
1484 # if HAVE_LCHOWN
1485 if (DO_CHOWN (lchown, dst_path, src_sb.st_uid, src_sb.st_gid))
1487 error (0, errno, _("failed to preserve ownership for %s"),
1488 dst_path);
1489 goto un_backup;
1491 # else
1492 /* Can't preserve ownership of symlinks.
1493 FIXME: maybe give a warning or even error for symlinks
1494 in directories with the sticky bit set -- there, not
1495 preserving owner/group is a potential security problem. */
1496 # endif
1499 else
1500 #endif
1502 error (0, 0, _("%s has unknown file type"), quote (src_path));
1503 goto un_backup;
1506 if (command_line_arg)
1507 record_file (x->dest_info, dst_path, NULL);
1509 if ( ! preserve_metadata)
1510 return 0;
1512 /* POSIX says that `cp -p' must restore the following:
1513 - permission bits
1514 - setuid, setgid bits
1515 - owner and group
1516 If it fails to restore any of those, we may give a warning but
1517 the destination must not be removed.
1518 FIXME: implement the above. */
1520 /* Adjust the times (and if possible, ownership) for the copy.
1521 chown turns off set[ug]id bits for non-root,
1522 so do the chmod last. */
1524 if (x->preserve_timestamps)
1526 struct timespec timespec[2];
1528 timespec[0].tv_sec = src_sb.st_atime;
1529 timespec[0].tv_nsec = TIMESPEC_NS (src_sb.st_atim);
1530 timespec[1].tv_sec = src_sb.st_mtime;
1531 timespec[1].tv_nsec = TIMESPEC_NS (src_sb.st_mtim);
1533 if (utimens (dst_path, timespec))
1535 error (0, errno, _("preserving times for %s"), quote (dst_path));
1536 if (x->require_preserve)
1537 return 1;
1541 /* Avoid calling chown if we know it's not necessary. */
1542 if (x->preserve_ownership
1543 && (new_dst || !SAME_OWNER_AND_GROUP (src_sb, dst_sb)))
1545 ran_chown = 1;
1546 if (DO_CHOWN (chown, dst_path, src_sb.st_uid, src_sb.st_gid))
1548 error (0, errno, _("failed to preserve ownership for %s"),
1549 quote (dst_path));
1550 if (x->require_preserve)
1551 return 1;
1555 #if HAVE_STRUCT_STAT_ST_AUTHOR
1556 /* Preserve the st_author field. */
1558 file_t file = file_name_lookup (dst_path, 0, 0);
1559 if (file == MACH_PORT_NULL)
1560 error (0, errno, _("failed to lookup file %s"), quote (dst_path));
1561 else
1563 error_t err = file_chauthor (file, src_sb.st_author);
1564 if (err)
1565 error (0, err, _("failed to preserve authorship for %s"),
1566 quote (dst_path));
1567 mach_port_deallocate (mach_task_self (), file);
1570 #endif
1572 /* Permissions of newly-created regular files were set upon `open' in
1573 copy_reg. But don't return early if there were any special bits and
1574 we had to run chown, because the chown must have reset those bits. */
1575 if ((new_dst && copied_as_regular)
1576 && !(ran_chown && (src_mode & ~S_IRWXUGO)))
1577 return delayed_fail;
1579 if ((x->preserve_mode || new_dst)
1580 && (x->copy_as_regular || S_ISREG (src_type) || S_ISDIR (src_type)))
1582 if (chmod (dst_path, get_dest_mode (x, src_mode)))
1584 error (0, errno, _("setting permissions for %s"), quote (dst_path));
1585 if (x->set_mode || x->require_preserve)
1586 return 1;
1590 return delayed_fail;
1592 un_backup:
1594 /* We have failed to create the destination file.
1595 If we've just added a dev/ino entry via the remember_copied
1596 call above (i.e., unless we've just failed to create a hard link),
1597 remove the entry associating the source dev/ino with the
1598 destination file name, so we don't try to `preserve' a link
1599 to a file we didn't create. */
1600 if (earlier_file == NULL)
1601 forget_created (src_sb.st_ino, src_sb.st_dev);
1603 if (dst_backup)
1605 if (rename (dst_backup, dst_path))
1606 error (0, errno, _("cannot un-backup %s"), quote (dst_path));
1607 else
1609 if (x->verbose)
1610 printf (_("%s -> %s (unbackup)\n"),
1611 quote_n (0, dst_backup), quote_n (1, dst_path));
1614 return 1;
1617 static int
1618 valid_options (const struct cp_options *co)
1620 assert (co != NULL);
1621 assert (VALID_BACKUP_TYPE (co->backup_type));
1622 assert (VALID_SPARSE_MODE (co->sparse_mode));
1623 return 1;
1626 /* Copy the file SRC_PATH to the file DST_PATH. The files may be of
1627 any type. NONEXISTENT_DST should be nonzero if the file DST_PATH
1628 is known not to exist (e.g., because its parent directory was just
1629 created); NONEXISTENT_DST should be zero if DST_PATH might already
1630 exist. OPTIONS is ... FIXME-describe
1631 Set *COPY_INTO_SELF to nonzero if SRC_PATH is a parent of (or the
1632 same as) DST_PATH; otherwise, set it to zero.
1633 Return 0 if successful, 1 if an error occurs. */
1636 copy (const char *src_path, const char *dst_path,
1637 int nonexistent_dst, const struct cp_options *options,
1638 int *copy_into_self, int *rename_succeeded)
1640 assert (valid_options (options));
1642 /* Record the file names: they're used in case of error, when copying
1643 a directory into itself. I don't like to make these tools do *any*
1644 extra work in the common case when that work is solely to handle
1645 exceptional cases, but in this case, I don't see a way to derive the
1646 top level source and destination directory names where they're used.
1647 An alternative is to use COPY_INTO_SELF and print the diagnostic
1648 from every caller -- but I don't want to do that. */
1649 top_level_src_path = src_path;
1650 top_level_dst_path = dst_path;
1652 return copy_internal (src_path, dst_path, nonexistent_dst, 0, NULL,
1653 options, 1, copy_into_self, rename_succeeded);