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
41 # define LINK_CHOWN(FILE, OWNER, GROUP) lchown(FILE, OWNER, GROUP)
43 # define LINK_CHOWN(FILE, OWNER, GROUP) chown(FILE, OWNER, GROUP)
46 #define DO_CHOWN(FILE, NEW_UID, NEW_GID) \
47 (LINK_CHOWN ((FILE), (myeuid == 0 ? (NEW_UID) : myeuid), (NEW_GID)) \
48 /* If non-root uses -p, it's ok if we can't preserve ownership. \
49 But root probably wants to know, e.g. if NFS disallows it. */ \
50 && (errno != EPERM || myeuid == 0))
52 /* Used by do_copy, make_path_private, and re_protect
53 to keep a list of leading directories whose protections
54 need to be fixed after copying. */
59 struct dir_attr *next;
62 /* Control creation of sparse files (files with holes). */
65 /* Never create holes in DEST. */
68 /* This is the default. Use a crude (and sometimes inaccurate)
69 heuristic to determine if SOURCE has holes. If so, try to create
73 /* For every sufficiently long sequence of bytes in SOURCE, try to
74 create a corresponding hole in DEST. There is a performance penalty
75 here because CP has to search for holes in SRC. But if the holes are
76 big enough, that penalty can be offset by the decrease in the amount
77 of data written to disk. */
86 enum backup_type get_version ();
90 static int do_copy __P ((int argc, char **argv));
91 static int copy __P ((const char *src_path, const char *dst_path, int new_dst,
92 dev_t device, struct dir_list *ancestors));
93 static int copy_dir __P ((const char *src_path_in, const char *dst_path_in,
94 int new_dst, const struct stat *src_sb,
95 struct dir_list *ancestors));
96 static int make_path_private __P ((const char *const_dirpath, int src_offset,
97 int mode, const char *verbose_fmt_string,
98 struct dir_attr **attr_list, int *new_dst));
99 static int copy_reg __P ((const char *src_path, const char *dst_path));
100 static int re_protect __P ((const char *const_dst_path, int src_offset,
101 struct dir_attr *attr_list));
103 /* Initial number of entries in each hash table entry's table of inodes. */
104 #define INITIAL_HASH_MODULE 100
106 /* Initial number of entries in the inode hash table. */
107 #define INITIAL_ENTRY_TAB_SIZE 70
109 /* The invocation name of this program. */
112 /* A pointer to either lstat or stat, depending on
113 whether dereferencing of symlinks is done. */
114 static int (*xstat) ();
116 /* If nonzero, copy all files except (directories and, if not dereferencing
117 them, symbolic links,) as if they were regular files. */
118 static int flag_copy_as_regular = 1;
120 /* If nonzero, dereference symbolic links (copy the files they point to). */
121 static int flag_dereference = 1;
123 /* If nonzero, remove existing destination nondirectories. */
124 static int flag_force = 0;
126 /* If nonzero, create hard links instead of copying files.
127 Create destination directories as usual. */
128 static int flag_hard_link = 0;
130 /* If nonzero, query before overwriting existing destinations
131 with regular files. */
132 static int flag_interactive = 0;
134 /* If nonzero, the command "cp x/e_file e_dir" uses "e_dir/x/e_file"
135 as its destination instead of the usual "e_dir/e_file." */
136 static int flag_path = 0;
138 /* If nonzero, give the copies the original files' permissions,
139 ownership, and timestamps. */
140 static int flag_preserve = 0;
142 /* If nonzero, copy directories recursively and copy special files
143 as themselves rather than copying their contents. */
144 static int flag_recursive = 0;
146 /* If nonzero, create symbolic links instead of copying files.
147 Create destination directories as usual. */
148 static int flag_symbolic_link = 0;
150 /* If nonzero, when copying recursively, skip any subdirectories that are
151 on different filesystems from the one we started on. */
152 static int flag_one_file_system = 0;
154 /* If nonzero, do not copy a nondirectory that has an existing destination
155 with the same or newer modification time. */
156 static int flag_update = 0;
158 /* If nonzero, display the names of the files before copying them. */
159 static int flag_verbose = 0;
161 static char const *const sparse_type_string[] =
163 "never", "auto", "always", 0
166 static enum Sparse_type const sparse_type[] =
168 SPARSE_NEVER, SPARSE_AUTO, SPARSE_ALWAYS
171 /* Control creation of sparse files. */
172 static int flag_sparse = SPARSE_AUTO;
174 /* The error code to return to the system. */
175 static int exit_status = 0;
177 /* The bits to preserve in created files' modes. */
178 static int umask_kill;
180 /* This process's effective user ID. */
183 /* If nonzero, display usage information and exit. */
184 static int show_help;
186 /* If nonzero, print the version on standard output and exit. */
187 static int show_version;
189 static struct option const long_opts[] =
191 {"archive", no_argument, NULL, 'a'},
192 {"backup", no_argument, NULL, 'b'},
193 {"force", no_argument, NULL, 'f'},
194 {"sparse", required_argument, NULL, 2},
195 {"interactive", no_argument, NULL, 'i'},
196 {"link", no_argument, NULL, 'l'},
197 {"no-dereference", no_argument, &flag_dereference, 0},
198 {"one-file-system", no_argument, &flag_one_file_system, 1},
199 {"parents", no_argument, &flag_path, 1},
200 {"path", no_argument, &flag_path, 1},
201 {"preserve", no_argument, &flag_preserve, 1},
202 {"recursive", no_argument, NULL, 'R'},
203 {"suffix", required_argument, NULL, 'S'},
204 {"symbolic-link", no_argument, NULL, 's'},
205 {"update", no_argument, &flag_update, 1},
206 {"verbose", no_argument, &flag_verbose, 1},
207 {"version-control", required_argument, NULL, 'V'},
208 {"help", no_argument, &show_help, 1},
209 {"version", no_argument, &show_version, 1},
214 main (int argc, char **argv)
217 int make_backups = 0;
220 program_name = argv[0];
221 setlocale (LC_ALL, "");
222 bindtextdomain (PACKAGE, LOCALEDIR);
223 textdomain (PACKAGE);
227 version = getenv ("SIMPLE_BACKUP_SUFFIX");
229 simple_backup_suffix = version;
230 version = getenv ("VERSION_CONTROL");
232 /* Find out the current file creation mask, to knock the right bits
233 when using chmod. The creation mask is set to to be liberal, so
234 that created directories can be written, even if it would not
235 have been allowed with the mask this process was started with. */
237 umask_kill = 0777777 ^ umask (0);
239 while ((c = getopt_long (argc, argv, "abdfilprsuvxPRS:V:", long_opts,
251 /* --sparse={never,auto,always} */
252 i = argmatch (optarg, sparse_type_string);
255 invalid_arg (_("sparse type"), optarg, i);
258 flag_sparse = sparse_type[i];
262 case 'a': /* Like -dpR. */
263 flag_dereference = 0;
266 flag_copy_as_regular = 0;
274 flag_dereference = 0;
279 flag_interactive = 0;
284 flag_interactive = 1;
301 flag_copy_as_regular = 1;
306 flag_copy_as_regular = 0;
311 flag_symbolic_link = 1;
313 error (1, 0, _("symbolic links are not supported on this system"));
326 flag_one_file_system = 1;
330 simple_backup_suffix = optarg;
344 printf ("cp - %s\n", PACKAGE_VERSION);
351 if (flag_hard_link && flag_symbolic_link)
353 error (0, 0, _("cannot make both hard and symbolic links"));
358 backup_type = get_version (version);
360 if (flag_preserve == 1)
361 umask_kill = 0777777;
363 /* The key difference between -d (--no-dereference) and not is the version
364 of `stat' to call. */
366 if (flag_dereference)
371 /* Allocate space for remembering copied and created files. */
373 hash_init (INITIAL_HASH_MODULE, INITIAL_ENTRY_TAB_SIZE);
375 exit_status |= do_copy (argc, argv);
380 /* Scan the arguments, and copy each by calling copy.
381 Return 0 if successful, 1 if any errors occur. */
384 do_copy (int argc, char **argv)
393 error (0, 0, _("missing file arguments"));
396 if (optind >= argc - 1)
398 error (0, 0, _("missing destination file"));
402 dest = argv[argc - 1];
404 if (lstat (dest, &sb))
408 error (0, errno, "%s", dest);
418 /* If `dest' is not a symlink to a nonexistent file, use
419 the results of stat instead of lstat, so we can copy files
420 into symlinks to directories. */
421 if (stat (dest, &sbx) == 0)
425 if (!new_dst && S_ISDIR (sb.st_mode))
427 /* cp file1...filen edir
428 Copy the files `file1' through `filen'
429 to the existing directory `edir'. */
436 int parent_exists = 1; /* True if dirname (dst_path) exists. */
437 struct dir_attr *attr_list;
438 char *arg_in_concat = NULL;
442 strip_trailing_slashes (arg);
446 /* Append all of `arg' to `dest'. */
447 dst_path = path_concat (dest, arg, &arg_in_concat);
448 if (dst_path == NULL)
449 error (1, 0, _("virtual memory exhausted"));
451 /* For --parents, we have to make sure that the directory
452 dirname (dst_path) exists. We may have to create a few
453 leading directories. */
454 parent_exists = !make_path_private (dst_path,
455 arg_in_concat - dst_path,
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, NULL));
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, arg_in_concat - dst_path,
491 if (optind == argc - 1)
496 else if (argc - optind == 2)
500 struct stat source_stats;
505 _("when preserving paths, last argument must be a directory"));
509 source = argv[optind];
511 /* When the force and backup options have been specified and
512 the source and destination are the same name for an existing
513 regular file, convert the user's command, e.g.,
514 `cp --force --backup foo foo' to `cp --force foo fooSUFFIX'
515 where SUFFIX is determined by any version control options used. */
518 && backup_type != none
519 && STREQ (source, dest)
520 && !new_dst && S_ISREG (sb.st_mode))
522 new_dest = find_backup_file_name (dest);
523 /* Set backup_type to `none' so that the normal backup
524 mechanism is not used when performing the actual copy.
525 backup_type must be set to `none' only *after* the above
526 call to find_backup_file_name -- that function uses
527 backup_type to determine the suffix it applies. */
529 if (new_dest == NULL)
530 error (1, 0, _("virtual memory exhausted"));
533 /* When the destination is specified with a trailing slash and the
534 source exists but is not a directory, convert the user's command
535 `cp source dest/' to `cp source dest/basename(source)'. Doing
536 this ensures that the command `cp non-directory file/' will now
537 fail rather than performing the copy. COPY diagnoses the case of
538 `cp directory non-directory'. */
540 else if (dest[strlen (dest) - 1] == '/'
541 && lstat (source, &source_stats) == 0
542 && !S_ISDIR (source_stats.st_mode))
547 tmp_source = (char *) alloca (strlen (source) + 1);
548 strcpy (tmp_source, source);
549 strip_trailing_slashes (tmp_source);
550 source_base = basename (tmp_source);
552 new_dest = (char *) alloca (strlen (dest)
553 + strlen (source_base) + 1);
554 stpcpy (stpcpy (new_dest, dest), source_base);
561 return copy (source, new_dest, new_dst, 0, (struct dir_list *) 0);
566 _("copying multiple files, but last argument (%s) \
567 is not a directory"),
573 /* Copy the file SRC_PATH to the file DST_PATH. The files may be of
574 any type. NEW_DST should be nonzero if the file DST_PATH cannot
575 exist because its parent directory was just created; NEW_DST should
576 be zero if DST_PATH might already exist. DEVICE is the device
577 number of the parent directory, or 0 if the parent of this file is
578 not known. ANCESTORS points to a linked, null terminated list of
579 devices and inodes of parent directories of SRC_PATH.
580 Return 0 if successful, 1 if an error occurs. */
583 copy (const char *src_path, const char *dst_path, int new_dst, dev_t device,
584 struct dir_list *ancestors)
591 char *dst_backup = NULL;
594 if ((*xstat) (src_path, &src_sb))
596 error (0, errno, "%s", src_path);
600 /* Are we crossing a file system boundary? */
601 if (flag_one_file_system && device != 0 && device != src_sb.st_dev)
604 /* We wouldn't insert a node unless nlink > 1, except that we need to
605 find created files so as to not copy infinitely if a directory is
606 copied into itself. */
608 earlier_file = remember_copied (dst_path, src_sb.st_ino, src_sb.st_dev);
610 /* Did we just create this file? */
612 if (earlier_file == &new_file)
615 src_mode = src_sb.st_mode;
616 src_type = src_sb.st_mode;
618 if (S_ISDIR (src_type) && !flag_recursive)
620 error (0, 0, _("%s: omitting directory"), src_path);
626 if ((*xstat) (dst_path, &dst_sb))
630 error (0, errno, "%s", dst_path);
638 /* The file exists already. */
640 if (src_sb.st_ino == dst_sb.st_ino && src_sb.st_dev == dst_sb.st_dev)
645 error (0, 0, _("`%s' and `%s' are the same file"),
650 if (!S_ISDIR (src_type))
652 if (S_ISDIR (dst_sb.st_mode))
655 _("%s: cannot overwrite directory with non-directory"),
660 if (flag_update && src_sb.st_mtime <= dst_sb.st_mtime)
664 if (S_ISREG (src_type) && !flag_force)
666 if (flag_interactive)
668 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));
674 fprintf (stderr, _("%s: overwrite `%s'? "),
675 program_name, dst_path);
681 if (backup_type != none && !S_ISDIR (dst_sb.st_mode))
683 char *tmp_backup = find_backup_file_name (dst_path);
684 if (tmp_backup == NULL)
685 error (1, 0, _("virtual memory exhausted"));
687 /* Detect (and fail) when creating the backup file would
688 destroy the source file. Before, running the commands
689 cd /tmp; rm -f a a~; : > a; echo A > a~; cp -b -V simple a~ a
690 would leave two zero-length files: a and a~. */
691 if (STREQ (tmp_backup, src_path))
694 _("backing up `%s' would destroy source; `%s' not copied"),
699 dst_backup = (char *) alloca (strlen (tmp_backup) + 1);
700 strcpy (dst_backup, tmp_backup);
702 if (rename (dst_path, dst_backup))
706 error (0, errno, _("cannot backup `%s'"), dst_path);
716 if (S_ISDIR (dst_sb.st_mode))
718 /* Temporarily change mode to allow overwriting. */
719 if (euidaccess (dst_path, W_OK | X_OK) != 0)
721 if (chmod (dst_path, 0700))
723 error (0, errno, "%s", dst_path);
732 if (unlink (dst_path) && errno != ENOENT)
734 error (0, errno, _("cannot remove old link to `%s'"),
744 /* If the source is a directory, we don't always create the destination
745 directory. So --verbose should not announce anything until we're
746 sure we'll create a directory. */
747 if (flag_verbose && !S_ISDIR (src_type))
748 printf ("%s -> %s\n", src_path, dst_path);
750 /* Did we copy this inode somewhere else (in this command line argument)
751 and therefore this is a second hard link to the inode? */
753 if (!flag_dereference && src_sb.st_nlink > 1 && earlier_file)
755 if (link (earlier_file, dst_path))
757 error (0, errno, "%s", dst_path);
763 if (S_ISDIR (src_type))
765 struct dir_list *dir;
767 /* If this directory has been copied before during the
768 recursion, there is a symbolic link to an ancestor
769 directory of the symbolic link. It is impossible to
770 continue to copy this, unless we've got an infinite disk. */
772 if (is_ancestor (&src_sb, ancestors))
774 error (0, 0, _("%s: cannot copy cyclic symbolic link"), src_path);
778 /* Insert the current directory in the list of parents. */
780 dir = (struct dir_list *) alloca (sizeof (struct dir_list));
781 dir->parent = ancestors;
782 dir->ino = src_sb.st_ino;
783 dir->dev = src_sb.st_dev;
785 if (new_dst || !S_ISDIR (dst_sb.st_mode))
787 /* Create the new directory writable and searchable, so
788 we can create new entries in it. */
790 if (mkdir (dst_path, (src_mode & umask_kill) | 0700))
792 error (0, errno, _("cannot create directory `%s'"), dst_path);
796 /* Insert the created directory's inode and device
797 numbers into the search structure, so that we can
798 avoid copying it again. */
800 if (remember_created (dst_path))
804 printf ("%s -> %s\n", src_path, dst_path);
807 /* Copy the contents of the directory. */
809 if (copy_dir (src_path, dst_path, new_dst, &src_sb, dir))
813 else if (flag_symbolic_link)
816 || (!strncmp (dst_path, "./", 2) && strchr (dst_path + 2, '/') == 0)
817 || strchr (dst_path, '/') == 0)
819 if (symlink (src_path, dst_path))
821 error (0, errno, "%s", dst_path);
825 /* Change the owner and group of the just-created symbolic link
826 if this system has the lchown function. */
829 && DO_CHOWN (dst_path, src_sb.st_uid, src_sb.st_gid))
831 error (0, errno, "%s", dst_path);
841 _("%s: can make relative symbolic links only in current directory"),
847 else if (flag_hard_link)
849 if (link (src_path, dst_path))
851 error (0, errno, _("cannot create link `%s'"), dst_path);
856 else if (S_ISREG (src_type)
857 || (flag_copy_as_regular && !S_ISDIR (src_type)
859 && !S_ISLNK (src_type)
863 if (copy_reg (src_path, dst_path))
868 if (S_ISFIFO (src_type))
870 if (mkfifo (dst_path, src_mode & umask_kill))
872 error (0, errno, _("cannot create fifo `%s'"), dst_path);
878 if (S_ISBLK (src_type) || S_ISCHR (src_type)
880 || S_ISSOCK (src_type)
884 if (mknod (dst_path, src_mode & umask_kill, src_sb.st_rdev))
886 error (0, errno, _("cannot create special file `%s'"), dst_path);
892 if (S_ISLNK (src_type))
897 link_val = (char *) alloca (PATH_MAX + 2);
898 link_size = readlink (src_path, link_val, PATH_MAX + 1);
901 error (0, errno, _("cannot read symbolic link `%s'"), src_path);
904 link_val[link_size] = '\0';
906 if (symlink (link_val, dst_path))
908 error (0, errno, _("cannot create symbolic link `%s'"), dst_path);
912 /* Change the owner and group of the just-created symbolic link
913 if this system has the lchown function. */
916 && DO_CHOWN (dst_path, src_sb.st_uid, src_sb.st_gid))
918 error (0, errno, "%s", dst_path);
928 error (0, 0, _("%s: unknown file type"), src_path);
932 /* Adjust the times (and if possible, ownership) for the copy.
933 chown turns off set[ug]id bits for non-root,
934 so do the chmod last. */
940 utb.actime = src_sb.st_atime;
941 utb.modtime = src_sb.st_mtime;
943 if (utime (dst_path, &utb))
945 error (0, errno, "%s", dst_path);
949 if (DO_CHOWN (dst_path, src_sb.st_uid, src_sb.st_gid))
951 error (0, errno, "%s", dst_path);
956 if ((flag_preserve || new_dst)
957 && (flag_copy_as_regular || S_ISREG (src_type) || S_ISDIR (src_type)))
959 if (chmod (dst_path, src_mode & umask_kill))
961 error (0, errno, "%s", dst_path);
967 /* Reset the temporarily changed mode. */
968 if (chmod (dst_path, dst_sb.st_mode))
970 error (0, errno, "%s", dst_path);
980 if (rename (dst_backup, dst_path))
981 error (0, errno, _("cannot un-backup `%s'"), dst_path);
986 /* Ensure that the parent directory of CONST_DIRPATH exists, for
987 the --parents option.
989 SRC_OFFSET is the index in CONST_DIRPATH (which is a destination
990 path) of the beginning of the source directory name.
991 Create any leading directories that don't already exist,
992 giving them permissions MODE.
993 If VERBOSE_FMT_STRING is nonzero, use it as a printf format
994 string for printing a message after successfully making a directory.
995 The format should take two string arguments: the names of the
996 source and destination directories.
997 Creates a linked list of attributes of intermediate directories,
998 *ATTR_LIST, for re_protect to use after calling copy.
999 Sets *NEW_DST to 1 if this function creates parent of CONST_DIRPATH.
1001 Return 0 if parent of CONST_DIRPATH exists as a directory with the proper
1002 permissions when done, otherwise 1. */
1005 make_path_private (const char *const_dirpath, int src_offset, int mode,
1006 const char *verbose_fmt_string, struct dir_attr **attr_list,
1010 char *dirpath; /* A copy of CONST_DIRPATH we can change. */
1011 char *src; /* Source name in `dirpath'. */
1012 char *tmp_dst_dirname; /* Leading path of `dirpath', malloc. */
1013 char *dst_dirname; /* Leading path of `dirpath', alloca. */
1015 dirpath = (char *) alloca (strlen (const_dirpath) + 1);
1016 strcpy (dirpath, const_dirpath);
1018 src = dirpath + src_offset;
1020 tmp_dst_dirname = dirname (dirpath);
1021 dst_dirname = (char *) alloca (strlen (tmp_dst_dirname) + 1);
1022 strcpy (dst_dirname, tmp_dst_dirname);
1023 free (tmp_dst_dirname);
1027 if ((*xstat) (dst_dirname, &stats))
1029 /* Parent of CONST_DIRNAME does not exist.
1030 Make all missing intermediate directories. */
1034 while (*slash == '/')
1036 while ((slash = strchr (slash, '/')))
1038 /* Add this directory to the list of directories whose modes need
1040 struct dir_attr *new =
1041 (struct dir_attr *) xmalloc (sizeof (struct dir_attr));
1042 new->slash_offset = slash - dirpath;
1043 new->next = *attr_list;
1047 if ((*xstat) (dirpath, &stats))
1049 /* This element of the path does not exist. We must set
1050 *new_dst and new->is_new_dir inside this loop because,
1051 for example, in the command `cp --parents ../a/../b/c e_dir',
1052 make_path_private creates only e_dir/../a if ./b already
1055 new->is_new_dir = 1;
1056 if (mkdir (dirpath, mode))
1058 error (0, errno, _("cannot make directory `%s'"), dirpath);
1063 if (verbose_fmt_string != NULL)
1064 printf (verbose_fmt_string, src, dirpath);
1067 else if (!S_ISDIR (stats.st_mode))
1069 error (0, 0, _("`%s' exists but is not a directory"), dirpath);
1074 new->is_new_dir = 0;
1079 /* Avoid unnecessary calls to `stat' when given
1080 pathnames containing multiple adjacent slashes. */
1081 while (*slash == '/')
1086 /* We get here if the parent of `dirpath' already exists. */
1088 else if (!S_ISDIR (stats.st_mode))
1090 error (0, 0, _("`%s' exists but is not a directory"), dst_dirname);
1100 /* Ensure that the parent directories of CONST_DST_PATH have the
1101 correct protections, for the --parents option. This is done
1102 after all copying has been completed, to allow permissions
1103 that don't include user write/execute.
1105 SRC_OFFSET is the index in CONST_DST_PATH of the beginning of the
1106 source directory name.
1108 ATTR_LIST is a null-terminated linked list of structures that
1109 indicates the end of the filename of each intermediate directory
1110 in CONST_DST_PATH that may need to have its attributes changed.
1111 The command `cp --parents --preserve a/b/c d/e_dir' changes the
1112 attributes of the directories d/e_dir/a and d/e_dir/a/b to match
1113 the corresponding source directories regardless of whether they
1114 existed before the `cp' command was given.
1116 Return 0 if the parent of CONST_DST_PATH and any intermediate
1117 directories specified by ATTR_LIST have the proper permissions
1118 when done, otherwise 1. */
1121 re_protect (const char *const_dst_path, int src_offset,
1122 struct dir_attr *attr_list)
1125 char *dst_path; /* A copy of CONST_DST_PATH we can change. */
1126 char *src_path; /* The source name in `dst_path'. */
1128 dst_path = (char *) alloca (strlen (const_dst_path) + 1);
1129 strcpy (dst_path, const_dst_path);
1130 src_path = dst_path + src_offset;
1132 for (p = attr_list; p; p = p->next)
1136 dst_path[p->slash_offset] = '\0';
1138 if ((*xstat) (src_path, &src_sb))
1140 error (0, errno, "%s", src_path);
1144 /* Adjust the times (and if possible, ownership) for the copy.
1145 chown turns off set[ug]id bits for non-root,
1146 so do the chmod last. */
1152 utb.actime = src_sb.st_atime;
1153 utb.modtime = src_sb.st_mtime;
1155 if (utime (dst_path, &utb))
1157 error (0, errno, "%s", dst_path);
1161 /* If non-root uses -p, it's ok if we can't preserve ownership.
1162 But root probably wants to know, e.g. if NFS disallows it. */
1163 if (chown (dst_path, src_sb.st_uid, src_sb.st_gid)
1164 && (errno != EPERM || myeuid == 0))
1166 error (0, errno, "%s", dst_path);
1171 if (flag_preserve || p->is_new_dir)
1173 if (chmod (dst_path, src_sb.st_mode & umask_kill))
1175 error (0, errno, "%s", dst_path);
1180 dst_path[p->slash_offset] = '/';
1185 /* Read the contents of the directory SRC_PATH_IN, and recursively
1186 copy the contents to DST_PATH_IN. NEW_DST is nonzero if
1187 DST_PATH_IN is a directory that was created previously in the
1188 recursion. SRC_SB and ANCESTORS describe SRC_PATH_IN.
1189 Return 0 if successful, -1 if an error occurs. */
1192 copy_dir (const char *src_path_in, const char *dst_path_in, int new_dst,
1193 const struct stat *src_sb, struct dir_list *ancestors)
1202 name_space = savedir (src_path_in, src_sb->st_size);
1203 if (name_space == 0)
1207 error (0, errno, "%s", src_path_in);
1211 error (1, 0, _("virtual memory exhausted"));
1215 while (*namep != '\0')
1217 int fn_length = strlen (namep) + 1;
1219 dst_path = xmalloc (strlen (dst_path_in) + fn_length + 1);
1220 src_path = xmalloc (strlen (src_path_in) + fn_length + 1);
1222 stpcpy (stpcpy (stpcpy (src_path, src_path_in), "/"), namep);
1223 stpcpy (stpcpy (stpcpy (dst_path, dst_path_in), "/"), namep);
1225 ret |= copy (src_path, dst_path, new_dst, src_sb->st_dev, ancestors);
1227 /* Free the memory for `src_path'. The memory for `dst_path'
1228 cannot be deallocated, since it is used to create multiple
1239 /* Copy a regular file from SRC_PATH to DST_PATH.
1240 If the source file contains holes, copies holes and blocks of zeros
1241 in the source file as holes in the destination file.
1242 (Holes are read as zeroes by the `read' system call.)
1243 Return 0 if successful, -1 if an error occurred. */
1246 copy_reg (const char *src_path, const char *dst_path)
1257 long n_read_total = 0;
1258 int last_write_made_hole = 0;
1259 int make_holes = (flag_sparse == SPARSE_ALWAYS);
1261 source_desc = open (src_path, O_RDONLY);
1262 if (source_desc < 0)
1264 error (0, errno, "%s", src_path);
1268 /* Create the new regular file with small permissions initially,
1269 to not create a security hole. */
1271 dest_desc = open (dst_path, O_WRONLY | O_CREAT | O_TRUNC, 0600);
1274 error (0, errno, _("cannot create regular file `%s'"), dst_path);
1279 /* Find out the optimal buffer size. */
1281 if (fstat (dest_desc, &sb))
1283 error (0, errno, "%s", dst_path);
1288 buf_size = ST_BLKSIZE (sb);
1290 #ifdef HAVE_ST_BLOCKS
1291 if (flag_sparse == SPARSE_AUTO && S_ISREG (sb.st_mode))
1293 /* Use a heuristic to determine whether SRC_PATH contains any
1296 if (fstat (source_desc, &sb))
1298 error (0, errno, "%s", src_path);
1303 /* If the file has fewer blocks than would normally
1304 be needed for a file of its size, then
1305 at least one of the blocks in the file is a hole. */
1306 if (S_ISREG (sb.st_mode)
1307 && (size_t) (sb.st_size / 512) > (size_t) ST_NBLOCKS (sb))
1312 /* Make a buffer with space for a sentinel at the end. */
1314 buf = (char *) alloca (buf_size + sizeof (int));
1318 n_read = read (source_desc, buf, buf_size);
1325 error (0, errno, "%s", src_path);
1332 n_read_total += n_read;
1337 buf[n_read] = 1; /* Sentinel to stop loop. */
1339 /* Find first nonzero *word*, or the word with the sentinel. */
1345 /* Find the first nonzero *byte*, or the sentinel. */
1347 cp = (char *) (ip - 1);
1351 /* If we found the sentinel, the whole input block was zero,
1352 and we can make a hole. */
1354 if (cp > buf + n_read)
1357 if (lseek (dest_desc, (off_t) n_read, SEEK_CUR) < 0L)
1359 error (0, errno, "%s", dst_path);
1363 last_write_made_hole = 1;
1366 /* Clear to indicate that a normal write is needed. */
1371 if (full_write (dest_desc, buf, n_read) < 0)
1373 error (0, errno, "%s", dst_path);
1377 last_write_made_hole = 0;
1381 /* If the file ends with a `hole', something needs to be written at
1382 the end. Otherwise the kernel would truncate the file at the end
1383 of the last write operation. */
1385 if (last_write_made_hole)
1387 #ifdef HAVE_FTRUNCATE
1388 /* Write a null character and truncate it again. */
1389 if (full_write (dest_desc, "", 1) < 0
1390 || ftruncate (dest_desc, n_read_total) < 0)
1392 /* Seek backwards one character and write a null. */
1393 if (lseek (dest_desc, (off_t) -1, SEEK_CUR) < 0L
1394 || full_write (dest_desc, "", 1) < 0)
1397 error (0, errno, "%s", dst_path);
1403 if (close (dest_desc) < 0)
1405 error (0, errno, "%s", dst_path);
1409 if (close (source_desc) < 0)
1411 error (0, errno, "%s", src_path);