1 /* cp.c -- file copying (main routines)
2 Copyright (C) 89, 90, 91, 95, 1996 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 Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. */
32 #include "backupfile.h"
34 #include "path-concat.h"
36 #ifndef _POSIX_VERSION
40 /* On Linux (from slackware-1.2.13 to 2.0.2?) there is no lchown function.
41 To change ownership of symlinks, you must run chown with an effective
44 # define ROOT_CHOWN_AFFECTS_SYMLINKS
47 #define DO_CHOWN(Chown, File, New_uid, New_gid) \
48 (Chown ((File), (myeuid == 0 ? (New_uid) : myeuid), (New_gid)) \
49 /* If non-root uses -p, it's ok if we can't preserve ownership. \
50 But root probably wants to know, e.g. if NFS disallows it. */ \
51 && (errno != EPERM || myeuid == 0))
53 /* Used by do_copy, make_path_private, and re_protect
54 to keep a list of leading directories whose protections
55 need to be fixed after copying. */
60 struct dir_attr
*next
;
63 /* Control creation of sparse files (files with holes). */
66 /* Never create holes in DEST. */
69 /* This is the default. Use a crude (and sometimes inaccurate)
70 heuristic to determine if SOURCE has holes. If so, try to create
74 /* For every sufficiently long sequence of bytes in SOURCE, try to
75 create a corresponding hole in DEST. There is a performance penalty
76 here because CP has to search for holes in SRC. But if the holes are
77 big enough, that penalty can be offset by the decrease in the amount
78 of data written to disk. */
87 enum backup_type
get_version ();
91 static int do_copy
__P ((int argc
, char **argv
));
92 static int copy
__P ((const char *src_path
, const char *dst_path
, int new_dst
,
93 dev_t device
, struct dir_list
*ancestors
));
94 static int copy_dir
__P ((const char *src_path_in
, const char *dst_path_in
,
95 int new_dst
, const struct stat
*src_sb
,
96 struct dir_list
*ancestors
));
97 static int make_path_private
__P ((const char *const_dirpath
, int src_offset
,
98 int mode
, const char *verbose_fmt_string
,
99 struct dir_attr
**attr_list
, int *new_dst
));
100 static int copy_reg
__P ((const char *src_path
, const char *dst_path
));
101 static int re_protect
__P ((const char *const_dst_path
, int src_offset
,
102 struct dir_attr
*attr_list
));
104 /* Initial number of entries in each hash table entry's table of inodes. */
105 #define INITIAL_HASH_MODULE 100
107 /* Initial number of entries in the inode hash table. */
108 #define INITIAL_ENTRY_TAB_SIZE 70
110 /* The invocation name of this program. */
113 /* A pointer to either lstat or stat, depending on
114 whether dereferencing of symlinks is done. */
115 static int (*xstat
) ();
117 /* If nonzero, copy all files except (directories and, if not dereferencing
118 them, symbolic links,) as if they were regular files. */
119 static int flag_copy_as_regular
= 1;
121 /* If nonzero, dereference symbolic links (copy the files they point to). */
122 static int flag_dereference
= 1;
124 /* If nonzero, remove existing destination nondirectories. */
125 static int flag_force
= 0;
127 /* If nonzero, create hard links instead of copying files.
128 Create destination directories as usual. */
129 static int flag_hard_link
= 0;
131 /* If nonzero, query before overwriting existing destinations
132 with regular files. */
133 static int flag_interactive
= 0;
135 /* If nonzero, the command "cp x/e_file e_dir" uses "e_dir/x/e_file"
136 as its destination instead of the usual "e_dir/e_file." */
137 static int flag_path
= 0;
139 /* If nonzero, give the copies the original files' permissions,
140 ownership, and timestamps. */
141 static int flag_preserve
= 0;
143 /* If nonzero, copy directories recursively and copy special files
144 as themselves rather than copying their contents. */
145 static int flag_recursive
= 0;
147 /* If nonzero, create symbolic links instead of copying files.
148 Create destination directories as usual. */
149 static int flag_symbolic_link
= 0;
151 /* If nonzero, when copying recursively, skip any subdirectories that are
152 on different filesystems from the one we started on. */
153 static int flag_one_file_system
= 0;
155 /* If nonzero, do not copy a nondirectory that has an existing destination
156 with the same or newer modification time. */
157 static int flag_update
= 0;
159 /* If nonzero, display the names of the files before copying them. */
160 static int flag_verbose
= 0;
162 static char const *const sparse_type_string
[] =
164 "never", "auto", "always", 0
167 static enum Sparse_type
const sparse_type
[] =
169 SPARSE_NEVER
, SPARSE_AUTO
, SPARSE_ALWAYS
172 /* Control creation of sparse files. */
173 static int flag_sparse
= SPARSE_AUTO
;
175 /* The error code to return to the system. */
176 static int exit_status
= 0;
178 /* The bits to preserve in created files' modes. */
179 static int umask_kill
;
181 /* This process's effective user ID. */
184 /* If nonzero, display usage information and exit. */
185 static int show_help
;
187 /* If nonzero, print the version on standard output and exit. */
188 static int show_version
;
190 static struct option
const long_opts
[] =
192 {"archive", no_argument
, NULL
, 'a'},
193 {"backup", no_argument
, NULL
, 'b'},
194 {"force", no_argument
, NULL
, 'f'},
195 {"sparse", required_argument
, NULL
, 2},
196 {"interactive", no_argument
, NULL
, 'i'},
197 {"link", no_argument
, NULL
, 'l'},
198 {"no-dereference", no_argument
, &flag_dereference
, 0},
199 {"one-file-system", no_argument
, &flag_one_file_system
, 1},
200 {"parents", no_argument
, &flag_path
, 1},
201 {"path", no_argument
, &flag_path
, 1},
202 {"preserve", no_argument
, &flag_preserve
, 1},
203 {"recursive", no_argument
, NULL
, 'R'},
204 {"suffix", required_argument
, NULL
, 'S'},
205 {"symbolic-link", no_argument
, NULL
, 's'},
206 {"update", no_argument
, &flag_update
, 1},
207 {"verbose", no_argument
, &flag_verbose
, 1},
208 {"version-control", required_argument
, NULL
, 'V'},
209 {"help", no_argument
, &show_help
, 1},
210 {"version", no_argument
, &show_version
, 1},
215 main (int argc
, char **argv
)
218 int make_backups
= 0;
221 program_name
= argv
[0];
222 setlocale (LC_ALL
, "");
223 bindtextdomain (PACKAGE
, LOCALEDIR
);
224 textdomain (PACKAGE
);
228 version
= getenv ("SIMPLE_BACKUP_SUFFIX");
230 simple_backup_suffix
= version
;
231 version
= getenv ("VERSION_CONTROL");
233 /* Find out the current file creation mask, to knock the right bits
234 when using chmod. The creation mask is set to to be liberal, so
235 that created directories can be written, even if it would not
236 have been allowed with the mask this process was started with. */
238 umask_kill
= 0777777 ^ umask (0);
240 while ((c
= getopt_long (argc
, argv
, "abdfilprsuvxPRS:V:", long_opts
,
252 /* --sparse={never,auto,always} */
253 i
= argmatch (optarg
, sparse_type_string
);
256 invalid_arg (_("sparse type"), optarg
, i
);
259 flag_sparse
= sparse_type
[i
];
263 case 'a': /* Like -dpR. */
264 flag_dereference
= 0;
267 flag_copy_as_regular
= 0;
275 flag_dereference
= 0;
280 flag_interactive
= 0;
285 flag_interactive
= 1;
302 flag_copy_as_regular
= 1;
307 flag_copy_as_regular
= 0;
312 flag_symbolic_link
= 1;
314 error (1, 0, _("symbolic links are not supported on this system"));
327 flag_one_file_system
= 1;
331 simple_backup_suffix
= optarg
;
345 printf ("cp (%s) %s\n", GNU_PACKAGE
, VERSION
);
352 if (flag_hard_link
&& flag_symbolic_link
)
354 error (0, 0, _("cannot make both hard and symbolic links"));
359 backup_type
= get_version (version
);
361 if (flag_preserve
== 1)
362 umask_kill
= 0777777;
364 /* The key difference between -d (--no-dereference) and not is the version
365 of `stat' to call. */
367 if (flag_dereference
)
372 /* Allocate space for remembering copied and created files. */
374 hash_init (INITIAL_HASH_MODULE
, INITIAL_ENTRY_TAB_SIZE
);
376 exit_status
|= do_copy (argc
, argv
);
381 /* Scan the arguments, and copy each by calling copy.
382 Return 0 if successful, 1 if any errors occur. */
385 do_copy (int argc
, char **argv
)
394 error (0, 0, _("missing file arguments"));
397 if (optind
>= argc
- 1)
399 error (0, 0, _("missing destination file"));
403 dest
= argv
[argc
- 1];
405 if (lstat (dest
, &sb
))
409 error (0, errno
, "%s", dest
);
419 /* If `dest' is not a symlink to a nonexistent file, use
420 the results of stat instead of lstat, so we can copy files
421 into symlinks to directories. */
422 if (stat (dest
, &sbx
) == 0)
426 if (!new_dst
&& S_ISDIR (sb
.st_mode
))
428 /* cp file1...filen edir
429 Copy the files `file1' through `filen'
430 to the existing directory `edir'. */
437 int parent_exists
= 1; /* True if dirname (dst_path) exists. */
438 struct dir_attr
*attr_list
;
439 char *arg_in_concat
= NULL
;
443 strip_trailing_slashes (arg
);
447 /* Append all of `arg' to `dest'. */
448 dst_path
= path_concat (dest
, arg
, &arg_in_concat
);
449 if (dst_path
== NULL
)
450 error (1, 0, _("virtual memory exhausted"));
452 /* For --parents, we have to make sure that the directory
453 dirname (dst_path) exists. We may have to create a few
454 leading directories. */
455 parent_exists
= !make_path_private (dst_path
,
456 arg_in_concat
- dst_path
,
459 ? "%s -> %s\n" : NULL
),
460 &attr_list
, &new_dst
);
464 /* Append the last component of `arg' to `dest'. */
467 /* For `cp -R source/.. dest', don't copy into `dest/..'. */
468 dst_path
= (STREQ (ap
, "..")
470 : path_concat (dest
, ap
, NULL
));
475 /* make_path_private failed, so don't even attempt the copy. */
480 ret
|= copy (arg
, dst_path
, new_dst
, 0, (struct dir_list
*) 0);
485 ret
|= re_protect (dst_path
, arg_in_concat
- dst_path
,
492 if (optind
== argc
- 1)
497 else if (argc
- optind
== 2)
501 struct stat source_stats
;
506 _("when preserving paths, last argument must be a directory"));
510 source
= argv
[optind
];
512 /* When the force and backup options have been specified and
513 the source and destination are the same name for an existing
514 regular file, convert the user's command, e.g.,
515 `cp --force --backup foo foo' to `cp --force foo fooSUFFIX'
516 where SUFFIX is determined by any version control options used. */
519 && backup_type
!= none
520 && STREQ (source
, dest
)
521 && !new_dst
&& S_ISREG (sb
.st_mode
))
523 new_dest
= find_backup_file_name (dest
);
524 /* Set backup_type to `none' so that the normal backup
525 mechanism is not used when performing the actual copy.
526 backup_type must be set to `none' only *after* the above
527 call to find_backup_file_name -- that function uses
528 backup_type to determine the suffix it applies. */
530 if (new_dest
== NULL
)
531 error (1, 0, _("virtual memory exhausted"));
534 /* When the destination is specified with a trailing slash and the
535 source exists but is not a directory, convert the user's command
536 `cp source dest/' to `cp source dest/basename(source)'. Doing
537 this ensures that the command `cp non-directory file/' will now
538 fail rather than performing the copy. COPY diagnoses the case of
539 `cp directory non-directory'. */
541 else if (dest
[strlen (dest
) - 1] == '/'
542 && lstat (source
, &source_stats
) == 0
543 && !S_ISDIR (source_stats
.st_mode
))
548 tmp_source
= (char *) alloca (strlen (source
) + 1);
549 strcpy (tmp_source
, source
);
550 strip_trailing_slashes (tmp_source
);
551 source_base
= basename (tmp_source
);
553 new_dest
= (char *) alloca (strlen (dest
)
554 + strlen (source_base
) + 1);
555 stpcpy (stpcpy (new_dest
, dest
), source_base
);
562 return copy (source
, new_dest
, new_dst
, 0, (struct dir_list
*) 0);
567 _("copying multiple files, but last argument (%s) \
568 is not a directory"),
574 /* Copy the file SRC_PATH to the file DST_PATH. The files may be of
575 any type. NEW_DST should be nonzero if the file DST_PATH cannot
576 exist because its parent directory was just created; NEW_DST should
577 be zero if DST_PATH might already exist. DEVICE is the device
578 number of the parent directory, or 0 if the parent of this file is
579 not known. ANCESTORS points to a linked, null terminated list of
580 devices and inodes of parent directories of SRC_PATH.
581 Return 0 if successful, 1 if an error occurs. */
584 copy (const char *src_path
, const char *dst_path
, int new_dst
, dev_t device
,
585 struct dir_list
*ancestors
)
592 char *dst_backup
= NULL
;
595 if ((*xstat
) (src_path
, &src_sb
))
597 error (0, errno
, "%s", src_path
);
601 /* Are we crossing a file system boundary? */
602 if (flag_one_file_system
&& device
!= 0 && device
!= src_sb
.st_dev
)
605 /* We wouldn't insert a node unless nlink > 1, except that we need to
606 find created files so as to not copy infinitely if a directory is
607 copied into itself. */
609 earlier_file
= remember_copied (dst_path
, src_sb
.st_ino
, src_sb
.st_dev
);
611 /* Did we just create this file? */
613 if (earlier_file
== &new_file
)
616 src_mode
= src_sb
.st_mode
;
617 src_type
= src_sb
.st_mode
;
619 if (S_ISDIR (src_type
) && !flag_recursive
)
621 error (0, 0, _("%s: omitting directory"), src_path
);
627 if ((*xstat
) (dst_path
, &dst_sb
))
631 error (0, errno
, "%s", dst_path
);
639 /* The file exists already. */
641 if (src_sb
.st_ino
== dst_sb
.st_ino
&& src_sb
.st_dev
== dst_sb
.st_dev
)
646 error (0, 0, _("`%s' and `%s' are the same file"),
651 if (!S_ISDIR (src_type
))
653 if (S_ISDIR (dst_sb
.st_mode
))
656 _("%s: cannot overwrite directory with non-directory"),
661 if (flag_update
&& src_sb
.st_mtime
<= dst_sb
.st_mtime
)
665 if (!S_ISDIR (src_type
) && !flag_force
&& flag_interactive
)
667 if (euidaccess (dst_path
, W_OK
) != 0)
670 _("%s: overwrite `%s', overriding mode %04o? "),
671 program_name
, dst_path
,
672 (unsigned int) (dst_sb
.st_mode
& 07777));
676 fprintf (stderr
, _("%s: overwrite `%s'? "),
677 program_name
, dst_path
);
683 if (backup_type
!= none
&& !S_ISDIR (dst_sb
.st_mode
))
685 char *tmp_backup
= find_backup_file_name (dst_path
);
686 if (tmp_backup
== NULL
)
687 error (1, 0, _("virtual memory exhausted"));
689 /* Detect (and fail) when creating the backup file would
690 destroy the source file. Before, running the commands
691 cd /tmp; rm -f a a~; : > a; echo A > a~; cp -b -V simple a~ a
692 would leave two zero-length files: a and a~. */
693 if (STREQ (tmp_backup
, src_path
))
696 _("backing up `%s' would destroy source; `%s' not copied"),
701 dst_backup
= (char *) alloca (strlen (tmp_backup
) + 1);
702 strcpy (dst_backup
, tmp_backup
);
704 if (rename (dst_path
, dst_backup
))
708 error (0, errno
, _("cannot backup `%s'"), dst_path
);
718 if (S_ISDIR (dst_sb
.st_mode
))
720 /* Temporarily change mode to allow overwriting. */
721 if (euidaccess (dst_path
, W_OK
| X_OK
) != 0)
723 if (chmod (dst_path
, 0700))
725 error (0, errno
, "%s", dst_path
);
734 if (unlink (dst_path
) && errno
!= ENOENT
)
736 error (0, errno
, _("cannot remove old link to `%s'"),
746 /* If the source is a directory, we don't always create the destination
747 directory. So --verbose should not announce anything until we're
748 sure we'll create a directory. */
749 if (flag_verbose
&& !S_ISDIR (src_type
))
750 printf ("%s -> %s\n", src_path
, dst_path
);
752 /* Did we copy this inode somewhere else (in this command line argument)
753 and therefore this is a second hard link to the inode? */
755 if (!flag_dereference
&& src_sb
.st_nlink
> 1 && earlier_file
)
757 if (link (earlier_file
, dst_path
))
759 error (0, errno
, "%s", dst_path
);
765 if (S_ISDIR (src_type
))
767 struct dir_list
*dir
;
769 /* If this directory has been copied before during the
770 recursion, there is a symbolic link to an ancestor
771 directory of the symbolic link. It is impossible to
772 continue to copy this, unless we've got an infinite disk. */
774 if (is_ancestor (&src_sb
, ancestors
))
776 error (0, 0, _("%s: cannot copy cyclic symbolic link"), src_path
);
780 /* Insert the current directory in the list of parents. */
782 dir
= (struct dir_list
*) alloca (sizeof (struct dir_list
));
783 dir
->parent
= ancestors
;
784 dir
->ino
= src_sb
.st_ino
;
785 dir
->dev
= src_sb
.st_dev
;
787 if (new_dst
|| !S_ISDIR (dst_sb
.st_mode
))
789 /* Create the new directory writable and searchable, so
790 we can create new entries in it. */
792 if (mkdir (dst_path
, (src_mode
& umask_kill
) | 0700))
794 error (0, errno
, _("cannot create directory `%s'"), dst_path
);
798 /* Insert the created directory's inode and device
799 numbers into the search structure, so that we can
800 avoid copying it again. */
802 if (remember_created (dst_path
))
806 printf ("%s -> %s\n", src_path
, dst_path
);
809 /* Copy the contents of the directory. */
811 if (copy_dir (src_path
, dst_path
, new_dst
, &src_sb
, dir
))
815 else if (flag_symbolic_link
)
818 || (!strncmp (dst_path
, "./", 2) && strchr (dst_path
+ 2, '/') == 0)
819 || strchr (dst_path
, '/') == 0)
821 if (symlink (src_path
, dst_path
))
823 error (0, errno
, "%s", dst_path
);
832 _("%s: can make relative symbolic links only in current directory"),
838 else if (flag_hard_link
)
840 if (link (src_path
, dst_path
))
842 error (0, errno
, _("cannot create link `%s'"), dst_path
);
847 else if (S_ISREG (src_type
)
848 || (flag_copy_as_regular
&& !S_ISDIR (src_type
)
850 && !S_ISLNK (src_type
)
854 if (copy_reg (src_path
, dst_path
))
859 if (S_ISFIFO (src_type
))
861 if (mkfifo (dst_path
, src_mode
& umask_kill
))
863 error (0, errno
, _("cannot create fifo `%s'"), dst_path
);
869 if (S_ISBLK (src_type
) || S_ISCHR (src_type
)
871 || S_ISSOCK (src_type
)
875 if (mknod (dst_path
, src_mode
& umask_kill
, src_sb
.st_rdev
))
877 error (0, errno
, _("cannot create special file `%s'"), dst_path
);
883 if (S_ISLNK (src_type
))
888 link_val
= (char *) alloca (PATH_MAX
+ 2);
889 link_size
= readlink (src_path
, link_val
, PATH_MAX
+ 1);
892 error (0, errno
, _("cannot read symbolic link `%s'"), src_path
);
895 link_val
[link_size
] = '\0';
897 if (symlink (link_val
, dst_path
))
899 error (0, errno
, _("cannot create symbolic link `%s'"), dst_path
);
905 /* Preserve the owner and group of the just-`copied'
906 symbolic link, if possible. */
908 if (DO_CHOWN (lchown
, dst_path
, src_sb
.st_uid
, src_sb
.st_gid
))
910 error (0, errno
, "%s", dst_path
);
914 # ifdef ROOT_CHOWN_AFFECTS_SYMLINKS
917 if (DO_CHOWN (chown
, dst_path
, src_sb
.st_uid
, src_sb
.st_gid
))
919 error (0, errno
, "%s", dst_path
);
925 /* FIXME: maybe give a diagnostic: you must be root
926 to preserve ownership and group of symlinks. */
929 /* Can't preserve ownership of symlinks.
930 FIXME: maybe give a warning or even error for symlinks
931 in directories with the sticky bit set -- there, not
932 preserving owner/group is a potential security problem. */
942 error (0, 0, _("%s: unknown file type"), src_path
);
946 /* Adjust the times (and if possible, ownership) for the copy.
947 chown turns off set[ug]id bits for non-root,
948 so do the chmod last. */
954 utb
.actime
= src_sb
.st_atime
;
955 utb
.modtime
= src_sb
.st_mtime
;
957 if (utime (dst_path
, &utb
))
959 error (0, errno
, "%s", dst_path
);
963 if (DO_CHOWN (chown
, dst_path
, src_sb
.st_uid
, src_sb
.st_gid
))
965 error (0, errno
, "%s", dst_path
);
970 if ((flag_preserve
|| new_dst
)
971 && (flag_copy_as_regular
|| S_ISREG (src_type
) || S_ISDIR (src_type
)))
973 if (chmod (dst_path
, src_mode
& umask_kill
))
975 error (0, errno
, "%s", dst_path
);
981 /* Reset the temporarily changed mode. */
982 if (chmod (dst_path
, dst_sb
.st_mode
))
984 error (0, errno
, "%s", dst_path
);
994 if (rename (dst_backup
, dst_path
))
995 error (0, errno
, _("cannot un-backup `%s'"), dst_path
);
1000 /* Ensure that the parent directory of CONST_DIRPATH exists, for
1001 the --parents option.
1003 SRC_OFFSET is the index in CONST_DIRPATH (which is a destination
1004 path) of the beginning of the source directory name.
1005 Create any leading directories that don't already exist,
1006 giving them permissions MODE.
1007 If VERBOSE_FMT_STRING is nonzero, use it as a printf format
1008 string for printing a message after successfully making a directory.
1009 The format should take two string arguments: the names of the
1010 source and destination directories.
1011 Creates a linked list of attributes of intermediate directories,
1012 *ATTR_LIST, for re_protect to use after calling copy.
1013 Sets *NEW_DST to 1 if this function creates parent of CONST_DIRPATH.
1015 Return 0 if parent of CONST_DIRPATH exists as a directory with the proper
1016 permissions when done, otherwise 1. */
1019 make_path_private (const char *const_dirpath
, int src_offset
, int mode
,
1020 const char *verbose_fmt_string
, struct dir_attr
**attr_list
,
1024 char *dirpath
; /* A copy of CONST_DIRPATH we can change. */
1025 char *src
; /* Source name in `dirpath'. */
1026 char *tmp_dst_dirname
; /* Leading path of `dirpath', malloc. */
1027 char *dst_dirname
; /* Leading path of `dirpath', alloca. */
1029 dirpath
= (char *) alloca (strlen (const_dirpath
) + 1);
1030 strcpy (dirpath
, const_dirpath
);
1032 src
= dirpath
+ src_offset
;
1034 tmp_dst_dirname
= dirname (dirpath
);
1035 dst_dirname
= (char *) alloca (strlen (tmp_dst_dirname
) + 1);
1036 strcpy (dst_dirname
, tmp_dst_dirname
);
1037 free (tmp_dst_dirname
);
1041 if ((*xstat
) (dst_dirname
, &stats
))
1043 /* Parent of CONST_DIRNAME does not exist.
1044 Make all missing intermediate directories. */
1048 while (*slash
== '/')
1050 while ((slash
= strchr (slash
, '/')))
1052 /* Add this directory to the list of directories whose modes need
1054 struct dir_attr
*new =
1055 (struct dir_attr
*) xmalloc (sizeof (struct dir_attr
));
1056 new->slash_offset
= slash
- dirpath
;
1057 new->next
= *attr_list
;
1061 if ((*xstat
) (dirpath
, &stats
))
1063 /* This element of the path does not exist. We must set
1064 *new_dst and new->is_new_dir inside this loop because,
1065 for example, in the command `cp --parents ../a/../b/c e_dir',
1066 make_path_private creates only e_dir/../a if ./b already
1069 new->is_new_dir
= 1;
1070 if (mkdir (dirpath
, mode
))
1072 error (0, errno
, _("cannot make directory `%s'"), dirpath
);
1077 if (verbose_fmt_string
!= NULL
)
1078 printf (verbose_fmt_string
, src
, dirpath
);
1081 else if (!S_ISDIR (stats
.st_mode
))
1083 error (0, 0, _("`%s' exists but is not a directory"), dirpath
);
1088 new->is_new_dir
= 0;
1093 /* Avoid unnecessary calls to `stat' when given
1094 pathnames containing multiple adjacent slashes. */
1095 while (*slash
== '/')
1100 /* We get here if the parent of `dirpath' already exists. */
1102 else if (!S_ISDIR (stats
.st_mode
))
1104 error (0, 0, _("`%s' exists but is not a directory"), dst_dirname
);
1114 /* Ensure that the parent directories of CONST_DST_PATH have the
1115 correct protections, for the --parents option. This is done
1116 after all copying has been completed, to allow permissions
1117 that don't include user write/execute.
1119 SRC_OFFSET is the index in CONST_DST_PATH of the beginning of the
1120 source directory name.
1122 ATTR_LIST is a null-terminated linked list of structures that
1123 indicates the end of the filename of each intermediate directory
1124 in CONST_DST_PATH that may need to have its attributes changed.
1125 The command `cp --parents --preserve a/b/c d/e_dir' changes the
1126 attributes of the directories d/e_dir/a and d/e_dir/a/b to match
1127 the corresponding source directories regardless of whether they
1128 existed before the `cp' command was given.
1130 Return 0 if the parent of CONST_DST_PATH and any intermediate
1131 directories specified by ATTR_LIST have the proper permissions
1132 when done, otherwise 1. */
1135 re_protect (const char *const_dst_path
, int src_offset
,
1136 struct dir_attr
*attr_list
)
1139 char *dst_path
; /* A copy of CONST_DST_PATH we can change. */
1140 char *src_path
; /* The source name in `dst_path'. */
1142 dst_path
= (char *) alloca (strlen (const_dst_path
) + 1);
1143 strcpy (dst_path
, const_dst_path
);
1144 src_path
= dst_path
+ src_offset
;
1146 for (p
= attr_list
; p
; p
= p
->next
)
1150 dst_path
[p
->slash_offset
] = '\0';
1152 if ((*xstat
) (src_path
, &src_sb
))
1154 error (0, errno
, "%s", src_path
);
1158 /* Adjust the times (and if possible, ownership) for the copy.
1159 chown turns off set[ug]id bits for non-root,
1160 so do the chmod last. */
1166 utb
.actime
= src_sb
.st_atime
;
1167 utb
.modtime
= src_sb
.st_mtime
;
1169 if (utime (dst_path
, &utb
))
1171 error (0, errno
, "%s", dst_path
);
1175 /* If non-root uses -p, it's ok if we can't preserve ownership.
1176 But root probably wants to know, e.g. if NFS disallows it. */
1177 if (chown (dst_path
, src_sb
.st_uid
, src_sb
.st_gid
)
1178 && (errno
!= EPERM
|| myeuid
== 0))
1180 error (0, errno
, "%s", dst_path
);
1185 if (flag_preserve
|| p
->is_new_dir
)
1187 if (chmod (dst_path
, src_sb
.st_mode
& umask_kill
))
1189 error (0, errno
, "%s", dst_path
);
1194 dst_path
[p
->slash_offset
] = '/';
1199 /* Read the contents of the directory SRC_PATH_IN, and recursively
1200 copy the contents to DST_PATH_IN. NEW_DST is nonzero if
1201 DST_PATH_IN is a directory that was created previously in the
1202 recursion. SRC_SB and ANCESTORS describe SRC_PATH_IN.
1203 Return 0 if successful, -1 if an error occurs. */
1206 copy_dir (const char *src_path_in
, const char *dst_path_in
, int new_dst
,
1207 const struct stat
*src_sb
, struct dir_list
*ancestors
)
1216 name_space
= savedir (src_path_in
, src_sb
->st_size
);
1217 if (name_space
== 0)
1221 error (0, errno
, "%s", src_path_in
);
1225 error (1, 0, _("virtual memory exhausted"));
1229 while (*namep
!= '\0')
1231 int fn_length
= strlen (namep
) + 1;
1233 dst_path
= xmalloc (strlen (dst_path_in
) + fn_length
+ 1);
1234 src_path
= xmalloc (strlen (src_path_in
) + fn_length
+ 1);
1236 stpcpy (stpcpy (stpcpy (src_path
, src_path_in
), "/"), namep
);
1237 stpcpy (stpcpy (stpcpy (dst_path
, dst_path_in
), "/"), namep
);
1239 ret
|= copy (src_path
, dst_path
, new_dst
, src_sb
->st_dev
, ancestors
);
1241 /* Free the memory for `src_path'. The memory for `dst_path'
1242 cannot be deallocated, since it is used to create multiple
1253 /* Copy a regular file from SRC_PATH to DST_PATH.
1254 If the source file contains holes, copies holes and blocks of zeros
1255 in the source file as holes in the destination file.
1256 (Holes are read as zeroes by the `read' system call.)
1257 Return 0 if successful, -1 if an error occurred. */
1260 copy_reg (const char *src_path
, const char *dst_path
)
1271 long n_read_total
= 0;
1272 int last_write_made_hole
= 0;
1273 int make_holes
= (flag_sparse
== SPARSE_ALWAYS
);
1275 source_desc
= open (src_path
, O_RDONLY
);
1276 if (source_desc
< 0)
1278 error (0, errno
, "%s", src_path
);
1282 /* Create the new regular file with small permissions initially,
1283 to not create a security hole. */
1285 dest_desc
= open (dst_path
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0600);
1288 error (0, errno
, _("cannot create regular file `%s'"), dst_path
);
1293 /* Find out the optimal buffer size. */
1295 if (fstat (dest_desc
, &sb
))
1297 error (0, errno
, "%s", dst_path
);
1302 buf_size
= ST_BLKSIZE (sb
);
1304 #ifdef HAVE_ST_BLOCKS
1305 if (flag_sparse
== SPARSE_AUTO
&& S_ISREG (sb
.st_mode
))
1307 /* Use a heuristic to determine whether SRC_PATH contains any
1310 if (fstat (source_desc
, &sb
))
1312 error (0, errno
, "%s", src_path
);
1317 /* If the file has fewer blocks than would normally
1318 be needed for a file of its size, then
1319 at least one of the blocks in the file is a hole. */
1320 if (S_ISREG (sb
.st_mode
)
1321 && (size_t) (sb
.st_size
/ 512) > (size_t) ST_NBLOCKS (sb
))
1326 /* Make a buffer with space for a sentinel at the end. */
1328 buf
= (char *) alloca (buf_size
+ sizeof (int));
1332 n_read
= read (source_desc
, buf
, buf_size
);
1339 error (0, errno
, "%s", src_path
);
1346 n_read_total
+= n_read
;
1351 buf
[n_read
] = 1; /* Sentinel to stop loop. */
1353 /* Find first nonzero *word*, or the word with the sentinel. */
1359 /* Find the first nonzero *byte*, or the sentinel. */
1361 cp
= (char *) (ip
- 1);
1365 /* If we found the sentinel, the whole input block was zero,
1366 and we can make a hole. */
1368 if (cp
> buf
+ n_read
)
1371 if (lseek (dest_desc
, (off_t
) n_read
, SEEK_CUR
) < 0L)
1373 error (0, errno
, "%s", dst_path
);
1377 last_write_made_hole
= 1;
1380 /* Clear to indicate that a normal write is needed. */
1385 if (full_write (dest_desc
, buf
, n_read
) < 0)
1387 error (0, errno
, "%s", dst_path
);
1391 last_write_made_hole
= 0;
1395 /* If the file ends with a `hole', something needs to be written at
1396 the end. Otherwise the kernel would truncate the file at the end
1397 of the last write operation. */
1399 if (last_write_made_hole
)
1401 #ifdef HAVE_FTRUNCATE
1402 /* Write a null character and truncate it again. */
1403 if (full_write (dest_desc
, "", 1) < 0
1404 || ftruncate (dest_desc
, n_read_total
) < 0)
1406 /* Seek backwards one character and write a null. */
1407 if (lseek (dest_desc
, (off_t
) -1, SEEK_CUR
) < 0L
1408 || full_write (dest_desc
, "", 1) < 0)
1411 error (0, errno
, "%s", dst_path
);
1417 if (close (dest_desc
) < 0)
1419 error (0, errno
, "%s", dst_path
);
1423 if (close (source_desc
) < 0)
1425 error (0, errno
, "%s", src_path
);