1 /* copy.c -- core functions for copying files and directories
2 Copyright (C) 89, 90, 91, 1995-1999 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)
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. */
27 #include <sys/types.h>
31 #include "backupfile.h"
35 #include "path-concat.h"
38 #define DO_CHOWN(Chown, File, New_uid, New_gid) \
39 (Chown ((File), (x->myeuid == 0 ? (New_uid) : x->myeuid), (New_gid)) \
40 /* If non-root uses -p, it's ok if we can't preserve ownership. \
41 But root probably wants to know, e.g. if NFS disallows it, \
42 or if the target system doesn't support file ownership. */ \
43 && ((errno != EPERM && errno != EINVAL) || x->myeuid == 0))
47 struct dir_list
*parent
;
56 static int copy_internal
PARAMS ((const char *src_path
, const char *dst_path
,
57 int new_dst
, dev_t device
,
58 struct dir_list
*ancestors
,
59 const struct cp_options
*x
,
62 int *rename_succeeded
));
64 /* The invocation name of this program. */
65 extern char *program_name
;
67 /* Encapsulate selection of the file mode to be applied to
68 new non-directories. */
71 new_nondir_mode (const struct cp_options
*option
, mode_t mode
)
73 /* In some applications (e.g., install), use precisely the
78 /* In others (e.g., cp, mv), apply the user's umask. */
79 return mode
& option
->umask_kill
;
83 /* FIXME: rewrite this to use a hash table so we avoid the quadratic
84 performance hit that's probably noticeable only on trees deeper
85 than a few hundred levels. See use of active_dir_map in remove.c */
88 is_ancestor (const struct stat
*sb
, const struct dir_list
*ancestors
)
90 while (ancestors
!= 0)
92 if (ancestors
->ino
== sb
->st_ino
&& ancestors
->dev
== sb
->st_dev
)
94 ancestors
= ancestors
->parent
;
99 /* Read the contents of the directory SRC_PATH_IN, and recursively
100 copy the contents to DST_PATH_IN. NEW_DST is nonzero if
101 DST_PATH_IN is a directory that was created previously in the
102 recursion. SRC_SB and ANCESTORS describe SRC_PATH_IN.
103 Set *COPY_INTO_SELF to nonzero if SRC_PATH_IN is a parent of
104 (or the same as) DST_PATH_IN; otherwise, set it to zero.
105 Return 0 if successful, -1 if an error occurs. */
108 copy_dir (const char *src_path_in
, const char *dst_path_in
, int new_dst
,
109 const struct stat
*src_sb
, struct dir_list
*ancestors
,
110 const struct cp_options
*x
, int *copy_into_self
)
117 name_space
= savedir (src_path_in
, (unsigned int) src_sb
->st_size
);
122 error (0, errno
, "%s", src_path_in
);
126 error (1, 0, _("virtual memory exhausted"));
130 while (*namep
!= '\0')
132 int local_copy_into_self
;
133 char *src_path
= path_concat (src_path_in
, namep
, NULL
);
134 char *dst_path
= path_concat (dst_path_in
, namep
, NULL
);
136 if (dst_path
== NULL
|| src_path
== NULL
)
137 error (1, 0, _("virtual memory exhausted"));
139 ret
|= copy_internal (src_path
, dst_path
, new_dst
, src_sb
->st_dev
,
140 ancestors
, x
, 0, &local_copy_into_self
, NULL
);
141 *copy_into_self
|= local_copy_into_self
;
143 /* Free the memory for `src_path'. The memory for `dst_path'
144 cannot be deallocated, since it is used to create multiple
149 namep
+= strlen (namep
) + 1;
155 /* Copy a regular file from SRC_PATH to DST_PATH.
156 If the source file contains holes, copies holes and blocks of zeros
157 in the source file as holes in the destination file.
158 (Holes are read as zeroes by the `read' system call.)
159 Return 0 if successful, -1 if an error occurred.
160 FIXME: describe sparse_mode. */
163 copy_reg (const char *src_path
, const char *dst_path
,
164 enum Sparse_type sparse_mode
)
175 off_t n_read_total
= 0;
176 int last_write_made_hole
= 0;
177 int make_holes
= (sparse_mode
== SPARSE_ALWAYS
);
179 source_desc
= open (src_path
, O_RDONLY
);
182 /* If SRC_PATH doesn't exist, then chances are good that the
183 user did something like this `cp --backup foo foo': and foo
184 existed to start with, but copy_internal renamed DST_PATH
185 with the backup suffix, thus also renaming SRC_PATH. */
187 error (0, 0, _("`%s' and `%s' are the same file"),
190 error (0, errno
, "%s", src_path
);
195 /* Create the new regular file with small permissions initially,
196 to not create a security hole. */
198 dest_desc
= open (dst_path
, O_WRONLY
| O_CREAT
| O_TRUNC
, S_IRUSR
| S_IWUSR
);
201 error (0, errno
, _("cannot create regular file `%s'"), dst_path
);
206 /* Find out the optimal buffer size. */
208 if (fstat (dest_desc
, &sb
))
210 error (0, errno
, "%s", dst_path
);
215 buf_size
= ST_BLKSIZE (sb
);
218 if (sparse_mode
== SPARSE_AUTO
&& S_ISREG (sb
.st_mode
))
220 /* Use a heuristic to determine whether SRC_PATH contains any
223 if (fstat (source_desc
, &sb
))
225 error (0, errno
, "%s", src_path
);
230 /* If the file has fewer blocks than would normally
231 be needed for a file of its size, then
232 at least one of the blocks in the file is a hole. */
233 if (S_ISREG (sb
.st_mode
)
234 && sb
.st_size
/ ST_NBLOCKSIZE
> ST_NBLOCKS (sb
))
239 /* Make a buffer with space for a sentinel at the end. */
241 buf
= (char *) alloca (buf_size
+ sizeof (int));
245 n_read
= read (source_desc
, buf
, buf_size
);
252 error (0, errno
, "%s", src_path
);
259 n_read_total
+= n_read
;
264 buf
[n_read
] = 1; /* Sentinel to stop loop. */
266 /* Find first nonzero *word*, or the word with the sentinel. */
272 /* Find the first nonzero *byte*, or the sentinel. */
274 cp
= (char *) (ip
- 1);
278 /* If we found the sentinel, the whole input block was zero,
279 and we can make a hole. */
281 if (cp
> buf
+ n_read
)
284 if (lseek (dest_desc
, (off_t
) n_read
, SEEK_CUR
) < 0L)
286 error (0, errno
, "%s", dst_path
);
290 last_write_made_hole
= 1;
293 /* Clear to indicate that a normal write is needed. */
298 if (full_write (dest_desc
, buf
, n_read
) < 0)
300 error (0, errno
, "%s", dst_path
);
304 last_write_made_hole
= 0;
308 /* If the file ends with a `hole', something needs to be written at
309 the end. Otherwise the kernel would truncate the file at the end
310 of the last write operation. */
312 if (last_write_made_hole
)
315 /* Write a null character and truncate it again. */
316 if (full_write (dest_desc
, "", 1) < 0
317 || ftruncate (dest_desc
, n_read_total
) < 0)
319 /* Seek backwards one character and write a null. */
320 if (lseek (dest_desc
, (off_t
) -1, SEEK_CUR
) < 0L
321 || full_write (dest_desc
, "", 1) < 0)
324 error (0, errno
, "%s", dst_path
);
330 if (close (dest_desc
) < 0)
332 error (0, errno
, "%s", dst_path
);
336 if (close (source_desc
) < 0)
338 error (0, errno
, "%s", src_path
);
345 /* Copy the file SRC_PATH to the file DST_PATH. The files may be of
346 any type. NEW_DST should be nonzero if the file DST_PATH cannot
347 exist because its parent directory was just created; NEW_DST should
348 be zero if DST_PATH might already exist. DEVICE is the device
349 number of the parent directory, or 0 if the parent of this file is
350 not known. ANCESTORS points to a linked, null terminated list of
351 devices and inodes of parent directories of SRC_PATH.
352 Set *COPY_INTO_SELF to nonzero if SRC_PATH is a parent of (or the
353 same as) DST_PATH; otherwise, set it to zero.
354 Return 0 if successful, 1 if an error occurs. */
357 copy_internal (const char *src_path
, const char *dst_path
,
360 struct dir_list
*ancestors
,
361 const struct cp_options
*x
,
364 int *rename_succeeded
)
371 char *dst_backup
= NULL
;
374 if (move_mode
&& rename_succeeded
)
375 *rename_succeeded
= 0;
378 if ((*(x
->xstat
)) (src_path
, &src_sb
))
380 error (0, errno
, "%s", src_path
);
384 /* We wouldn't insert a node unless nlink > 1, except that we need to
385 find created files so as to not copy infinitely if a directory is
386 copied into itself. */
388 earlier_file
= remember_copied (dst_path
, src_sb
.st_ino
, src_sb
.st_dev
);
390 src_mode
= src_sb
.st_mode
;
391 src_type
= src_sb
.st_mode
;
393 if (S_ISDIR (src_type
) && !x
->recursive
)
395 error (0, 0, _("%s: omitting directory"), src_path
);
401 if ((*(x
->xstat
)) (dst_path
, &dst_sb
))
405 error (0, errno
, "%s", dst_path
);
417 /* The destination file exists already. */
419 same
= (SAME_INODE (src_sb
, dst_sb
));
422 /* If we're preserving symlinks (--no-dereference) and either
423 file is a symlink, use stat (not xstat) to see if they refer
427 /* If we'll remove DST_PATH first, then this doesn't matter. */
430 /* Allow them to be the same (and don't set `same') if
431 we're in move mode and the target is a symlink. */
433 && S_ISLNK (dst_sb
.st_mode
))
435 /* If we're making a backup, we'll detect the problem case in
436 copy_reg because SRC_PATH will no longer exist. Allowing
437 the test to be deferred lets cp do some useful things.
438 But when creating hardlinks and SRC_PATH is a symlink
439 but DST_PATH is not we must test anyway. */
440 && (x
->backup_type
== none
442 && S_ISLNK (src_sb
.st_mode
)
443 && !S_ISLNK (dst_sb
.st_mode
)))
445 && (S_ISLNK (dst_sb
.st_mode
) || S_ISLNK (src_sb
.st_mode
)))
449 if (stat (dst_path
, &dst2_sb
) == 0
450 && stat (src_path
, &src2_sb
) == 0
451 && SAME_INODE (src2_sb
, dst2_sb
))
463 if (x
->backup_type
== none
&& !x
->force
)
465 error (0, 0, _("`%s' and `%s' are the same file"),
471 if (!S_ISDIR (src_type
))
473 if (S_ISDIR (dst_sb
.st_mode
))
476 _("%s: cannot overwrite directory with non-directory"),
481 if (x
->update
&& MTIME_CMP (src_sb
, dst_sb
) <= 0)
485 if (!S_ISDIR (src_type
) && !x
->force
&& x
->interactive
)
487 if (euidaccess (dst_path
, W_OK
) != 0)
490 _("%s: overwrite `%s', overriding mode %04lo? "),
491 program_name
, dst_path
,
492 (unsigned long) (dst_sb
.st_mode
& CHMOD_MODE_BITS
));
496 fprintf (stderr
, _("%s: overwrite `%s'? "),
497 program_name
, dst_path
);
500 return (move_mode
? 1 : 0);
503 /* In move_mode, DEST may not be an existing directory. */
504 if (move_mode
&& S_ISDIR (dst_sb
.st_mode
))
506 error (0, 0, _("%s: cannot overwrite directory"), dst_path
);
510 if (x
->backup_type
!= none
&& !S_ISDIR (dst_sb
.st_mode
))
512 char *tmp_backup
= find_backup_file_name (dst_path
,
514 if (tmp_backup
== NULL
)
515 error (1, 0, _("virtual memory exhausted"));
517 /* Detect (and fail) when creating the backup file would
518 destroy the source file. Before, running the commands
519 cd /tmp; rm -f a a~; : > a; echo A > a~; cp -b -V simple a~ a
520 would leave two zero-length files: a and a~. */
521 if (STREQ (tmp_backup
, src_path
))
525 ? _("backing up `%s' would destroy source; `%s' not moved")
526 : _("backing up `%s' would destroy source; `%s' not copied"));
527 error (0, 0, fmt
, dst_path
, src_path
);
532 dst_backup
= (char *) alloca (strlen (tmp_backup
) + 1);
533 strcpy (dst_backup
, tmp_backup
);
535 if (rename (dst_path
, dst_backup
))
539 error (0, errno
, _("cannot backup `%s'"), dst_path
);
547 /* rename succeeded */
549 printf (_("%s -> %s (backup)\n"), dst_path
, dst_backup
);
555 if (S_ISDIR (dst_sb
.st_mode
))
557 /* Temporarily change mode to allow overwriting. */
558 if (euidaccess (dst_path
, W_OK
| X_OK
) != 0)
560 if (chmod (dst_path
, S_IRWXU
))
562 error (0, errno
, "%s", dst_path
);
571 if (unlink (dst_path
) && errno
!= ENOENT
)
573 error (0, errno
, _("cannot remove old link to `%s'"),
575 if (x
->failed_unlink_is_fatal
)
587 /* If the source is a directory, we don't always create the destination
588 directory. So --verbose should not announce anything until we're
589 sure we'll create a directory. */
590 if (x
->verbose
&& !S_ISDIR (src_type
))
591 printf ("%s -> %s\n", src_path
, dst_path
);
593 /* Did we copy this inode somewhere else (in this command line argument)
594 and therefore this is a second hard link to the inode? */
596 if (!x
->dereference
&& src_sb
.st_nlink
> 1 && earlier_file
)
598 /* Avoid damaging the destination filesystem by refusing to preserve
599 hard-linked directories (which are found at least in Netapp snapshot
601 if (S_ISDIR (src_type
))
603 error (0, 0, _("won't create hard link `%s' to directory `%s'"),
604 dst_path
, earlier_file
);
608 if (link (earlier_file
, dst_path
))
610 error (0, errno
, "%s", dst_path
);
619 if (rename (src_path
, dst_path
) == 0)
621 if (x
->verbose
&& S_ISDIR (src_type
))
622 printf ("%s -> %s\n", src_path
, dst_path
);
623 if (rename_succeeded
)
624 *rename_succeeded
= 1;
628 /* FIXME: someday, consider what to do when moving a directory into
629 itself but when source and destination are on different devices. */
631 /* This happens when attempting to rename a directory to a
632 subdirectory of itself. */
635 /* When src_path is on an NFS file system, some types of
636 clients, e.g., SunOS4.1.4 and IRIX-5.3, set errno to EIO
637 instead. Testing for this here risks misinterpreting a real
638 I/O error as an attempt to move a directory into itself, so
639 FIXME: consider not doing this. */
642 /* And with SunOS-4.1.4 client and OpenBSD-2.3 server,
644 || errno
== ENOTEMPTY
)
646 /* FIXME: this is a little fragile in that it relies on rename(2)
647 failing with a specific errno value. Expect problems on
648 non-POSIX systems. */
653 /* Ignore other types of failure (e.g. EXDEV), since the following
654 code will try to perform a copy, then remove. */
657 if (S_ISDIR (src_type
))
659 struct dir_list
*dir
;
661 /* If this directory has been copied before during the
662 recursion, there is a symbolic link to an ancestor
663 directory of the symbolic link. It is impossible to
664 continue to copy this, unless we've got an infinite disk. */
666 if (is_ancestor (&src_sb
, ancestors
))
668 error (0, 0, _("%s: cannot copy cyclic symbolic link"), src_path
);
672 /* Insert the current directory in the list of parents. */
674 dir
= (struct dir_list
*) alloca (sizeof (struct dir_list
));
675 dir
->parent
= ancestors
;
676 dir
->ino
= src_sb
.st_ino
;
677 dir
->dev
= src_sb
.st_dev
;
679 if (new_dst
|| !S_ISDIR (dst_sb
.st_mode
))
681 /* Create the new directory writable and searchable, so
682 we can create new entries in it. */
684 if (mkdir (dst_path
, (src_mode
& x
->umask_kill
) | S_IRWXU
))
686 error (0, errno
, _("cannot create directory `%s'"), dst_path
);
690 /* Insert the created directory's inode and device
691 numbers into the search structure, so that we can
692 avoid copying it again. */
694 if (remember_created (dst_path
))
698 printf ("%s -> %s\n", src_path
, dst_path
);
701 /* Are we crossing a file system boundary? */
702 if (x
->one_file_system
&& device
!= 0 && device
!= src_sb
.st_dev
)
705 /* Copy the contents of the directory. */
707 if (copy_dir (src_path
, dst_path
, new_dst
, &src_sb
, dir
, x
,
712 else if (x
->symbolic_link
)
714 if (*src_path
!= '/')
716 /* Check that DST_PATH denotes a file in the current directory. */
718 struct stat dst_parent_sb
;
722 dst_parent
= dir_name (dst_path
);
723 if (dst_parent
== NULL
)
724 error (1, 0, _("virtual memory exhausted"));
726 in_current_dir
= (STREQ (".", dst_parent
)
727 /* If either stat call fails, it's ok not to report
728 the failure and say dst_path is in the current
729 directory. Other things will fail later. */
730 || stat (".", &dot_sb
)
731 || stat (dst_parent
, &dst_parent_sb
)
732 || SAME_INODE (dot_sb
, dst_parent_sb
));
735 if (! in_current_dir
)
738 _("%s: can make relative symbolic links only in current directory"),
743 if (symlink (src_path
, dst_path
))
745 error (0, errno
, "%s", dst_path
);
752 else if (x
->hard_link
)
754 if (link (src_path
, dst_path
))
756 error (0, errno
, _("cannot create link `%s'"), dst_path
);
761 else if (S_ISREG (src_type
)
762 || (x
->copy_as_regular
&& !S_ISDIR (src_type
)
764 && !S_ISLNK (src_type
)
768 if (copy_reg (src_path
, dst_path
, x
->sparse_mode
))
773 if (S_ISFIFO (src_type
))
775 if (mkfifo (dst_path
, new_nondir_mode (x
, src_mode
)))
777 error (0, errno
, _("cannot create fifo `%s'"), dst_path
);
783 if (S_ISBLK (src_type
) || S_ISCHR (src_type
)
785 || S_ISSOCK (src_type
)
789 if (mknod (dst_path
, new_nondir_mode (x
, src_mode
), src_sb
.st_rdev
))
791 error (0, errno
, _("cannot create special file `%s'"), dst_path
);
797 if (S_ISLNK (src_type
))
802 link_val
= (char *) alloca (PATH_MAX
+ 2);
803 link_size
= readlink (src_path
, link_val
, PATH_MAX
+ 1);
806 error (0, errno
, _("cannot read symbolic link `%s'"), src_path
);
809 link_val
[link_size
] = '\0';
811 if (symlink (link_val
, dst_path
))
813 error (0, errno
, _("cannot create symbolic link `%s'"), dst_path
);
817 if (x
->preserve_owner_and_group
)
819 /* Preserve the owner and group of the just-`copied'
820 symbolic link, if possible. */
822 if (DO_CHOWN (lchown
, dst_path
, src_sb
.st_uid
, src_sb
.st_gid
))
824 error (0, errno
, _("preserving ownership for %s"), dst_path
);
828 /* Can't preserve ownership of symlinks.
829 FIXME: maybe give a warning or even error for symlinks
830 in directories with the sticky bit set -- there, not
831 preserving owner/group is a potential security problem. */
840 error (0, 0, _("%s: unknown file type"), src_path
);
844 /* POSIX says that `cp -p' must restore the following:
846 - setuid, setgid bits
848 If it fails to restore any of those, we may give a warning but
849 the destination must not be removed.
850 FIXME: implement the above. */
852 /* Adjust the times (and if possible, ownership) for the copy.
853 chown turns off set[ug]id bits for non-root,
854 so do the chmod last. */
856 if (x
->preserve_timestamps
)
860 /* There's currently no interface to set file timestamps with
861 better than 1-second resolution, so discard any fractional
862 part of the source timestamp. */
864 utb
.actime
= src_sb
.st_atime
;
865 utb
.modtime
= src_sb
.st_mtime
;
867 if (utime (dst_path
, &utb
))
869 error (0, errno
, _("preserving times for %s"), dst_path
);
870 if (x
->require_preserve
)
875 if (x
->preserve_owner_and_group
)
877 if (DO_CHOWN (chown
, dst_path
, src_sb
.st_uid
, src_sb
.st_gid
))
879 error (0, errno
, _("preserving ownership for %s"), dst_path
);
880 if (x
->require_preserve
)
887 /* This is so install's -m MODE option works. */
888 if (chmod (dst_path
, x
->mode
))
890 error (0, errno
, _("setting permissions for %s"), dst_path
);
894 else if ((x
->preserve_chmod_bits
|| new_dst
)
895 && (x
->copy_as_regular
|| S_ISREG (src_type
) || S_ISDIR (src_type
)))
897 if (chmod (dst_path
, src_mode
& x
->umask_kill
))
899 error (0, errno
, _("preserving permissions for %s"), dst_path
);
900 if (x
->require_preserve
)
906 /* Reset the temporarily changed mode. */
907 if (chmod (dst_path
, dst_sb
.st_mode
))
909 error (0, errno
, _("restoring permissions of %s"), dst_path
);
919 if (rename (dst_backup
, dst_path
))
920 error (0, errno
, _("cannot un-backup `%s'"), dst_path
);
924 printf (_("%s -> %s (unbackup)\n"), dst_backup
, dst_path
);
931 valid_options (const struct cp_options
*co
)
935 assert (VALID_BACKUP_TYPE (co
->backup_type
));
937 /* FIXME: for some reason this assertion always fails,
938 at least on Solaris2.5.1. Just disable it for now. */
939 /* assert (co->xstat == lstat || co->xstat == stat); */
941 /* Make sure xstat and dereference are consistent. */
944 assert (VALID_SPARSE_MODE (co
->sparse_mode
));
949 /* Copy the file SRC_PATH to the file DST_PATH. The files may be of
950 any type. NONEXISTENT_DST should be nonzero if the file DST_PATH
951 is known not to exist (e.g., because its parent directory was just
952 created); NONEXISTENT_DST should be zero if DST_PATH might already
953 exist. OPTIONS is ... FIXME-describe
954 Set *COPY_INTO_SELF to nonzero if SRC_PATH is a parent of (or the
955 same as) DST_PATH; otherwise, set it to zero.
956 Return 0 if successful, 1 if an error occurs. */
959 copy (const char *src_path
, const char *dst_path
,
960 int nonexistent_dst
, const struct cp_options
*options
,
961 int *copy_into_self
, int *rename_succeeded
)
963 /* move_mode is set to the value from the `options' parameter for the
964 first copy_internal call. For all subsequent calls (if any), it must
966 int move_mode
= options
->move_mode
;
968 assert (valid_options (options
));
969 return copy_internal (src_path
, dst_path
, nonexistent_dst
, 0, NULL
,
970 options
, move_mode
, copy_into_self
, rename_succeeded
);