.
[coreutils.git] / src / cp.c
blob553e93bf858af7a3bac9f0bfd54a290f6cda3a16
1 /* cp.c -- file copying (main routines)
2 Copyright (C) 1989, 1990, 1991, 1995 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)
7 any later version.
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
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. */
20 #ifdef _AIX
21 #pragma alloca
22 #endif
24 #include <config.h>
25 #include <stdio.h>
26 #include <getopt.h>
27 #include "cp.h"
28 #include "backupfile.h"
29 #include "version.h"
31 #ifndef _POSIX_VERSION
32 uid_t geteuid ();
33 #endif
35 /* Used by do_copy, make_path_private, and re_protect
36 to keep a list of leading directories whose protections
37 need to be fixed after copying. */
38 struct dir_attr
40 int is_new_dir;
41 int slash_offset;
42 struct dir_attr *next;
45 int stat ();
46 int lstat ();
48 char *dirname ();
49 char *xstrdup ();
50 enum backup_type get_version ();
51 int euidaccess ();
52 int full_write ();
54 static int do_copy __P ((int argc, char **argv));
55 static int copy __P ((char *src_path, char *dst_path, int new_dst,
56 dev_t device, struct dir_list *ancestors));
57 static int copy_dir __P ((char *src_path_in, char *dst_path_in, int new_dst,
58 struct stat *src_sb, struct dir_list *ancestors));
59 static int make_path_private __P ((char *const_dirpath, int src_offset,
60 int mode, char *verbose_fmt_string,
61 struct dir_attr **attr_list, int *new_dst));
62 static int copy_reg __P ((char *src_path, char *dst_path));
63 static int re_protect __P ((char *const_dst_path, int src_offset,
64 struct dir_attr *attr_list));
66 /* Initial number of entries in each hash table entry's table of inodes. */
67 #define INITIAL_HASH_MODULE 100
69 /* Initial number of entries in the inode hash table. */
70 #define INITIAL_ENTRY_TAB_SIZE 70
72 /* The invocation name of this program. */
73 char *program_name;
75 /* A pointer to either lstat or stat, depending on
76 whether dereferencing of symlinks is done. */
77 static int (*xstat) ();
79 /* If nonzero, copy all files except (directories and, if not dereferencing
80 them, symbolic links,) as if they were regular files. */
81 static int flag_copy_as_regular = 1;
83 /* If nonzero, dereference symbolic links (copy the files they point to). */
84 static int flag_dereference = 1;
86 /* If nonzero, remove existing destination nondirectories. */
87 static int flag_force = 0;
89 /* If nonzero, create hard links instead of copying files.
90 Create destination directories as usual. */
91 static int flag_hard_link = 0;
93 /* If nonzero, query before overwriting existing destinations
94 with regular files. */
95 static int flag_interactive = 0;
97 /* If nonzero, the command "cp x/e_file e_dir" uses "e_dir/x/e_file"
98 as its destination instead of the usual "e_dir/e_file." */
99 static int flag_path = 0;
101 /* If nonzero, give the copies the original files' permissions,
102 ownership, and timestamps. */
103 static int flag_preserve = 0;
105 /* If nonzero, copy directories recursively and copy special files
106 as themselves rather than copying their contents. */
107 static int flag_recursive = 0;
109 /* If nonzero, create symbolic links instead of copying files.
110 Create destination directories as usual. */
111 static int flag_symbolic_link = 0;
113 /* If nonzero, when copying recursively, skip any subdirectories that are
114 on different filesystems from the one we started on. */
115 static int flag_one_file_system = 0;
117 /* If nonzero, do not copy a nondirectory that has an existing destination
118 with the same or newer modification time. */
119 static int flag_update = 0;
121 /* If nonzero, display the names of the files before copying them. */
122 static int flag_verbose = 0;
124 /* The error code to return to the system. */
125 static int exit_status = 0;
127 /* The bits to preserve in created files' modes. */
128 static int umask_kill;
130 /* This process's effective user ID. */
131 static uid_t myeuid;
133 /* If nonzero, display usage information and exit. */
134 static int show_help;
136 /* If nonzero, print the version on standard output and exit. */
137 static int show_version;
139 static struct option const long_opts[] =
141 {"archive", no_argument, NULL, 'a'},
142 {"backup", no_argument, NULL, 'b'},
143 {"force", no_argument, NULL, 'f'},
144 {"interactive", no_argument, NULL, 'i'},
145 {"link", no_argument, NULL, 'l'},
146 {"no-dereference", no_argument, &flag_dereference, 0},
147 {"one-file-system", no_argument, &flag_one_file_system, 1},
148 {"parents", no_argument, &flag_path, 1},
149 {"path", no_argument, &flag_path, 1},
150 {"preserve", no_argument, &flag_preserve, 1},
151 {"recursive", no_argument, NULL, 'R'},
152 {"suffix", required_argument, NULL, 'S'},
153 {"symbolic-link", no_argument, NULL, 's'},
154 {"update", no_argument, &flag_update, 1},
155 {"verbose", no_argument, &flag_verbose, 1},
156 {"version-control", required_argument, NULL, 'V'},
157 {"help", no_argument, &show_help, 1},
158 {"version", no_argument, &show_version, 1},
159 {NULL, 0, NULL, 0}
162 void
163 main (int argc, char **argv)
165 int c;
166 int make_backups = 0;
167 char *version;
169 program_name = argv[0];
170 myeuid = geteuid ();
172 version = getenv ("SIMPLE_BACKUP_SUFFIX");
173 if (version)
174 simple_backup_suffix = version;
175 version = getenv ("VERSION_CONTROL");
177 /* Find out the current file creation mask, to knock the right bits
178 when using chmod. The creation mask is set to to be liberal, so
179 that created directories can be written, even if it would not
180 have been allowed with the mask this process was started with. */
182 umask_kill = 0777777 ^ umask (0);
184 while ((c = getopt_long (argc, argv, "abdfilprsuvxPRS:V:", long_opts,
185 (int *) 0)) != EOF)
187 switch (c)
189 case 0:
190 break;
192 case 'a': /* Like -dpR. */
193 flag_dereference = 0;
194 flag_preserve = 1;
195 flag_recursive = 1;
196 flag_copy_as_regular = 0;
197 break;
199 case 'b':
200 make_backups = 1;
201 break;
203 case 'd':
204 flag_dereference = 0;
205 break;
207 case 'f':
208 flag_force = 1;
209 flag_interactive = 0;
210 break;
212 case 'i':
213 flag_force = 0;
214 flag_interactive = 1;
215 break;
217 case 'l':
218 flag_hard_link = 1;
219 break;
221 case 'p':
222 flag_preserve = 1;
223 break;
225 case 'P':
226 flag_path = 1;
227 break;
229 case 'r':
230 flag_recursive = 1;
231 flag_copy_as_regular = 1;
232 break;
234 case 'R':
235 flag_recursive = 1;
236 flag_copy_as_regular = 0;
237 break;
239 case 's':
240 #ifdef S_ISLNK
241 flag_symbolic_link = 1;
242 #else
243 error (1, 0, _("symbolic links are not supported on this system"));
244 #endif
245 break;
247 case 'u':
248 flag_update = 1;
249 break;
251 case 'v':
252 flag_verbose = 1;
253 break;
255 case 'x':
256 flag_one_file_system = 1;
257 break;
259 case 'S':
260 simple_backup_suffix = optarg;
261 break;
263 case 'V':
264 version = optarg;
265 break;
267 default:
268 usage (2, (char *) 0);
272 if (show_version)
274 printf ("cp - %s\n", version_string);
275 exit (0);
278 if (show_help)
279 usage (0, NULL);
281 if (flag_hard_link && flag_symbolic_link)
282 usage (2, _("cannot make both hard and symbolic links"));
284 if (make_backups)
285 backup_type = get_version (version);
287 if (flag_preserve == 1)
288 umask_kill = 0777777;
290 /* The key difference between -d (--no-dereference) and not is the version
291 of `stat' to call. */
293 if (flag_dereference)
294 xstat = stat;
295 else
296 xstat = lstat;
298 /* Allocate space for remembering copied and created files. */
300 hash_init (INITIAL_HASH_MODULE, INITIAL_ENTRY_TAB_SIZE);
302 exit_status |= do_copy (argc, argv);
304 exit (exit_status);
307 /* Scan the arguments, and copy each by calling copy.
308 Return 0 if successful, 1 if any errors occur. */
310 static int
311 do_copy (int argc, char **argv)
313 char *dest;
314 struct stat sb;
315 int new_dst = 0;
316 int ret = 0;
318 if (optind >= argc)
319 usage (2, _("missing file arguments"));
320 if (optind >= argc - 1)
321 usage (2, _("missing file argument"));
323 dest = argv[argc - 1];
325 if (lstat (dest, &sb))
327 if (errno != ENOENT)
329 error (0, errno, "%s", dest);
330 return 1;
332 else
333 new_dst = 1;
335 else
337 struct stat sbx;
339 /* If `dest' is not a symlink to a nonexistent file, use
340 the results of stat instead of lstat, so we can copy files
341 into symlinks to directories. */
342 if (stat (dest, &sbx) == 0)
343 sb = sbx;
346 if (!new_dst && S_ISDIR (sb.st_mode))
348 /* cp file1...filen edir
349 Copy the files `file1' through `filen'
350 to the existing directory `edir'. */
352 for (;;)
354 char *arg;
355 char *ap;
356 char *dst_path;
357 int parent_exists = 1; /* True if dirname (dst_path) exists. */
358 struct dir_attr *attr_list;
360 arg = argv[optind];
362 strip_trailing_slashes (arg);
364 if (flag_path)
366 /* Append all of `arg' to `dest'. */
367 dst_path = xmalloc (strlen (dest) + strlen (arg) + 2);
368 stpcpy (stpcpy (stpcpy (dst_path, dest), "/"), arg);
370 /* For --parents, we have to make sure that the directory
371 dirname (dst_path) exists. We may have to create a few
372 leading directories. */
373 parent_exists = !make_path_private (dst_path,
374 strlen (dest) + 1, 0700,
375 flag_verbose ? "%s -> %s\n" :
376 (char *) NULL,
377 &attr_list, &new_dst);
379 else
381 /* Append the last component of `arg' to `dest'. */
383 ap = basename (arg);
384 /* For `cp -R source/.. dest', don't copy into `dest/..'. */
385 if (!strcmp (ap, ".."))
386 dst_path = xstrdup (dest);
387 else
389 dst_path = xmalloc (strlen (dest) + strlen (ap) + 2);
390 stpcpy (stpcpy (stpcpy (dst_path, dest), "/"), ap);
394 if (!parent_exists)
396 /* make_path_private failed, so we shouldn't even attempt the copy. */
397 ret = 1;
399 else
401 ret |= copy (arg, dst_path, new_dst, 0, (struct dir_list *) 0);
402 forget_all ();
404 if (flag_path)
406 ret |= re_protect (dst_path, strlen (dest) + 1,
407 attr_list);
411 free (dst_path);
412 ++optind;
413 if (optind == argc - 1)
414 break;
416 return ret;
418 else if (argc - optind == 2)
420 char *new_dest;
421 char *source;
422 struct stat source_stats;
424 if (flag_path)
425 usage (2, _("when preserving paths, last argument must be a directory"));
427 source = argv[optind];
429 /* When the destination is specified with a trailing slash and the
430 source exists but is not a directory, convert the user's command
431 `cp source dest/' to `cp source dest/basename(source)'. */
433 if (dest[strlen (dest) - 1] == '/'
434 && lstat (source, &source_stats) == 0
435 && !S_ISDIR (source_stats.st_mode))
437 char *source_base;
438 char *tmp_source;
440 tmp_source = (char *) alloca (strlen (source) + 1);
441 strcpy (tmp_source, source);
442 strip_trailing_slashes (tmp_source);
443 source_base = basename (tmp_source);
445 new_dest = (char *) alloca (strlen (dest) + 1 +
446 strlen (source_base) + 1);
447 stpcpy (stpcpy (stpcpy (new_dest, dest), "/"), source_base);
449 else
451 new_dest = dest;
454 return copy (source, new_dest, new_dst, 0, (struct dir_list *) 0);
456 else
457 usage (2,
458 _("when copying multiple files, last argument must be a directory"));
461 /* Copy the file SRC_PATH to the file DST_PATH. The files may be of
462 any type. NEW_DST should be nonzero if the file DST_PATH cannot
463 exist because its parent directory was just created; NEW_DST should
464 be zero if DST_PATH might already exist. DEVICE is the device
465 number of the parent directory, or 0 if the parent of this file is
466 not known. ANCESTORS points to a linked, null terminated list of
467 devices and inodes of parent directories of SRC_PATH.
468 Return 0 if successful, 1 if an error occurs. */
470 static int
471 copy (char *src_path, char *dst_path, int new_dst, dev_t device,
472 struct dir_list *ancestors)
474 struct stat src_sb;
475 struct stat dst_sb;
476 int src_mode;
477 int src_type;
478 char *earlier_file;
479 char *dst_backup = NULL;
480 int fix_mode = 0;
482 if ((*xstat) (src_path, &src_sb))
484 error (0, errno, "%s", src_path);
485 return 1;
488 /* Are we crossing a file system boundary? */
489 if (flag_one_file_system && device != 0 && device != src_sb.st_dev)
490 return 0;
492 /* We wouldn't insert a node unless nlink > 1, except that we need to
493 find created files so as to not copy infinitely if a directory is
494 copied into itself. */
496 earlier_file = remember_copied (dst_path, src_sb.st_ino, src_sb.st_dev);
498 /* Did we just create this file? */
500 if (earlier_file == &new_file)
501 return 0;
503 src_mode = src_sb.st_mode;
504 src_type = src_sb.st_mode;
506 if (S_ISDIR (src_type) && !flag_recursive)
508 error (0, 0, _("%s: omitting directory"), src_path);
509 return 1;
512 if (!new_dst)
514 if ((*xstat) (dst_path, &dst_sb))
516 if (errno != ENOENT)
518 error (0, errno, "%s", dst_path);
519 return 1;
521 else
522 new_dst = 1;
524 else
526 /* The file exists already. */
528 if (src_sb.st_ino == dst_sb.st_ino && src_sb.st_dev == dst_sb.st_dev)
530 if (flag_hard_link)
531 return 0;
533 error (0, 0, _("`%s' and `%s' are the same file"),
534 src_path, dst_path);
535 return 1;
538 if (!S_ISDIR (src_type))
540 if (S_ISDIR (dst_sb.st_mode))
542 error (0, 0,
543 _("%s: cannot overwrite directory with non-directory"),
544 dst_path);
545 return 1;
548 if (flag_update && src_sb.st_mtime <= dst_sb.st_mtime)
549 return 0;
552 if (S_ISREG (src_type) && !flag_force)
554 if (flag_interactive)
556 if (euidaccess (dst_path, W_OK) != 0)
557 fprintf (stderr,
558 _("%s: overwrite `%s', overriding mode %04o? "),
559 program_name, dst_path,
560 (unsigned int) (dst_sb.st_mode & 07777));
561 else
562 fprintf (stderr, _("%s: overwrite `%s'? "),
563 program_name, dst_path);
564 if (!yesno ())
565 return 0;
569 if (backup_type != none && !S_ISDIR (dst_sb.st_mode))
571 char *tmp_backup = find_backup_file_name (dst_path);
572 if (tmp_backup == NULL)
573 error (1, 0, _("virtual memory exhausted"));
574 dst_backup = (char *) alloca (strlen (tmp_backup) + 1);
575 strcpy (dst_backup, tmp_backup);
576 free (tmp_backup);
577 if (rename (dst_path, dst_backup))
579 if (errno != ENOENT)
581 error (0, errno, _("cannot backup `%s'"), dst_path);
582 return 1;
584 else
585 dst_backup = NULL;
587 new_dst = 1;
589 else if (flag_force)
591 if (S_ISDIR (dst_sb.st_mode))
593 /* Temporarily change mode to allow overwriting. */
594 if (euidaccess (dst_path, W_OK | X_OK) != 0)
596 if (chmod (dst_path, 0700))
598 error (0, errno, "%s", dst_path);
599 return 1;
601 else
602 fix_mode = 1;
605 else
607 if (unlink (dst_path) && errno != ENOENT)
609 error (0, errno, _("cannot remove old link to `%s'"),
610 dst_path);
611 return 1;
613 new_dst = 1;
619 /* If the source is a directory, we don't always create the destination
620 directory. So --verbose should not announce anything until we're
621 sure we'll create a directory. */
622 if (flag_verbose && !S_ISDIR (src_type))
623 printf ("%s -> %s\n", src_path, dst_path);
625 /* Did we copy this inode somewhere else (in this command line argument)
626 and therefore this is a second hard link to the inode? */
628 if (!flag_dereference && src_sb.st_nlink > 1 && earlier_file)
630 if (link (earlier_file, dst_path))
632 error (0, errno, "%s", dst_path);
633 goto un_backup;
635 return 0;
638 if (S_ISDIR (src_type))
640 struct dir_list *dir;
642 /* If this directory has been copied before during the
643 recursion, there is a symbolic link to an ancestor
644 directory of the symbolic link. It is impossible to
645 continue to copy this, unless we've got an infinite disk. */
647 if (is_ancestor (&src_sb, ancestors))
649 error (0, 0, _("%s: cannot copy cyclic symbolic link"), src_path);
650 goto un_backup;
653 /* Insert the current directory in the list of parents. */
655 dir = (struct dir_list *) alloca (sizeof (struct dir_list));
656 dir->parent = ancestors;
657 dir->ino = src_sb.st_ino;
658 dir->dev = src_sb.st_dev;
660 if (new_dst || !S_ISDIR (dst_sb.st_mode))
662 /* Create the new directory writable and searchable, so
663 we can create new entries in it. */
665 if (mkdir (dst_path, (src_mode & umask_kill) | 0700))
667 error (0, errno, _("cannot create directory `%s'"), dst_path);
668 goto un_backup;
671 /* Insert the created directory's inode and device
672 numbers into the search structure, so that we can
673 avoid copying it again. */
675 if (remember_created (dst_path))
676 goto un_backup;
678 if (flag_verbose)
679 printf ("%s -> %s\n", src_path, dst_path);
682 /* Copy the contents of the directory. */
684 if (copy_dir (src_path, dst_path, new_dst, &src_sb, dir))
685 return 1;
687 #ifdef S_ISLNK
688 else if (flag_symbolic_link)
690 if (*src_path == '/'
691 || (!strncmp (dst_path, "./", 2) && strchr (dst_path + 2, '/') == 0)
692 || strchr (dst_path, '/') == 0)
694 if (symlink (src_path, dst_path))
696 error (0, errno, "%s", dst_path);
697 goto un_backup;
699 return 0;
701 else
703 error (0, 0,
704 _("%s: can only make relative symbolic links in current directory"), dst_path);
705 goto un_backup;
708 #endif
709 else if (flag_hard_link)
711 if (link (src_path, dst_path))
713 error (0, errno, _("cannot create link `%s'"), dst_path);
714 goto un_backup;
716 return 0;
718 else if (S_ISREG (src_type)
719 || (flag_copy_as_regular && !S_ISDIR (src_type)
720 #ifdef S_ISLNK
721 && !S_ISLNK (src_type)
722 #endif
725 if (copy_reg (src_path, dst_path))
726 goto un_backup;
728 else
729 #ifdef S_ISFIFO
730 if (S_ISFIFO (src_type))
732 if (mkfifo (dst_path, src_mode & umask_kill))
734 error (0, errno, _("cannot create fifo `%s'"), dst_path);
735 goto un_backup;
738 else
739 #endif
740 if (S_ISBLK (src_type) || S_ISCHR (src_type)
741 #ifdef S_ISSOCK
742 || S_ISSOCK (src_type)
743 #endif
746 if (mknod (dst_path, src_mode & umask_kill, src_sb.st_rdev))
748 error (0, errno, _("cannot create special file `%s'"), dst_path);
749 goto un_backup;
752 else
753 #ifdef S_ISLNK
754 if (S_ISLNK (src_type))
756 char *link_val;
757 int link_size;
759 link_val = (char *) alloca (PATH_MAX + 2);
760 link_size = readlink (src_path, link_val, PATH_MAX + 1);
761 if (link_size < 0)
763 error (0, errno, _("cannot read symbolic link `%s'"), src_path);
764 goto un_backup;
766 link_val[link_size] = '\0';
768 if (symlink (link_val, dst_path))
770 error (0, errno, _("cannot create symbolic link `%s'"), dst_path);
771 goto un_backup;
773 return 0;
775 else
776 #endif
778 error (0, 0, _("%s: unknown file type"), src_path);
779 goto un_backup;
782 /* Adjust the times (and if possible, ownership) for the copy.
783 chown turns off set[ug]id bits for non-root,
784 so do the chmod last. */
786 if (flag_preserve)
788 struct utimbuf utb;
790 utb.actime = src_sb.st_atime;
791 utb.modtime = src_sb.st_mtime;
793 if (utime (dst_path, &utb))
795 error (0, errno, "%s", dst_path);
796 return 1;
799 /* If non-root uses -p, it's ok if we can't preserve ownership.
800 But root probably wants to know, e.g. if NFS disallows it. */
801 if (chown (dst_path,
802 (myeuid == 0 ? src_sb.st_uid : myeuid),
803 src_sb.st_gid)
804 && (errno != EPERM || myeuid == 0))
806 error (0, errno, "%s", dst_path);
807 return 1;
811 if ((flag_preserve || new_dst)
812 && (flag_copy_as_regular || S_ISREG (src_type) || S_ISDIR (src_type)))
814 if (chmod (dst_path, src_mode & umask_kill))
816 error (0, errno, "%s", dst_path);
817 return 1;
820 else if (fix_mode)
822 /* Reset the temporarily changed mode. */
823 if (chmod (dst_path, dst_sb.st_mode))
825 error (0, errno, "%s", dst_path);
826 return 1;
830 return 0;
832 un_backup:
833 if (dst_backup)
835 if (rename (dst_backup, dst_path))
836 error (0, errno, _("cannot un-backup `%s'"), dst_path);
838 return 1;
841 /* Ensure that the parent directory of CONST_DIRPATH exists, for
842 the --parents option.
844 SRC_OFFSET is the index in CONST_DIRPATH (which is a destination
845 path) of the beginning of the source directory name.
846 Create any leading directories that don't already exist,
847 giving them permissions MODE.
848 If VERBOSE_FMT_STRING is nonzero, use it as a printf format
849 string for printing a message after successfully making a directory.
850 The format should take two string arguments: the names of the
851 source and destination directories.
852 Creates a linked list of attributes of intermediate directories,
853 *ATTR_LIST, for re_protect to use after calling copy.
854 Sets *NEW_DST to 1 if this function creates parent of CONST_DIRPATH.
856 Return 0 if parent of CONST_DIRPATH exists as a directory with the proper
857 permissions when done, otherwise 1. */
859 static int
860 make_path_private (char *const_dirpath, int src_offset, int mode,
861 char *verbose_fmt_string, struct dir_attr **attr_list,
862 int *new_dst)
864 struct stat stats;
865 char *dirpath; /* A copy of CONST_DIRPATH we can change. */
866 char *src; /* Source name in `dirpath'. */
867 char *tmp_dst_dirname; /* Leading path of `dirpath', malloc. */
868 char *dst_dirname; /* Leading path of `dirpath', alloca. */
870 dirpath = (char *) alloca (strlen (const_dirpath) + 1);
871 strcpy (dirpath, const_dirpath);
873 src = dirpath + src_offset;
875 tmp_dst_dirname = dirname (dirpath);
876 dst_dirname = (char *) alloca (strlen (tmp_dst_dirname) + 1);
877 strcpy (dst_dirname, tmp_dst_dirname);
878 free (tmp_dst_dirname);
880 *attr_list = NULL;
882 if ((*xstat) (dst_dirname, &stats))
884 /* Parent of CONST_DIRNAME does not exist.
885 Make all missing intermediate directories. */
886 char *slash;
888 slash = src;
889 while (*slash == '/')
890 slash++;
891 while ((slash = strchr (slash, '/')))
893 /* Add this directory to the list of directories whose modes need
894 fixing later. */
895 struct dir_attr *new =
896 (struct dir_attr *) xmalloc (sizeof (struct dir_attr));
897 new->slash_offset = slash - dirpath;
898 new->next = *attr_list;
899 *attr_list = new;
901 *slash = '\0';
902 if ((*xstat) (dirpath, &stats))
904 /* This element of the path does not exist. We must set
905 *new_dst and new->is_new_dir inside this loop because,
906 for example, in the command `cp --parents ../a/../b/c e_dir',
907 make_path_private creates only e_dir/../a if ./b already
908 exists. */
909 *new_dst = 1;
910 new->is_new_dir = 1;
911 if (mkdir (dirpath, mode))
913 error (0, errno, _("cannot make directory `%s'"), dirpath);
914 return 1;
916 else
918 if (verbose_fmt_string != NULL)
919 printf (verbose_fmt_string, src, dirpath);
922 else if (!S_ISDIR (stats.st_mode))
924 error (0, 0, _("`%s' exists but is not a directory"), dirpath);
925 return 1;
927 else
929 new->is_new_dir = 0;
930 *new_dst = 0;
932 *slash++ = '/';
934 /* Avoid unnecessary calls to `stat' when given
935 pathnames containing multiple adjacent slashes. */
936 while (*slash == '/')
937 slash++;
941 /* We get here if the parent of `dirpath' already exists. */
943 else if (!S_ISDIR (stats.st_mode))
945 error (0, 0, _("`%s' exists but is not a directory"), dst_dirname);
946 return 1;
948 else
950 *new_dst = 0;
952 return 0;
955 /* Ensure that the parent directories of CONST_DST_PATH have the
956 correct protections, for the --parents option. This is done
957 after all copying has been completed, to allow permissions
958 that don't include user write/execute.
960 SRC_OFFSET is the index in CONST_DST_PATH of the beginning of the
961 source directory name.
963 ATTR_LIST is a null-terminated linked list of structures that
964 indicates the end of the filename of each intermediate directory
965 in CONST_DST_PATH that may need to have its attributes changed.
966 The command `cp --parents --preserve a/b/c d/e_dir' changes the
967 attributes of the directories d/e_dir/a and d/e_dir/a/b to match
968 the corresponding source directories regardless of whether they
969 existed before the `cp' command was given.
971 Return 0 if the parent of CONST_DST_PATH and any intermediate
972 directories specified by ATTR_LIST have the proper permissions
973 when done, otherwise 1. */
975 static int
976 re_protect (char *const_dst_path, int src_offset, struct dir_attr *attr_list)
978 struct dir_attr *p;
979 char *dst_path; /* A copy of CONST_DST_PATH we can change. */
980 char *src_path; /* The source name in `dst_path'. */
982 dst_path = (char *) alloca (strlen (const_dst_path) + 1);
983 strcpy (dst_path, const_dst_path);
984 src_path = dst_path + src_offset;
986 for (p = attr_list; p; p = p->next)
988 struct stat src_sb;
990 dst_path[p->slash_offset] = '\0';
992 if ((*xstat) (src_path, &src_sb))
994 error (0, errno, "%s", src_path);
995 return 1;
998 /* Adjust the times (and if possible, ownership) for the copy.
999 chown turns off set[ug]id bits for non-root,
1000 so do the chmod last. */
1002 if (flag_preserve)
1004 struct utimbuf utb;
1006 utb.actime = src_sb.st_atime;
1007 utb.modtime = src_sb.st_mtime;
1009 if (utime (dst_path, &utb))
1011 error (0, errno, "%s", dst_path);
1012 return 1;
1015 /* If non-root uses -p, it's ok if we can't preserve ownership.
1016 But root probably wants to know, e.g. if NFS disallows it. */
1017 if (chown (dst_path, src_sb.st_uid, src_sb.st_gid)
1018 && (errno != EPERM || myeuid == 0))
1020 error (0, errno, "%s", dst_path);
1021 return 1;
1025 if (flag_preserve || p->is_new_dir)
1027 if (chmod (dst_path, src_sb.st_mode & umask_kill))
1029 error (0, errno, "%s", dst_path);
1030 return 1;
1034 dst_path[p->slash_offset] = '/';
1036 return 0;
1039 /* Read the contents of the directory SRC_PATH_IN, and recursively
1040 copy the contents to DST_PATH_IN. NEW_DST is nonzero if
1041 DST_PATH_IN is a directory that was created previously in the
1042 recursion. SRC_SB and ANCESTORS describe SRC_PATH_IN.
1043 Return 0 if successful, -1 if an error occurs. */
1045 static int
1046 copy_dir (char *src_path_in, char *dst_path_in, int new_dst,
1047 struct stat *src_sb, struct dir_list *ancestors)
1049 char *name_space;
1050 char *namep;
1051 char *src_path;
1052 char *dst_path;
1053 int ret = 0;
1055 errno = 0;
1056 name_space = savedir (src_path_in, src_sb->st_size);
1057 if (name_space == 0)
1059 if (errno)
1061 error (0, errno, "%s", src_path_in);
1062 return -1;
1064 else
1065 error (1, 0, _("virtual memory exhausted"));
1068 namep = name_space;
1069 while (*namep != '\0')
1071 int fn_length = strlen (namep) + 1;
1073 dst_path = xmalloc (strlen (dst_path_in) + fn_length + 1);
1074 src_path = xmalloc (strlen (src_path_in) + fn_length + 1);
1076 stpcpy (stpcpy (stpcpy (src_path, src_path_in), "/"), namep);
1077 stpcpy (stpcpy (stpcpy (dst_path, dst_path_in), "/"), namep);
1079 ret |= copy (src_path, dst_path, new_dst, src_sb->st_dev, ancestors);
1081 /* Free the memory for `src_path'. The memory for `dst_path'
1082 cannot be deallocated, since it is used to create multiple
1083 hard links. */
1085 free (src_path);
1087 namep += fn_length;
1089 free (name_space);
1090 return -ret;
1093 /* Copy a regular file from SRC_PATH to DST_PATH.
1094 If the source file contains holes, copies holes and blocks of zeros
1095 in the source file as holes in the destination file.
1096 (Holes are read as zeroes by the `read' system call.)
1097 Return 0 if successful, -1 if an error occurred. */
1099 static int
1100 copy_reg (char *src_path, char *dst_path)
1102 char *buf;
1103 int buf_size;
1104 int dest_desc;
1105 int source_desc;
1106 int n_read;
1107 struct stat sb;
1108 char *cp;
1109 int *ip;
1110 int return_val = 0;
1111 long n_read_total = 0;
1112 int last_write_made_hole = 0;
1113 int make_holes = 0;
1115 source_desc = open (src_path, O_RDONLY);
1116 if (source_desc < 0)
1118 error (0, errno, "%s", src_path);
1119 return -1;
1122 /* Create the new regular file with small permissions initially,
1123 to not create a security hole. */
1125 dest_desc = open (dst_path, O_WRONLY | O_CREAT | O_TRUNC, 0600);
1126 if (dest_desc < 0)
1128 error (0, errno, _("cannot create regular file `%s'"), dst_path);
1129 return_val = -1;
1130 goto ret2;
1133 /* Find out the optimal buffer size. */
1135 if (fstat (dest_desc, &sb))
1137 error (0, errno, "%s", dst_path);
1138 return_val = -1;
1139 goto ret;
1142 buf_size = ST_BLKSIZE (sb);
1144 #ifdef HAVE_ST_BLOCKS
1145 if (S_ISREG (sb.st_mode))
1147 /* Find out whether the file contains any sparse blocks. */
1149 if (fstat (source_desc, &sb))
1151 error (0, errno, "%s", src_path);
1152 return_val = -1;
1153 goto ret;
1156 /* If the file has fewer blocks than would normally
1157 be needed for a file of its size, then
1158 at least one of the blocks in the file is a hole. */
1159 if (S_ISREG (sb.st_mode) && sb.st_size > sb.st_blocks * DEV_BSIZE)
1160 make_holes = 1;
1162 #endif
1164 /* Make a buffer with space for a sentinel at the end. */
1166 buf = (char *) alloca (buf_size + sizeof (int));
1168 for (;;)
1170 n_read = read (source_desc, buf, buf_size);
1171 if (n_read < 0)
1173 #ifdef EINTR
1174 if (errno == EINTR)
1175 continue;
1176 #endif
1177 error (0, errno, "%s", src_path);
1178 return_val = -1;
1179 goto ret;
1181 if (n_read == 0)
1182 break;
1184 n_read_total += n_read;
1186 ip = 0;
1187 if (make_holes)
1189 buf[n_read] = 1; /* Sentinel to stop loop. */
1191 /* Find first nonzero *word*, or the word with the sentinel. */
1193 ip = (int *) buf;
1194 while (*ip++ == 0)
1197 /* Find the first nonzero *byte*, or the sentinel. */
1199 cp = (char *) (ip - 1);
1200 while (*cp++ == 0)
1203 /* If we found the sentinel, the whole input block was zero,
1204 and we can make a hole. */
1206 if (cp > buf + n_read)
1208 /* Make a hole. */
1209 if (lseek (dest_desc, (off_t) n_read, SEEK_CUR) < 0L)
1211 error (0, errno, "%s", dst_path);
1212 return_val = -1;
1213 goto ret;
1215 last_write_made_hole = 1;
1217 else
1218 /* Clear to indicate that a normal write is needed. */
1219 ip = 0;
1221 if (ip == 0)
1223 if (full_write (dest_desc, buf, n_read) < 0)
1225 error (0, errno, "%s", dst_path);
1226 return_val = -1;
1227 goto ret;
1229 last_write_made_hole = 0;
1233 /* If the file ends with a `hole', something needs to be written at
1234 the end. Otherwise the kernel would truncate the file at the end
1235 of the last write operation. */
1237 if (last_write_made_hole)
1239 #ifdef HAVE_FTRUNCATE
1240 /* Write a null character and truncate it again. */
1241 if (full_write (dest_desc, "", 1) < 0
1242 || ftruncate (dest_desc, n_read_total) < 0)
1243 #else
1244 /* Seek backwards one character and write a null. */
1245 if (lseek (dest_desc, (off_t) -1, SEEK_CUR) < 0L
1246 || full_write (dest_desc, "", 1) < 0)
1247 #endif
1249 error (0, errno, "%s", dst_path);
1250 return_val = -1;
1254 ret:
1255 if (close (dest_desc) < 0)
1257 error (0, errno, "%s", dst_path);
1258 return_val = -1;
1260 ret2:
1261 if (close (source_desc) < 0)
1263 error (0, errno, "%s", src_path);
1264 return_val = -1;
1267 return return_val;