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"
36 #include "path-concat.h"
39 #define DO_CHOWN(Chown, File, New_uid, New_gid) \
40 (Chown ((File), (x->myeuid == 0 ? (New_uid) : x->myeuid), (New_gid)) \
41 /* If non-root uses -p, it's ok if we can't preserve ownership. \
42 But root probably wants to know, e.g. if NFS disallows it, \
43 or if the target system doesn't support file ownership. */ \
44 && ((errno != EPERM && errno != EINVAL) || x->myeuid == 0))
48 struct dir_list
*parent
;
57 static int copy_internal
PARAMS ((const char *src_path
, const char *dst_path
,
58 int new_dst
, dev_t device
,
59 struct dir_list
*ancestors
,
60 const struct cp_options
*x
,
63 int *rename_succeeded
));
65 /* The invocation name of this program. */
66 extern char *program_name
;
68 /* Encapsulate selection of the file mode to be applied to
69 new non-directories. */
72 new_nondir_mode (const struct cp_options
*option
, mode_t mode
)
74 /* In some applications (e.g., install), use precisely the
79 /* In others (e.g., cp, mv), apply the user's umask. */
80 return mode
& option
->umask_kill
;
84 /* FIXME: rewrite this to use a hash table so we avoid the quadratic
85 performance hit that's probably noticeable only on trees deeper
86 than a few hundred levels. See use of active_dir_map in remove.c */
89 is_ancestor (const struct stat
*sb
, const struct dir_list
*ancestors
)
91 while (ancestors
!= 0)
93 if (ancestors
->ino
== sb
->st_ino
&& ancestors
->dev
== sb
->st_dev
)
95 ancestors
= ancestors
->parent
;
100 /* Read the contents of the directory SRC_PATH_IN, and recursively
101 copy the contents to DST_PATH_IN. NEW_DST is nonzero if
102 DST_PATH_IN is a directory that was created previously in the
103 recursion. SRC_SB and ANCESTORS describe SRC_PATH_IN.
104 Set *COPY_INTO_SELF to nonzero if SRC_PATH_IN is a parent of
105 (or the same as) DST_PATH_IN; otherwise, set it to zero.
106 Return 0 if successful, -1 if an error occurs. */
109 copy_dir (const char *src_path_in
, const char *dst_path_in
, int new_dst
,
110 const struct stat
*src_sb
, struct dir_list
*ancestors
,
111 const struct cp_options
*x
, int *copy_into_self
)
118 name_space
= savedir (src_path_in
, (unsigned int) src_sb
->st_size
);
123 error (0, errno
, "%s", src_path_in
);
127 error (1, 0, _("virtual memory exhausted"));
131 while (*namep
!= '\0')
133 int local_copy_into_self
;
134 char *src_path
= path_concat (src_path_in
, namep
, NULL
);
135 char *dst_path
= path_concat (dst_path_in
, namep
, NULL
);
137 if (dst_path
== NULL
|| src_path
== NULL
)
138 error (1, 0, _("virtual memory exhausted"));
140 ret
|= copy_internal (src_path
, dst_path
, new_dst
, src_sb
->st_dev
,
141 ancestors
, x
, 0, &local_copy_into_self
, NULL
);
142 *copy_into_self
|= local_copy_into_self
;
144 /* Free the memory for `src_path'. The memory for `dst_path'
145 cannot be deallocated, since it is used to create multiple
150 namep
+= strlen (namep
) + 1;
156 /* Copy a regular file from SRC_PATH to DST_PATH.
157 If the source file contains holes, copies holes and blocks of zeros
158 in the source file as holes in the destination file.
159 (Holes are read as zeroes by the `read' system call.)
160 Return 0 if successful, -1 if an error occurred.
161 FIXME: describe sparse_mode. */
164 copy_reg (const char *src_path
, const char *dst_path
,
165 enum Sparse_type sparse_mode
)
176 off_t n_read_total
= 0;
177 int last_write_made_hole
= 0;
178 int make_holes
= (sparse_mode
== SPARSE_ALWAYS
);
180 source_desc
= open (src_path
, O_RDONLY
);
183 /* If SRC_PATH doesn't exist, then chances are good that the
184 user did something like this `cp --backup foo foo': and foo
185 existed to start with, but copy_internal renamed DST_PATH
186 with the backup suffix, thus also renaming SRC_PATH. */
188 error (0, 0, _("`%s' and `%s' are the same file"),
191 error (0, errno
, "%s", src_path
);
196 /* Create the new regular file with small permissions initially,
197 to not create a security hole. */
199 dest_desc
= open (dst_path
, O_WRONLY
| O_CREAT
| O_TRUNC
, S_IRUSR
| S_IWUSR
);
202 error (0, errno
, _("cannot create regular file `%s'"), dst_path
);
207 /* Find out the optimal buffer size. */
209 if (fstat (dest_desc
, &sb
))
211 error (0, errno
, "%s", dst_path
);
216 buf_size
= ST_BLKSIZE (sb
);
219 if (sparse_mode
== SPARSE_AUTO
&& S_ISREG (sb
.st_mode
))
221 /* Use a heuristic to determine whether SRC_PATH contains any
224 if (fstat (source_desc
, &sb
))
226 error (0, errno
, "%s", src_path
);
231 /* If the file has fewer blocks than would normally
232 be needed for a file of its size, then
233 at least one of the blocks in the file is a hole. */
234 if (S_ISREG (sb
.st_mode
)
235 && sb
.st_size
/ ST_NBLOCKSIZE
> ST_NBLOCKS (sb
))
240 /* Make a buffer with space for a sentinel at the end. */
242 buf
= (char *) alloca (buf_size
+ sizeof (int));
246 n_read
= read (source_desc
, buf
, buf_size
);
253 error (0, errno
, "%s", src_path
);
260 n_read_total
+= n_read
;
265 buf
[n_read
] = 1; /* Sentinel to stop loop. */
267 /* Find first nonzero *word*, or the word with the sentinel. */
273 /* Find the first nonzero *byte*, or the sentinel. */
275 cp
= (char *) (ip
- 1);
279 /* If we found the sentinel, the whole input block was zero,
280 and we can make a hole. */
282 if (cp
> buf
+ n_read
)
285 if (lseek (dest_desc
, (off_t
) n_read
, SEEK_CUR
) < 0L)
287 error (0, errno
, "%s", dst_path
);
291 last_write_made_hole
= 1;
294 /* Clear to indicate that a normal write is needed. */
299 if (full_write (dest_desc
, buf
, n_read
) < 0)
301 error (0, errno
, "%s", dst_path
);
305 last_write_made_hole
= 0;
309 /* If the file ends with a `hole', something needs to be written at
310 the end. Otherwise the kernel would truncate the file at the end
311 of the last write operation. */
313 if (last_write_made_hole
)
316 /* Write a null character and truncate it again. */
317 if (full_write (dest_desc
, "", 1) < 0
318 || ftruncate (dest_desc
, n_read_total
) < 0)
320 /* Seek backwards one character and write a null. */
321 if (lseek (dest_desc
, (off_t
) -1, SEEK_CUR
) < 0L
322 || full_write (dest_desc
, "", 1) < 0)
325 error (0, errno
, "%s", dst_path
);
331 if (close (dest_desc
) < 0)
333 error (0, errno
, "%s", dst_path
);
337 if (close (source_desc
) < 0)
339 error (0, errno
, "%s", src_path
);
346 /* Copy the file SRC_PATH to the file DST_PATH. The files may be of
347 any type. NEW_DST should be nonzero if the file DST_PATH cannot
348 exist because its parent directory was just created; NEW_DST should
349 be zero if DST_PATH might already exist. DEVICE is the device
350 number of the parent directory, or 0 if the parent of this file is
351 not known. ANCESTORS points to a linked, null terminated list of
352 devices and inodes of parent directories of SRC_PATH.
353 Set *COPY_INTO_SELF to nonzero if SRC_PATH is a parent of (or the
354 same as) DST_PATH; otherwise, set it to zero.
355 Return 0 if successful, 1 if an error occurs. */
358 copy_internal (const char *src_path
, const char *dst_path
,
361 struct dir_list
*ancestors
,
362 const struct cp_options
*x
,
365 int *rename_succeeded
)
372 char *dst_backup
= NULL
;
375 if (move_mode
&& rename_succeeded
)
376 *rename_succeeded
= 0;
379 if ((*(x
->xstat
)) (src_path
, &src_sb
))
381 error (0, errno
, "%s", src_path
);
385 /* We wouldn't insert a node unless nlink > 1, except that we need to
386 find created files so as to not copy infinitely if a directory is
387 copied into itself. */
389 earlier_file
= remember_copied (dst_path
, src_sb
.st_ino
, src_sb
.st_dev
);
391 src_mode
= src_sb
.st_mode
;
392 src_type
= src_sb
.st_mode
;
394 if (S_ISDIR (src_type
) && !x
->recursive
)
396 error (0, 0, _("%s: omitting directory"), src_path
);
402 if ((*(x
->xstat
)) (dst_path
, &dst_sb
))
406 error (0, errno
, "%s", dst_path
);
418 /* The destination file exists already. */
420 same
= (SAME_INODE (src_sb
, dst_sb
));
423 /* If we're preserving symlinks (--no-dereference) and either
424 file is a symlink, use stat (not xstat) to see if they refer
428 /* If we'll remove DST_PATH first, then this doesn't matter. */
431 /* Allow them to be the same (and don't set `same') if
432 we're in move mode and the target is a symlink. */
434 && S_ISLNK (dst_sb
.st_mode
))
436 /* If we're making a backup, we'll detect the problem case in
437 copy_reg because SRC_PATH will no longer exist. Allowing
438 the test to be deferred lets cp do some useful things.
439 But when creating hardlinks and SRC_PATH is a symlink
440 but DST_PATH is not we must test anyway. */
441 && (x
->backup_type
== none
443 && S_ISLNK (src_sb
.st_mode
)
444 && !S_ISLNK (dst_sb
.st_mode
)))
446 && (S_ISLNK (dst_sb
.st_mode
) || S_ISLNK (src_sb
.st_mode
)))
450 if (stat (dst_path
, &dst2_sb
) == 0
451 && stat (src_path
, &src2_sb
) == 0
452 && SAME_INODE (src2_sb
, dst2_sb
))
464 if (x
->backup_type
== none
465 && (!x
->force
|| same_name (src_path
, dst_path
)))
467 error (0, 0, _("`%s' and `%s' are the same file"),
473 if (!S_ISDIR (src_type
))
475 if (S_ISDIR (dst_sb
.st_mode
))
478 _("%s: cannot overwrite directory with non-directory"),
483 if (x
->update
&& MTIME_CMP (src_sb
, dst_sb
) <= 0)
487 if (!S_ISDIR (src_type
) && !x
->force
&& x
->interactive
)
489 if (euidaccess (dst_path
, W_OK
) != 0)
492 _("%s: overwrite `%s', overriding mode %04lo? "),
493 program_name
, dst_path
,
494 (unsigned long) (dst_sb
.st_mode
& CHMOD_MODE_BITS
));
498 fprintf (stderr
, _("%s: overwrite `%s'? "),
499 program_name
, dst_path
);
502 return (move_mode
? 1 : 0);
505 /* In move_mode, DEST may not be an existing directory. */
506 if (move_mode
&& S_ISDIR (dst_sb
.st_mode
))
508 error (0, 0, _("%s: cannot overwrite directory"), dst_path
);
512 if (x
->backup_type
!= none
&& !S_ISDIR (dst_sb
.st_mode
))
514 char *tmp_backup
= find_backup_file_name (dst_path
,
516 if (tmp_backup
== NULL
)
517 error (1, 0, _("virtual memory exhausted"));
519 /* Detect (and fail) when creating the backup file would
520 destroy the source file. Before, running the commands
521 cd /tmp; rm -f a a~; : > a; echo A > a~; cp -b -V simple a~ a
522 would leave two zero-length files: a and a~. */
523 if (STREQ (tmp_backup
, src_path
))
527 ? _("backing up `%s' would destroy source; `%s' not moved")
528 : _("backing up `%s' would destroy source; `%s' not copied"));
529 error (0, 0, fmt
, dst_path
, src_path
);
534 dst_backup
= (char *) alloca (strlen (tmp_backup
) + 1);
535 strcpy (dst_backup
, tmp_backup
);
537 if (rename (dst_path
, dst_backup
))
541 error (0, errno
, _("cannot backup `%s'"), dst_path
);
549 /* rename succeeded */
551 printf (_("%s -> %s (backup)\n"), dst_path
, dst_backup
);
557 if (S_ISDIR (dst_sb
.st_mode
))
559 /* Temporarily change mode to allow overwriting. */
560 if (euidaccess (dst_path
, W_OK
| X_OK
) != 0)
562 if (chmod (dst_path
, S_IRWXU
))
564 error (0, errno
, "%s", dst_path
);
573 if (unlink (dst_path
) && errno
!= ENOENT
)
575 error (0, errno
, _("cannot remove old link to `%s'"),
577 if (x
->failed_unlink_is_fatal
)
589 /* If the source is a directory, we don't always create the destination
590 directory. So --verbose should not announce anything until we're
591 sure we'll create a directory. */
592 if (x
->verbose
&& !S_ISDIR (src_type
))
593 printf ("%s -> %s\n", src_path
, dst_path
);
595 /* Did we copy this inode somewhere else (in this command line argument)
596 and therefore this is a second hard link to the inode? */
598 if (!x
->dereference
&& src_sb
.st_nlink
> 1 && earlier_file
)
600 /* Avoid damaging the destination filesystem by refusing to preserve
601 hard-linked directories (which are found at least in Netapp snapshot
603 if (S_ISDIR (src_type
))
605 error (0, 0, _("won't create hard link `%s' to directory `%s'"),
606 dst_path
, earlier_file
);
610 if (link (earlier_file
, dst_path
))
612 error (0, errno
, "%s", dst_path
);
621 if (rename (src_path
, dst_path
) == 0)
623 if (x
->verbose
&& S_ISDIR (src_type
))
624 printf ("%s -> %s\n", src_path
, dst_path
);
625 if (rename_succeeded
)
626 *rename_succeeded
= 1;
630 /* FIXME: someday, consider what to do when moving a directory into
631 itself but when source and destination are on different devices. */
633 /* This happens when attempting to rename a directory to a
634 subdirectory of itself. */
637 /* When src_path is on an NFS file system, some types of
638 clients, e.g., SunOS4.1.4 and IRIX-5.3, set errno to EIO
639 instead. Testing for this here risks misinterpreting a real
640 I/O error as an attempt to move a directory into itself, so
641 FIXME: consider not doing this. */
644 /* And with SunOS-4.1.4 client and OpenBSD-2.3 server,
646 || errno
== ENOTEMPTY
)
648 /* FIXME: this is a little fragile in that it relies on rename(2)
649 failing with a specific errno value. Expect problems on
650 non-POSIX systems. */
655 /* Ignore other types of failure (e.g. EXDEV), since the following
656 code will try to perform a copy, then remove. */
659 if (S_ISDIR (src_type
))
661 struct dir_list
*dir
;
663 /* If this directory has been copied before during the
664 recursion, there is a symbolic link to an ancestor
665 directory of the symbolic link. It is impossible to
666 continue to copy this, unless we've got an infinite disk. */
668 if (is_ancestor (&src_sb
, ancestors
))
670 error (0, 0, _("%s: cannot copy cyclic symbolic link"), src_path
);
674 /* Insert the current directory in the list of parents. */
676 dir
= (struct dir_list
*) alloca (sizeof (struct dir_list
));
677 dir
->parent
= ancestors
;
678 dir
->ino
= src_sb
.st_ino
;
679 dir
->dev
= src_sb
.st_dev
;
681 if (new_dst
|| !S_ISDIR (dst_sb
.st_mode
))
683 /* Create the new directory writable and searchable, so
684 we can create new entries in it. */
686 if (mkdir (dst_path
, (src_mode
& x
->umask_kill
) | S_IRWXU
))
688 error (0, errno
, _("cannot create directory `%s'"), dst_path
);
692 /* Insert the created directory's inode and device
693 numbers into the search structure, so that we can
694 avoid copying it again. */
696 if (remember_created (dst_path
))
700 printf ("%s -> %s\n", src_path
, dst_path
);
703 /* Are we crossing a file system boundary? */
704 if (x
->one_file_system
&& device
!= 0 && device
!= src_sb
.st_dev
)
707 /* Copy the contents of the directory. */
709 if (copy_dir (src_path
, dst_path
, new_dst
, &src_sb
, dir
, x
,
714 else if (x
->symbolic_link
)
716 if (*src_path
!= '/')
718 /* Check that DST_PATH denotes a file in the current directory. */
720 struct stat dst_parent_sb
;
724 dst_parent
= dir_name (dst_path
);
725 if (dst_parent
== NULL
)
726 error (1, 0, _("virtual memory exhausted"));
728 in_current_dir
= (STREQ (".", dst_parent
)
729 /* If either stat call fails, it's ok not to report
730 the failure and say dst_path is in the current
731 directory. Other things will fail later. */
732 || stat (".", &dot_sb
)
733 || stat (dst_parent
, &dst_parent_sb
)
734 || SAME_INODE (dot_sb
, dst_parent_sb
));
737 if (! in_current_dir
)
740 _("%s: can make relative symbolic links only in current directory"),
745 if (symlink (src_path
, dst_path
))
747 error (0, errno
, "%s", dst_path
);
754 else if (x
->hard_link
)
756 if (link (src_path
, dst_path
))
758 error (0, errno
, _("cannot create link `%s'"), dst_path
);
763 else if (S_ISREG (src_type
)
764 || (x
->copy_as_regular
&& !S_ISDIR (src_type
)
766 && !S_ISLNK (src_type
)
770 if (copy_reg (src_path
, dst_path
, x
->sparse_mode
))
775 if (S_ISFIFO (src_type
))
777 if (mkfifo (dst_path
, new_nondir_mode (x
, src_mode
)))
779 error (0, errno
, _("cannot create fifo `%s'"), dst_path
);
785 if (S_ISBLK (src_type
) || S_ISCHR (src_type
)
787 || S_ISSOCK (src_type
)
791 if (mknod (dst_path
, new_nondir_mode (x
, src_mode
), src_sb
.st_rdev
))
793 error (0, errno
, _("cannot create special file `%s'"), dst_path
);
799 if (S_ISLNK (src_type
))
804 link_val
= (char *) alloca (PATH_MAX
+ 2);
805 link_size
= readlink (src_path
, link_val
, PATH_MAX
+ 1);
808 error (0, errno
, _("cannot read symbolic link `%s'"), src_path
);
811 link_val
[link_size
] = '\0';
813 if (symlink (link_val
, dst_path
))
815 error (0, errno
, _("cannot create symbolic link `%s'"), dst_path
);
819 if (x
->preserve_owner_and_group
)
821 /* Preserve the owner and group of the just-`copied'
822 symbolic link, if possible. */
824 if (DO_CHOWN (lchown
, dst_path
, src_sb
.st_uid
, src_sb
.st_gid
))
826 error (0, errno
, _("preserving ownership for %s"), dst_path
);
830 /* Can't preserve ownership of symlinks.
831 FIXME: maybe give a warning or even error for symlinks
832 in directories with the sticky bit set -- there, not
833 preserving owner/group is a potential security problem. */
842 error (0, 0, _("%s: unknown file type"), src_path
);
846 /* POSIX says that `cp -p' must restore the following:
848 - setuid, setgid bits
850 If it fails to restore any of those, we may give a warning but
851 the destination must not be removed.
852 FIXME: implement the above. */
854 /* Adjust the times (and if possible, ownership) for the copy.
855 chown turns off set[ug]id bits for non-root,
856 so do the chmod last. */
858 if (x
->preserve_timestamps
)
862 /* There's currently no interface to set file timestamps with
863 better than 1-second resolution, so discard any fractional
864 part of the source timestamp. */
866 utb
.actime
= src_sb
.st_atime
;
867 utb
.modtime
= src_sb
.st_mtime
;
869 if (utime (dst_path
, &utb
))
871 error (0, errno
, _("preserving times for %s"), dst_path
);
872 if (x
->require_preserve
)
877 if (x
->preserve_owner_and_group
)
879 if (DO_CHOWN (chown
, dst_path
, src_sb
.st_uid
, src_sb
.st_gid
))
881 error (0, errno
, _("preserving ownership for %s"), dst_path
);
882 if (x
->require_preserve
)
889 /* This is so install's -m MODE option works. */
890 if (chmod (dst_path
, x
->mode
))
892 error (0, errno
, _("setting permissions for %s"), dst_path
);
896 else if ((x
->preserve_chmod_bits
|| new_dst
)
897 && (x
->copy_as_regular
|| S_ISREG (src_type
) || S_ISDIR (src_type
)))
899 mode_t dst_mode
= src_mode
;
901 /* Honor the umask for `cp', but not for `mv'. */
903 dst_mode
&= x
->umask_kill
;
905 if (chmod (dst_path
, dst_mode
))
907 error (0, errno
, _("preserving permissions for %s"), dst_path
);
908 if (x
->require_preserve
)
914 /* Reset the temporarily changed mode. */
915 if (chmod (dst_path
, dst_sb
.st_mode
))
917 error (0, errno
, _("restoring permissions of %s"), dst_path
);
927 if (rename (dst_backup
, dst_path
))
928 error (0, errno
, _("cannot un-backup `%s'"), dst_path
);
932 printf (_("%s -> %s (unbackup)\n"), dst_backup
, dst_path
);
939 valid_options (const struct cp_options
*co
)
943 assert (VALID_BACKUP_TYPE (co
->backup_type
));
945 /* FIXME: for some reason this assertion always fails,
946 at least on Solaris2.5.1. Just disable it for now. */
947 /* assert (co->xstat == lstat || co->xstat == stat); */
949 /* Make sure xstat and dereference are consistent. */
952 assert (VALID_SPARSE_MODE (co
->sparse_mode
));
957 /* Copy the file SRC_PATH to the file DST_PATH. The files may be of
958 any type. NONEXISTENT_DST should be nonzero if the file DST_PATH
959 is known not to exist (e.g., because its parent directory was just
960 created); NONEXISTENT_DST should be zero if DST_PATH might already
961 exist. OPTIONS is ... FIXME-describe
962 Set *COPY_INTO_SELF to nonzero if SRC_PATH is a parent of (or the
963 same as) DST_PATH; otherwise, set it to zero.
964 Return 0 if successful, 1 if an error occurs. */
967 copy (const char *src_path
, const char *dst_path
,
968 int nonexistent_dst
, const struct cp_options
*options
,
969 int *copy_into_self
, int *rename_succeeded
)
971 /* move_mode is set to the value from the `options' parameter for the
972 first copy_internal call. For all subsequent calls (if any), it must
974 int move_mode
= options
->move_mode
;
976 assert (valid_options (options
));
977 return copy_internal (src_path
, dst_path
, nonexistent_dst
, 0, NULL
,
978 options
, move_mode
, copy_into_self
, rename_succeeded
);