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"
35 #ifndef _POSIX_VERSION
40 # define chown(PATH, OWNER, GROUP) lchown(PATH, OWNER, GROUP)
43 /* Used by do_copy, make_path_private, and re_protect
44 to keep a list of leading directories whose protections
45 need to be fixed after copying. */
50 struct dir_attr
*next
;
53 /* Control creation of sparse files (files with holes). */
56 /* Never create holes in DEST. */
59 /* This is the default. Use a crude (and sometimes inaccurate)
60 heuristic to determine if SOURCE has holes. If so, try to create
64 /* For every sufficiently long sequence of bytes in SOURCE, try to
65 create a corresponding hole in DEST. There is a performance penalty
66 here because CP has to search for holes in SRC. But if the holes are
67 big enough, that penalty can be offset by the decrease in the amount
68 of data written to disk. */
77 enum backup_type
get_version ();
81 static int do_copy
__P ((int argc
, char **argv
));
82 static int copy
__P ((const char *src_path
, const char *dst_path
, int new_dst
,
83 dev_t device
, struct dir_list
*ancestors
));
84 static int copy_dir
__P ((const char *src_path_in
, const char *dst_path_in
,
85 int new_dst
, const struct stat
*src_sb
,
86 struct dir_list
*ancestors
));
87 static int make_path_private
__P ((const char *const_dirpath
, int src_offset
,
88 int mode
, const char *verbose_fmt_string
,
89 struct dir_attr
**attr_list
, int *new_dst
));
90 static int copy_reg
__P ((const char *src_path
, const char *dst_path
));
91 static int re_protect
__P ((const char *const_dst_path
, int src_offset
,
92 struct dir_attr
*attr_list
));
94 /* Initial number of entries in each hash table entry's table of inodes. */
95 #define INITIAL_HASH_MODULE 100
97 /* Initial number of entries in the inode hash table. */
98 #define INITIAL_ENTRY_TAB_SIZE 70
100 /* The invocation name of this program. */
103 /* A pointer to either lstat or stat, depending on
104 whether dereferencing of symlinks is done. */
105 static int (*xstat
) ();
107 /* If nonzero, copy all files except (directories and, if not dereferencing
108 them, symbolic links,) as if they were regular files. */
109 static int flag_copy_as_regular
= 1;
111 /* If nonzero, dereference symbolic links (copy the files they point to). */
112 static int flag_dereference
= 1;
114 /* If nonzero, remove existing destination nondirectories. */
115 static int flag_force
= 0;
117 /* If nonzero, create hard links instead of copying files.
118 Create destination directories as usual. */
119 static int flag_hard_link
= 0;
121 /* If nonzero, query before overwriting existing destinations
122 with regular files. */
123 static int flag_interactive
= 0;
125 /* If nonzero, the command "cp x/e_file e_dir" uses "e_dir/x/e_file"
126 as its destination instead of the usual "e_dir/e_file." */
127 static int flag_path
= 0;
129 /* If nonzero, give the copies the original files' permissions,
130 ownership, and timestamps. */
131 static int flag_preserve
= 0;
133 /* If nonzero, copy directories recursively and copy special files
134 as themselves rather than copying their contents. */
135 static int flag_recursive
= 0;
137 /* If nonzero, create symbolic links instead of copying files.
138 Create destination directories as usual. */
139 static int flag_symbolic_link
= 0;
141 /* If nonzero, when copying recursively, skip any subdirectories that are
142 on different filesystems from the one we started on. */
143 static int flag_one_file_system
= 0;
145 /* If nonzero, do not copy a nondirectory that has an existing destination
146 with the same or newer modification time. */
147 static int flag_update
= 0;
149 /* If nonzero, display the names of the files before copying them. */
150 static int flag_verbose
= 0;
152 static char const *const sparse_type_string
[] =
154 "never", "auto", "always", 0
157 static enum Sparse_type
const sparse_type
[] =
159 SPARSE_NEVER
, SPARSE_AUTO
, SPARSE_ALWAYS
162 /* Control creation of sparse files. */
163 static int flag_sparse
= SPARSE_AUTO
;
165 /* The error code to return to the system. */
166 static int exit_status
= 0;
168 /* The bits to preserve in created files' modes. */
169 static int umask_kill
;
171 /* This process's effective user ID. */
174 /* If nonzero, display usage information and exit. */
175 static int show_help
;
177 /* If nonzero, print the version on standard output and exit. */
178 static int show_version
;
180 static struct option
const long_opts
[] =
182 {"archive", no_argument
, NULL
, 'a'},
183 {"backup", no_argument
, NULL
, 'b'},
184 {"force", no_argument
, NULL
, 'f'},
185 {"sparse", required_argument
, NULL
, 2},
186 {"interactive", no_argument
, NULL
, 'i'},
187 {"link", no_argument
, NULL
, 'l'},
188 {"no-dereference", no_argument
, &flag_dereference
, 0},
189 {"one-file-system", no_argument
, &flag_one_file_system
, 1},
190 {"parents", no_argument
, &flag_path
, 1},
191 {"path", no_argument
, &flag_path
, 1},
192 {"preserve", no_argument
, &flag_preserve
, 1},
193 {"recursive", no_argument
, NULL
, 'R'},
194 {"suffix", required_argument
, NULL
, 'S'},
195 {"symbolic-link", no_argument
, NULL
, 's'},
196 {"update", no_argument
, &flag_update
, 1},
197 {"verbose", no_argument
, &flag_verbose
, 1},
198 {"version-control", required_argument
, NULL
, 'V'},
199 {"help", no_argument
, &show_help
, 1},
200 {"version", no_argument
, &show_version
, 1},
205 main (int argc
, char **argv
)
208 int make_backups
= 0;
211 program_name
= argv
[0];
212 setlocale (LC_ALL
, "");
213 bindtextdomain (PACKAGE
, LOCALEDIR
);
214 textdomain (PACKAGE
);
218 version
= getenv ("SIMPLE_BACKUP_SUFFIX");
220 simple_backup_suffix
= version
;
221 version
= getenv ("VERSION_CONTROL");
223 /* Find out the current file creation mask, to knock the right bits
224 when using chmod. The creation mask is set to to be liberal, so
225 that created directories can be written, even if it would not
226 have been allowed with the mask this process was started with. */
228 umask_kill
= 0777777 ^ umask (0);
230 while ((c
= getopt_long (argc
, argv
, "abdfilprsuvxPRS:V:", long_opts
,
242 /* --sparse={never,auto,always} */
243 i
= argmatch (optarg
, sparse_type_string
);
246 invalid_arg (_("sparse type"), optarg
, i
);
249 flag_sparse
= sparse_type
[i
];
253 case 'a': /* Like -dpR. */
254 flag_dereference
= 0;
257 flag_copy_as_regular
= 0;
265 flag_dereference
= 0;
270 flag_interactive
= 0;
275 flag_interactive
= 1;
292 flag_copy_as_regular
= 1;
297 flag_copy_as_regular
= 0;
302 flag_symbolic_link
= 1;
304 error (1, 0, _("symbolic links are not supported on this system"));
317 flag_one_file_system
= 1;
321 simple_backup_suffix
= optarg
;
329 usage (2, (char *) 0);
335 printf ("cp - %s\n", PACKAGE_VERSION
);
342 if (flag_hard_link
&& flag_symbolic_link
)
343 usage (2, _("cannot make both hard and symbolic links"));
346 backup_type
= get_version (version
);
348 if (flag_preserve
== 1)
349 umask_kill
= 0777777;
351 /* The key difference between -d (--no-dereference) and not is the version
352 of `stat' to call. */
354 if (flag_dereference
)
359 /* Allocate space for remembering copied and created files. */
361 hash_init (INITIAL_HASH_MODULE
, INITIAL_ENTRY_TAB_SIZE
);
363 exit_status
|= do_copy (argc
, argv
);
368 /* Concatenate two pathname components, DIR and BASE, in newly-allocated
369 storage and return the result. Be careful that in the result they are
370 separated by a slash. That is, if DIR ends with a slash or if BASE
371 begins with one, don't add a separating slash. Otherwise, add one. */
374 path_concat (const char *dir
, const char *base
)
379 assert (strlen (dir
) > 0);
380 p_concat
= xmalloc (strlen (dir
) + strlen (base
) + 2);
381 dir_end
= stpcpy (p_concat
, dir
);
382 if (*(dir_end
- 1) == '/')
384 else if (*base
== '/')
386 stpcpy (stpcpy (dir_end
, "/"), base
);
390 /* Scan the arguments, and copy each by calling copy.
391 Return 0 if successful, 1 if any errors occur. */
394 do_copy (int argc
, char **argv
)
402 usage (2, _("missing file arguments"));
403 if (optind
>= argc
- 1)
404 usage (2, _("missing destination file"));
406 dest
= argv
[argc
- 1];
408 if (lstat (dest
, &sb
))
412 error (0, errno
, "%s", dest
);
422 /* If `dest' is not a symlink to a nonexistent file, use
423 the results of stat instead of lstat, so we can copy files
424 into symlinks to directories. */
425 if (stat (dest
, &sbx
) == 0)
429 if (!new_dst
&& S_ISDIR (sb
.st_mode
))
431 /* cp file1...filen edir
432 Copy the files `file1' through `filen'
433 to the existing directory `edir'. */
440 int parent_exists
= 1; /* True if dirname (dst_path) exists. */
441 struct dir_attr
*attr_list
;
445 strip_trailing_slashes (arg
);
449 /* Append all of `arg' to `dest'. */
450 dst_path
= path_concat (dest
, arg
);
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 strlen (dest
) + 1, 0700,
458 ? "%s -> %s\n" : NULL
),
459 &attr_list
, &new_dst
);
463 /* Append the last component of `arg' to `dest'. */
466 /* For `cp -R source/.. dest', don't copy into `dest/..'. */
467 dst_path
= (STREQ (ap
, "..")
469 : path_concat (dest
, ap
));
474 /* make_path_private failed, so don't even attempt the copy. */
479 ret
|= copy (arg
, dst_path
, new_dst
, 0, (struct dir_list
*) 0);
484 ret
|= re_protect (dst_path
, strlen (dest
) + 1, attr_list
);
490 if (optind
== argc
- 1)
495 else if (argc
- optind
== 2)
499 struct stat source_stats
;
503 _("when preserving paths, last argument must be a directory"));
505 source
= argv
[optind
];
507 /* When the force and backup options have been specified and
508 the source and destination are the same name for an existing
509 regular file, convert the user's command, e.g.,
510 `cp --force --backup foo foo' to `cp --force foo fooSUFFIX'
511 where SUFFIX is determined by any version control options used. */
514 && backup_type
!= none
515 && STREQ (source
, dest
)
516 && !new_dst
&& S_ISREG (sb
.st_mode
))
519 new_dest
= find_backup_file_name (dest
);
520 if (new_dest
== NULL
)
521 error (1, 0, _("virtual memory exhausted"));
524 /* When the destination is specified with a trailing slash and the
525 source exists but is not a directory, convert the user's command
526 `cp source dest/' to `cp source dest/basename(source)'. */
528 else if (dest
[strlen (dest
) - 1] == '/'
529 && lstat (source
, &source_stats
) == 0
530 && !S_ISDIR (source_stats
.st_mode
))
535 tmp_source
= (char *) alloca (strlen (source
) + 1);
536 strcpy (tmp_source
, source
);
537 strip_trailing_slashes (tmp_source
);
538 source_base
= basename (tmp_source
);
540 new_dest
= (char *) alloca (strlen (dest
) + 1 +
541 strlen (source_base
) + 1);
542 stpcpy (stpcpy (stpcpy (new_dest
, dest
), "/"), source_base
);
549 return copy (source
, new_dest
, new_dst
, 0, (struct dir_list
*) 0);
553 _("when copying multiple files, last argument must be a directory"));
556 /* Copy the file SRC_PATH to the file DST_PATH. The files may be of
557 any type. NEW_DST should be nonzero if the file DST_PATH cannot
558 exist because its parent directory was just created; NEW_DST should
559 be zero if DST_PATH might already exist. DEVICE is the device
560 number of the parent directory, or 0 if the parent of this file is
561 not known. ANCESTORS points to a linked, null terminated list of
562 devices and inodes of parent directories of SRC_PATH.
563 Return 0 if successful, 1 if an error occurs. */
566 copy (const char *src_path
, const char *dst_path
, int new_dst
, dev_t device
,
567 struct dir_list
*ancestors
)
574 char *dst_backup
= NULL
;
577 if ((*xstat
) (src_path
, &src_sb
))
579 error (0, errno
, "%s", src_path
);
583 /* Are we crossing a file system boundary? */
584 if (flag_one_file_system
&& device
!= 0 && device
!= src_sb
.st_dev
)
587 /* We wouldn't insert a node unless nlink > 1, except that we need to
588 find created files so as to not copy infinitely if a directory is
589 copied into itself. */
591 earlier_file
= remember_copied (dst_path
, src_sb
.st_ino
, src_sb
.st_dev
);
593 /* Did we just create this file? */
595 if (earlier_file
== &new_file
)
598 src_mode
= src_sb
.st_mode
;
599 src_type
= src_sb
.st_mode
;
601 if (S_ISDIR (src_type
) && !flag_recursive
)
603 error (0, 0, _("%s: omitting directory"), src_path
);
609 if ((*xstat
) (dst_path
, &dst_sb
))
613 error (0, errno
, "%s", dst_path
);
621 /* The file exists already. */
623 if (src_sb
.st_ino
== dst_sb
.st_ino
&& src_sb
.st_dev
== dst_sb
.st_dev
)
628 error (0, 0, _("`%s' and `%s' are the same file"),
633 if (!S_ISDIR (src_type
))
635 if (S_ISDIR (dst_sb
.st_mode
))
638 _("%s: cannot overwrite directory with non-directory"),
643 if (flag_update
&& src_sb
.st_mtime
<= dst_sb
.st_mtime
)
647 if (S_ISREG (src_type
) && !flag_force
)
649 if (flag_interactive
)
651 if (euidaccess (dst_path
, W_OK
) != 0)
653 _("%s: overwrite `%s', overriding mode %04o? "),
654 program_name
, dst_path
,
655 (unsigned int) (dst_sb
.st_mode
& 07777));
657 fprintf (stderr
, _("%s: overwrite `%s'? "),
658 program_name
, dst_path
);
664 if (backup_type
!= none
&& !S_ISDIR (dst_sb
.st_mode
))
666 char *tmp_backup
= find_backup_file_name (dst_path
);
667 if (tmp_backup
== NULL
)
668 error (1, 0, _("virtual memory exhausted"));
670 /* Detect (and fail) when creating the backup file would
671 destroy the source file. Before, running the commands
672 cd /tmp; rm -f a a~; : > a; echo A > a~; cp -b -V simple a~ a
673 would leave two zero-length files: a and a~. */
674 if (STREQ (tmp_backup
, src_path
))
677 _("backing up `%s' would destroy source; `%s' not copied"),
682 dst_backup
= (char *) alloca (strlen (tmp_backup
) + 1);
683 strcpy (dst_backup
, tmp_backup
);
685 if (rename (dst_path
, dst_backup
))
689 error (0, errno
, _("cannot backup `%s'"), dst_path
);
699 if (S_ISDIR (dst_sb
.st_mode
))
701 /* Temporarily change mode to allow overwriting. */
702 if (euidaccess (dst_path
, W_OK
| X_OK
) != 0)
704 if (chmod (dst_path
, 0700))
706 error (0, errno
, "%s", dst_path
);
715 if (unlink (dst_path
) && errno
!= ENOENT
)
717 error (0, errno
, _("cannot remove old link to `%s'"),
727 /* If the source is a directory, we don't always create the destination
728 directory. So --verbose should not announce anything until we're
729 sure we'll create a directory. */
730 if (flag_verbose
&& !S_ISDIR (src_type
))
731 printf ("%s -> %s\n", src_path
, dst_path
);
733 /* Did we copy this inode somewhere else (in this command line argument)
734 and therefore this is a second hard link to the inode? */
736 if (!flag_dereference
&& src_sb
.st_nlink
> 1 && earlier_file
)
738 if (link (earlier_file
, dst_path
))
740 error (0, errno
, "%s", dst_path
);
746 if (S_ISDIR (src_type
))
748 struct dir_list
*dir
;
750 /* If this directory has been copied before during the
751 recursion, there is a symbolic link to an ancestor
752 directory of the symbolic link. It is impossible to
753 continue to copy this, unless we've got an infinite disk. */
755 if (is_ancestor (&src_sb
, ancestors
))
757 error (0, 0, _("%s: cannot copy cyclic symbolic link"), src_path
);
761 /* Insert the current directory in the list of parents. */
763 dir
= (struct dir_list
*) alloca (sizeof (struct dir_list
));
764 dir
->parent
= ancestors
;
765 dir
->ino
= src_sb
.st_ino
;
766 dir
->dev
= src_sb
.st_dev
;
768 if (new_dst
|| !S_ISDIR (dst_sb
.st_mode
))
770 /* Create the new directory writable and searchable, so
771 we can create new entries in it. */
773 if (mkdir (dst_path
, (src_mode
& umask_kill
) | 0700))
775 error (0, errno
, _("cannot create directory `%s'"), dst_path
);
779 /* Insert the created directory's inode and device
780 numbers into the search structure, so that we can
781 avoid copying it again. */
783 if (remember_created (dst_path
))
787 printf ("%s -> %s\n", src_path
, dst_path
);
790 /* Copy the contents of the directory. */
792 if (copy_dir (src_path
, dst_path
, new_dst
, &src_sb
, dir
))
796 else if (flag_symbolic_link
)
799 || (!strncmp (dst_path
, "./", 2) && strchr (dst_path
+ 2, '/') == 0)
800 || strchr (dst_path
, '/') == 0)
802 if (symlink (src_path
, dst_path
))
804 error (0, errno
, "%s", dst_path
);
812 _("%s: can make relative symbolic links only in current directory"),
818 else if (flag_hard_link
)
820 if (link (src_path
, dst_path
))
822 error (0, errno
, _("cannot create link `%s'"), dst_path
);
827 else if (S_ISREG (src_type
)
828 || (flag_copy_as_regular
&& !S_ISDIR (src_type
)
830 && !S_ISLNK (src_type
)
834 if (copy_reg (src_path
, dst_path
))
839 if (S_ISFIFO (src_type
))
841 if (mkfifo (dst_path
, src_mode
& umask_kill
))
843 error (0, errno
, _("cannot create fifo `%s'"), dst_path
);
849 if (S_ISBLK (src_type
) || S_ISCHR (src_type
)
851 || S_ISSOCK (src_type
)
855 if (mknod (dst_path
, src_mode
& umask_kill
, src_sb
.st_rdev
))
857 error (0, errno
, _("cannot create special file `%s'"), dst_path
);
863 if (S_ISLNK (src_type
))
868 link_val
= (char *) alloca (PATH_MAX
+ 2);
869 link_size
= readlink (src_path
, link_val
, PATH_MAX
+ 1);
872 error (0, errno
, _("cannot read symbolic link `%s'"), src_path
);
875 link_val
[link_size
] = '\0';
877 if (symlink (link_val
, dst_path
))
879 error (0, errno
, _("cannot create symbolic link `%s'"), dst_path
);
887 error (0, 0, _("%s: unknown file type"), src_path
);
891 /* Adjust the times (and if possible, ownership) for the copy.
892 chown turns off set[ug]id bits for non-root,
893 so do the chmod last. */
899 utb
.actime
= src_sb
.st_atime
;
900 utb
.modtime
= src_sb
.st_mtime
;
902 if (utime (dst_path
, &utb
))
904 error (0, errno
, "%s", dst_path
);
908 /* If non-root uses -p, it's ok if we can't preserve ownership.
909 But root probably wants to know, e.g. if NFS disallows it. */
911 (myeuid
== 0 ? src_sb
.st_uid
: myeuid
),
913 && (errno
!= EPERM
|| myeuid
== 0))
915 error (0, errno
, "%s", dst_path
);
920 if ((flag_preserve
|| new_dst
)
921 && (flag_copy_as_regular
|| S_ISREG (src_type
) || S_ISDIR (src_type
)))
923 if (chmod (dst_path
, src_mode
& umask_kill
))
925 error (0, errno
, "%s", dst_path
);
931 /* Reset the temporarily changed mode. */
932 if (chmod (dst_path
, dst_sb
.st_mode
))
934 error (0, errno
, "%s", dst_path
);
944 if (rename (dst_backup
, dst_path
))
945 error (0, errno
, _("cannot un-backup `%s'"), dst_path
);
950 /* Ensure that the parent directory of CONST_DIRPATH exists, for
951 the --parents option.
953 SRC_OFFSET is the index in CONST_DIRPATH (which is a destination
954 path) of the beginning of the source directory name.
955 Create any leading directories that don't already exist,
956 giving them permissions MODE.
957 If VERBOSE_FMT_STRING is nonzero, use it as a printf format
958 string for printing a message after successfully making a directory.
959 The format should take two string arguments: the names of the
960 source and destination directories.
961 Creates a linked list of attributes of intermediate directories,
962 *ATTR_LIST, for re_protect to use after calling copy.
963 Sets *NEW_DST to 1 if this function creates parent of CONST_DIRPATH.
965 Return 0 if parent of CONST_DIRPATH exists as a directory with the proper
966 permissions when done, otherwise 1. */
969 make_path_private (const char *const_dirpath
, int src_offset
, int mode
,
970 const char *verbose_fmt_string
, struct dir_attr
**attr_list
,
974 char *dirpath
; /* A copy of CONST_DIRPATH we can change. */
975 char *src
; /* Source name in `dirpath'. */
976 char *tmp_dst_dirname
; /* Leading path of `dirpath', malloc. */
977 char *dst_dirname
; /* Leading path of `dirpath', alloca. */
979 dirpath
= (char *) alloca (strlen (const_dirpath
) + 1);
980 strcpy (dirpath
, const_dirpath
);
982 src
= dirpath
+ src_offset
;
984 tmp_dst_dirname
= dirname (dirpath
);
985 dst_dirname
= (char *) alloca (strlen (tmp_dst_dirname
) + 1);
986 strcpy (dst_dirname
, tmp_dst_dirname
);
987 free (tmp_dst_dirname
);
991 if ((*xstat
) (dst_dirname
, &stats
))
993 /* Parent of CONST_DIRNAME does not exist.
994 Make all missing intermediate directories. */
998 while (*slash
== '/')
1000 while ((slash
= strchr (slash
, '/')))
1002 /* Add this directory to the list of directories whose modes need
1004 struct dir_attr
*new =
1005 (struct dir_attr
*) xmalloc (sizeof (struct dir_attr
));
1006 new->slash_offset
= slash
- dirpath
;
1007 new->next
= *attr_list
;
1011 if ((*xstat
) (dirpath
, &stats
))
1013 /* This element of the path does not exist. We must set
1014 *new_dst and new->is_new_dir inside this loop because,
1015 for example, in the command `cp --parents ../a/../b/c e_dir',
1016 make_path_private creates only e_dir/../a if ./b already
1019 new->is_new_dir
= 1;
1020 if (mkdir (dirpath
, mode
))
1022 error (0, errno
, _("cannot make directory `%s'"), dirpath
);
1027 if (verbose_fmt_string
!= NULL
)
1028 printf (verbose_fmt_string
, src
, dirpath
);
1031 else if (!S_ISDIR (stats
.st_mode
))
1033 error (0, 0, _("`%s' exists but is not a directory"), dirpath
);
1038 new->is_new_dir
= 0;
1043 /* Avoid unnecessary calls to `stat' when given
1044 pathnames containing multiple adjacent slashes. */
1045 while (*slash
== '/')
1050 /* We get here if the parent of `dirpath' already exists. */
1052 else if (!S_ISDIR (stats
.st_mode
))
1054 error (0, 0, _("`%s' exists but is not a directory"), dst_dirname
);
1064 /* Ensure that the parent directories of CONST_DST_PATH have the
1065 correct protections, for the --parents option. This is done
1066 after all copying has been completed, to allow permissions
1067 that don't include user write/execute.
1069 SRC_OFFSET is the index in CONST_DST_PATH of the beginning of the
1070 source directory name.
1072 ATTR_LIST is a null-terminated linked list of structures that
1073 indicates the end of the filename of each intermediate directory
1074 in CONST_DST_PATH that may need to have its attributes changed.
1075 The command `cp --parents --preserve a/b/c d/e_dir' changes the
1076 attributes of the directories d/e_dir/a and d/e_dir/a/b to match
1077 the corresponding source directories regardless of whether they
1078 existed before the `cp' command was given.
1080 Return 0 if the parent of CONST_DST_PATH and any intermediate
1081 directories specified by ATTR_LIST have the proper permissions
1082 when done, otherwise 1. */
1085 re_protect (const char *const_dst_path
, int src_offset
,
1086 struct dir_attr
*attr_list
)
1089 char *dst_path
; /* A copy of CONST_DST_PATH we can change. */
1090 char *src_path
; /* The source name in `dst_path'. */
1092 dst_path
= (char *) alloca (strlen (const_dst_path
) + 1);
1093 strcpy (dst_path
, const_dst_path
);
1094 src_path
= dst_path
+ src_offset
;
1096 for (p
= attr_list
; p
; p
= p
->next
)
1100 dst_path
[p
->slash_offset
] = '\0';
1102 if ((*xstat
) (src_path
, &src_sb
))
1104 error (0, errno
, "%s", src_path
);
1108 /* Adjust the times (and if possible, ownership) for the copy.
1109 chown turns off set[ug]id bits for non-root,
1110 so do the chmod last. */
1116 utb
.actime
= src_sb
.st_atime
;
1117 utb
.modtime
= src_sb
.st_mtime
;
1119 if (utime (dst_path
, &utb
))
1121 error (0, errno
, "%s", dst_path
);
1125 /* If non-root uses -p, it's ok if we can't preserve ownership.
1126 But root probably wants to know, e.g. if NFS disallows it. */
1127 if (chown (dst_path
, src_sb
.st_uid
, src_sb
.st_gid
)
1128 && (errno
!= EPERM
|| myeuid
== 0))
1130 error (0, errno
, "%s", dst_path
);
1135 if (flag_preserve
|| p
->is_new_dir
)
1137 if (chmod (dst_path
, src_sb
.st_mode
& umask_kill
))
1139 error (0, errno
, "%s", dst_path
);
1144 dst_path
[p
->slash_offset
] = '/';
1149 /* Read the contents of the directory SRC_PATH_IN, and recursively
1150 copy the contents to DST_PATH_IN. NEW_DST is nonzero if
1151 DST_PATH_IN is a directory that was created previously in the
1152 recursion. SRC_SB and ANCESTORS describe SRC_PATH_IN.
1153 Return 0 if successful, -1 if an error occurs. */
1156 copy_dir (const char *src_path_in
, const char *dst_path_in
, int new_dst
,
1157 const struct stat
*src_sb
, struct dir_list
*ancestors
)
1166 name_space
= savedir (src_path_in
, src_sb
->st_size
);
1167 if (name_space
== 0)
1171 error (0, errno
, "%s", src_path_in
);
1175 error (1, 0, _("virtual memory exhausted"));
1179 while (*namep
!= '\0')
1181 int fn_length
= strlen (namep
) + 1;
1183 dst_path
= xmalloc (strlen (dst_path_in
) + fn_length
+ 1);
1184 src_path
= xmalloc (strlen (src_path_in
) + fn_length
+ 1);
1186 stpcpy (stpcpy (stpcpy (src_path
, src_path_in
), "/"), namep
);
1187 stpcpy (stpcpy (stpcpy (dst_path
, dst_path_in
), "/"), namep
);
1189 ret
|= copy (src_path
, dst_path
, new_dst
, src_sb
->st_dev
, ancestors
);
1191 /* Free the memory for `src_path'. The memory for `dst_path'
1192 cannot be deallocated, since it is used to create multiple
1203 /* Copy a regular file from SRC_PATH to DST_PATH.
1204 If the source file contains holes, copies holes and blocks of zeros
1205 in the source file as holes in the destination file.
1206 (Holes are read as zeroes by the `read' system call.)
1207 Return 0 if successful, -1 if an error occurred. */
1210 copy_reg (const char *src_path
, const char *dst_path
)
1221 long n_read_total
= 0;
1222 int last_write_made_hole
= 0;
1223 int make_holes
= (flag_sparse
== SPARSE_ALWAYS
);
1225 source_desc
= open (src_path
, O_RDONLY
);
1226 if (source_desc
< 0)
1228 error (0, errno
, "%s", src_path
);
1232 /* Create the new regular file with small permissions initially,
1233 to not create a security hole. */
1235 dest_desc
= open (dst_path
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0600);
1238 error (0, errno
, _("cannot create regular file `%s'"), dst_path
);
1243 /* Find out the optimal buffer size. */
1245 if (fstat (dest_desc
, &sb
))
1247 error (0, errno
, "%s", dst_path
);
1252 buf_size
= ST_BLKSIZE (sb
);
1254 #ifdef HAVE_ST_BLOCKS
1255 if (flag_sparse
== SPARSE_AUTO
&& S_ISREG (sb
.st_mode
))
1257 /* Use a heuristic to determine whether SRC_PATH contains any
1260 if (fstat (source_desc
, &sb
))
1262 error (0, errno
, "%s", src_path
);
1267 /* If the file has fewer blocks than would normally
1268 be needed for a file of its size, then
1269 at least one of the blocks in the file is a hole. */
1270 if (S_ISREG (sb
.st_mode
)
1271 && (size_t) (sb
.st_size
/ 512) > (size_t) ST_NBLOCKS (sb
))
1276 /* Make a buffer with space for a sentinel at the end. */
1278 buf
= (char *) alloca (buf_size
+ sizeof (int));
1282 n_read
= read (source_desc
, buf
, buf_size
);
1289 error (0, errno
, "%s", src_path
);
1296 n_read_total
+= n_read
;
1301 buf
[n_read
] = 1; /* Sentinel to stop loop. */
1303 /* Find first nonzero *word*, or the word with the sentinel. */
1309 /* Find the first nonzero *byte*, or the sentinel. */
1311 cp
= (char *) (ip
- 1);
1315 /* If we found the sentinel, the whole input block was zero,
1316 and we can make a hole. */
1318 if (cp
> buf
+ n_read
)
1321 if (lseek (dest_desc
, (off_t
) n_read
, SEEK_CUR
) < 0L)
1323 error (0, errno
, "%s", dst_path
);
1327 last_write_made_hole
= 1;
1330 /* Clear to indicate that a normal write is needed. */
1335 if (full_write (dest_desc
, buf
, n_read
) < 0)
1337 error (0, errno
, "%s", dst_path
);
1341 last_write_made_hole
= 0;
1345 /* If the file ends with a `hole', something needs to be written at
1346 the end. Otherwise the kernel would truncate the file at the end
1347 of the last write operation. */
1349 if (last_write_made_hole
)
1351 #ifdef HAVE_FTRUNCATE
1352 /* Write a null character and truncate it again. */
1353 if (full_write (dest_desc
, "", 1) < 0
1354 || ftruncate (dest_desc
, n_read_total
) < 0)
1356 /* Seek backwards one character and write a null. */
1357 if (lseek (dest_desc
, (off_t
) -1, SEEK_CUR
) < 0L
1358 || full_write (dest_desc
, "", 1) < 0)
1361 error (0, errno
, "%s", dst_path
);
1367 if (close (dest_desc
) < 0)
1369 error (0, errno
, "%s", dst_path
);
1373 if (close (source_desc
) < 0)
1375 error (0, errno
, "%s", src_path
);