.
[coreutils.git] / src / cp.c
blob692a067f873ef0b06efd8ccdb2c265438182f0ae
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"
30 #include "argmatch.h"
32 #ifndef _POSIX_VERSION
33 uid_t geteuid ();
34 #endif
36 /* Used by do_copy, make_path_private, and re_protect
37 to keep a list of leading directories whose protections
38 need to be fixed after copying. */
39 struct dir_attr
41 int is_new_dir;
42 int slash_offset;
43 struct dir_attr *next;
46 /* Control creation of sparse files (files with holes). */
47 enum Sparse_type
49 /* Never create holes in DEST. */
50 SPARSE_NEVER,
52 /* This is the default. Use a crude (and sometimes inaccurate)
53 heuristic to determine if SOURCE has holes. If so, try to create
54 holes in DEST. */
55 SPARSE_AUTO,
57 /* For every sufficiently long sequence of bytes in SOURCE, try to
58 create a corresponding hole in DEST. There is a performance penalty
59 here because CP has to search for holes in SRC. But if the holes are
60 big enough, that penalty can be offset by the decrease in the amount
61 of data written to disk. */
62 SPARSE_ALWAYS
65 int stat ();
66 int lstat ();
68 char *dirname ();
69 char *xstrdup ();
70 enum backup_type get_version ();
71 int euidaccess ();
72 int full_write ();
74 static int do_copy __P ((int argc, char **argv));
75 static int copy __P ((char *src_path, char *dst_path, int new_dst,
76 dev_t device, struct dir_list *ancestors));
77 static int copy_dir __P ((char *src_path_in, char *dst_path_in, int new_dst,
78 struct stat *src_sb, struct dir_list *ancestors));
79 static int make_path_private __P ((char *const_dirpath, int src_offset,
80 int mode, char *verbose_fmt_string,
81 struct dir_attr **attr_list, int *new_dst));
82 static int copy_reg __P ((char *src_path, char *dst_path));
83 static int re_protect __P ((char *const_dst_path, int src_offset,
84 struct dir_attr *attr_list));
86 /* Initial number of entries in each hash table entry's table of inodes. */
87 #define INITIAL_HASH_MODULE 100
89 /* Initial number of entries in the inode hash table. */
90 #define INITIAL_ENTRY_TAB_SIZE 70
92 /* The invocation name of this program. */
93 char *program_name;
95 /* A pointer to either lstat or stat, depending on
96 whether dereferencing of symlinks is done. */
97 static int (*xstat) ();
99 /* If nonzero, copy all files except (directories and, if not dereferencing
100 them, symbolic links,) as if they were regular files. */
101 static int flag_copy_as_regular = 1;
103 /* If nonzero, dereference symbolic links (copy the files they point to). */
104 static int flag_dereference = 1;
106 /* If nonzero, remove existing destination nondirectories. */
107 static int flag_force = 0;
109 /* If nonzero, create hard links instead of copying files.
110 Create destination directories as usual. */
111 static int flag_hard_link = 0;
113 /* If nonzero, query before overwriting existing destinations
114 with regular files. */
115 static int flag_interactive = 0;
117 /* If nonzero, the command "cp x/e_file e_dir" uses "e_dir/x/e_file"
118 as its destination instead of the usual "e_dir/e_file." */
119 static int flag_path = 0;
121 /* If nonzero, give the copies the original files' permissions,
122 ownership, and timestamps. */
123 static int flag_preserve = 0;
125 /* If nonzero, copy directories recursively and copy special files
126 as themselves rather than copying their contents. */
127 static int flag_recursive = 0;
129 /* If nonzero, create symbolic links instead of copying files.
130 Create destination directories as usual. */
131 static int flag_symbolic_link = 0;
133 /* If nonzero, when copying recursively, skip any subdirectories that are
134 on different filesystems from the one we started on. */
135 static int flag_one_file_system = 0;
137 /* If nonzero, do not copy a nondirectory that has an existing destination
138 with the same or newer modification time. */
139 static int flag_update = 0;
141 /* If nonzero, display the names of the files before copying them. */
142 static int flag_verbose = 0;
144 static char const *const sparse_type_string[] =
146 "never", "auto", "always", 0
149 static enum Sparse_type const sparse_type[] =
151 SPARSE_NEVER, SPARSE_AUTO, SPARSE_ALWAYS
154 /* Control creation of sparse files. */
155 static int flag_sparse = SPARSE_AUTO;
157 /* The error code to return to the system. */
158 static int exit_status = 0;
160 /* The bits to preserve in created files' modes. */
161 static int umask_kill;
163 /* This process's effective user ID. */
164 static uid_t myeuid;
166 /* If nonzero, display usage information and exit. */
167 static int show_help;
169 /* If nonzero, print the version on standard output and exit. */
170 static int show_version;
172 static struct option const long_opts[] =
174 {"archive", no_argument, NULL, 'a'},
175 {"backup", no_argument, NULL, 'b'},
176 {"force", no_argument, NULL, 'f'},
177 {"sparse", required_argument, NULL, 2},
178 {"interactive", no_argument, NULL, 'i'},
179 {"link", no_argument, NULL, 'l'},
180 {"no-dereference", no_argument, &flag_dereference, 0},
181 {"one-file-system", no_argument, &flag_one_file_system, 1},
182 {"parents", no_argument, &flag_path, 1},
183 {"path", no_argument, &flag_path, 1},
184 {"preserve", no_argument, &flag_preserve, 1},
185 {"recursive", no_argument, NULL, 'R'},
186 {"suffix", required_argument, NULL, 'S'},
187 {"symbolic-link", no_argument, NULL, 's'},
188 {"update", no_argument, &flag_update, 1},
189 {"verbose", no_argument, &flag_verbose, 1},
190 {"version-control", required_argument, NULL, 'V'},
191 {"help", no_argument, &show_help, 1},
192 {"version", no_argument, &show_version, 1},
193 {NULL, 0, NULL, 0}
196 void
197 main (int argc, char **argv)
199 int c;
200 int make_backups = 0;
201 char *version;
203 program_name = argv[0];
204 setlocale (LC_ALL, "");
205 bindtextdomain (PACKAGE, LOCALEDIR);
206 textdomain (PACKAGE);
208 myeuid = geteuid ();
210 version = getenv ("SIMPLE_BACKUP_SUFFIX");
211 if (version)
212 simple_backup_suffix = version;
213 version = getenv ("VERSION_CONTROL");
215 /* Find out the current file creation mask, to knock the right bits
216 when using chmod. The creation mask is set to to be liberal, so
217 that created directories can be written, even if it would not
218 have been allowed with the mask this process was started with. */
220 umask_kill = 0777777 ^ umask (0);
222 while ((c = getopt_long (argc, argv, "abdfilprsuvxPRS:V:", long_opts,
223 (int *) 0)) != EOF)
225 switch (c)
227 case 0:
228 break;
230 case 2:
232 int i;
234 /* --sparse={never,auto,always} */
235 i = argmatch (optarg, sparse_type_string);
236 if (i < 0)
238 invalid_arg (_("sparse type"), optarg, i);
239 usage (2, NULL);
241 flag_sparse = sparse_type[i];
243 break;
245 case 'a': /* Like -dpR. */
246 flag_dereference = 0;
247 flag_preserve = 1;
248 flag_recursive = 1;
249 flag_copy_as_regular = 0;
250 break;
252 case 'b':
253 make_backups = 1;
254 break;
256 case 'd':
257 flag_dereference = 0;
258 break;
260 case 'f':
261 flag_force = 1;
262 flag_interactive = 0;
263 break;
265 case 'i':
266 flag_force = 0;
267 flag_interactive = 1;
268 break;
270 case 'l':
271 flag_hard_link = 1;
272 break;
274 case 'p':
275 flag_preserve = 1;
276 break;
278 case 'P':
279 flag_path = 1;
280 break;
282 case 'r':
283 flag_recursive = 1;
284 flag_copy_as_regular = 1;
285 break;
287 case 'R':
288 flag_recursive = 1;
289 flag_copy_as_regular = 0;
290 break;
292 case 's':
293 #ifdef S_ISLNK
294 flag_symbolic_link = 1;
295 #else
296 error (1, 0, _("symbolic links are not supported on this system"));
297 #endif
298 break;
300 case 'u':
301 flag_update = 1;
302 break;
304 case 'v':
305 flag_verbose = 1;
306 break;
308 case 'x':
309 flag_one_file_system = 1;
310 break;
312 case 'S':
313 simple_backup_suffix = optarg;
314 break;
316 case 'V':
317 version = optarg;
318 break;
320 default:
321 usage (2, (char *) 0);
325 if (show_version)
327 printf ("cp - %s\n", version_string);
328 exit (0);
331 if (show_help)
332 usage (0, NULL);
334 if (flag_hard_link && flag_symbolic_link)
335 usage (2, _("cannot make both hard and symbolic links"));
337 if (make_backups)
338 backup_type = get_version (version);
340 if (flag_preserve == 1)
341 umask_kill = 0777777;
343 /* The key difference between -d (--no-dereference) and not is the version
344 of `stat' to call. */
346 if (flag_dereference)
347 xstat = stat;
348 else
349 xstat = lstat;
351 /* Allocate space for remembering copied and created files. */
353 hash_init (INITIAL_HASH_MODULE, INITIAL_ENTRY_TAB_SIZE);
355 exit_status |= do_copy (argc, argv);
357 exit (exit_status);
360 /* Scan the arguments, and copy each by calling copy.
361 Return 0 if successful, 1 if any errors occur. */
363 static int
364 do_copy (int argc, char **argv)
366 char *dest;
367 struct stat sb;
368 int new_dst = 0;
369 int ret = 0;
371 if (optind >= argc)
372 usage (2, _("missing file arguments"));
373 if (optind >= argc - 1)
374 usage (2, _("missing file argument"));
376 dest = argv[argc - 1];
378 if (lstat (dest, &sb))
380 if (errno != ENOENT)
382 error (0, errno, "%s", dest);
383 return 1;
385 else
386 new_dst = 1;
388 else
390 struct stat sbx;
392 /* If `dest' is not a symlink to a nonexistent file, use
393 the results of stat instead of lstat, so we can copy files
394 into symlinks to directories. */
395 if (stat (dest, &sbx) == 0)
396 sb = sbx;
399 if (!new_dst && S_ISDIR (sb.st_mode))
401 /* cp file1...filen edir
402 Copy the files `file1' through `filen'
403 to the existing directory `edir'. */
405 for (;;)
407 char *arg;
408 char *ap;
409 char *dst_path;
410 int parent_exists = 1; /* True if dirname (dst_path) exists. */
411 struct dir_attr *attr_list;
413 arg = argv[optind];
415 strip_trailing_slashes (arg);
417 if (flag_path)
419 /* Append all of `arg' to `dest'. */
420 dst_path = xmalloc (strlen (dest) + strlen (arg) + 2);
421 stpcpy (stpcpy (stpcpy (dst_path, dest), "/"), arg);
423 /* For --parents, we have to make sure that the directory
424 dirname (dst_path) exists. We may have to create a few
425 leading directories. */
426 parent_exists = !make_path_private (dst_path,
427 strlen (dest) + 1, 0700,
428 flag_verbose ? "%s -> %s\n" :
429 (char *) NULL,
430 &attr_list, &new_dst);
432 else
434 /* Append the last component of `arg' to `dest'. */
436 ap = basename (arg);
437 /* For `cp -R source/.. dest', don't copy into `dest/..'. */
438 if (!strcmp (ap, ".."))
439 dst_path = xstrdup (dest);
440 else
442 dst_path = xmalloc (strlen (dest) + strlen (ap) + 2);
443 stpcpy (stpcpy (stpcpy (dst_path, dest), "/"), ap);
447 if (!parent_exists)
449 /* make_path_private failed, so we shouldn't even attempt the copy. */
450 ret = 1;
452 else
454 ret |= copy (arg, dst_path, new_dst, 0, (struct dir_list *) 0);
455 forget_all ();
457 if (flag_path)
459 ret |= re_protect (dst_path, strlen (dest) + 1,
460 attr_list);
464 free (dst_path);
465 ++optind;
466 if (optind == argc - 1)
467 break;
469 return ret;
471 else if (argc - optind == 2)
473 char *new_dest;
474 char *source;
475 struct stat source_stats;
477 if (flag_path)
478 usage (2, _("when preserving paths, last argument must be a directory"));
480 source = argv[optind];
482 /* When the destination is specified with a trailing slash and the
483 source exists but is not a directory, convert the user's command
484 `cp source dest/' to `cp source dest/basename(source)'. */
486 if (dest[strlen (dest) - 1] == '/'
487 && lstat (source, &source_stats) == 0
488 && !S_ISDIR (source_stats.st_mode))
490 char *source_base;
491 char *tmp_source;
493 tmp_source = (char *) alloca (strlen (source) + 1);
494 strcpy (tmp_source, source);
495 strip_trailing_slashes (tmp_source);
496 source_base = basename (tmp_source);
498 new_dest = (char *) alloca (strlen (dest) + 1 +
499 strlen (source_base) + 1);
500 stpcpy (stpcpy (stpcpy (new_dest, dest), "/"), source_base);
502 else
504 new_dest = dest;
507 return copy (source, new_dest, new_dst, 0, (struct dir_list *) 0);
509 else
510 usage (2,
511 _("when copying multiple files, last argument must be a directory"));
514 /* Copy the file SRC_PATH to the file DST_PATH. The files may be of
515 any type. NEW_DST should be nonzero if the file DST_PATH cannot
516 exist because its parent directory was just created; NEW_DST should
517 be zero if DST_PATH might already exist. DEVICE is the device
518 number of the parent directory, or 0 if the parent of this file is
519 not known. ANCESTORS points to a linked, null terminated list of
520 devices and inodes of parent directories of SRC_PATH.
521 Return 0 if successful, 1 if an error occurs. */
523 static int
524 copy (char *src_path, char *dst_path, int new_dst, dev_t device,
525 struct dir_list *ancestors)
527 struct stat src_sb;
528 struct stat dst_sb;
529 int src_mode;
530 int src_type;
531 char *earlier_file;
532 char *dst_backup = NULL;
533 int fix_mode = 0;
535 if ((*xstat) (src_path, &src_sb))
537 error (0, errno, "%s", src_path);
538 return 1;
541 /* Are we crossing a file system boundary? */
542 if (flag_one_file_system && device != 0 && device != src_sb.st_dev)
543 return 0;
545 /* We wouldn't insert a node unless nlink > 1, except that we need to
546 find created files so as to not copy infinitely if a directory is
547 copied into itself. */
549 earlier_file = remember_copied (dst_path, src_sb.st_ino, src_sb.st_dev);
551 /* Did we just create this file? */
553 if (earlier_file == &new_file)
554 return 0;
556 src_mode = src_sb.st_mode;
557 src_type = src_sb.st_mode;
559 if (S_ISDIR (src_type) && !flag_recursive)
561 error (0, 0, _("%s: omitting directory"), src_path);
562 return 1;
565 if (!new_dst)
567 if ((*xstat) (dst_path, &dst_sb))
569 if (errno != ENOENT)
571 error (0, errno, "%s", dst_path);
572 return 1;
574 else
575 new_dst = 1;
577 else
579 /* The file exists already. */
581 if (src_sb.st_ino == dst_sb.st_ino && src_sb.st_dev == dst_sb.st_dev)
583 if (flag_hard_link)
584 return 0;
586 error (0, 0, _("`%s' and `%s' are the same file"),
587 src_path, dst_path);
588 return 1;
591 if (!S_ISDIR (src_type))
593 if (S_ISDIR (dst_sb.st_mode))
595 error (0, 0,
596 _("%s: cannot overwrite directory with non-directory"),
597 dst_path);
598 return 1;
601 if (flag_update && src_sb.st_mtime <= dst_sb.st_mtime)
602 return 0;
605 if (S_ISREG (src_type) && !flag_force)
607 if (flag_interactive)
609 if (euidaccess (dst_path, W_OK) != 0)
610 fprintf (stderr,
611 _("%s: overwrite `%s', overriding mode %04o? "),
612 program_name, dst_path,
613 (unsigned int) (dst_sb.st_mode & 07777));
614 else
615 fprintf (stderr, _("%s: overwrite `%s'? "),
616 program_name, dst_path);
617 if (!yesno ())
618 return 0;
622 if (backup_type != none && !S_ISDIR (dst_sb.st_mode))
624 char *tmp_backup = find_backup_file_name (dst_path);
625 if (tmp_backup == NULL)
626 error (1, 0, _("virtual memory exhausted"));
628 /* Detect (and fail) when creating the backup file would
629 destroy the source file. Before, running the commands
630 cd /tmp; rm -f a a~; : > a; echo A > a~; cp -b -V simple a~ a
631 would leave two zero-length files: a and a~. */
632 if (strcmp (tmp_backup, src_path) == 0)
634 error (0, 0,
635 _("backing up `%s' would destroy source; `%s' not copied"),
636 dst_path, src_path);
637 return 1;
640 dst_backup = (char *) alloca (strlen (tmp_backup) + 1);
641 strcpy (dst_backup, tmp_backup);
642 free (tmp_backup);
643 if (rename (dst_path, dst_backup))
645 if (errno != ENOENT)
647 error (0, errno, _("cannot backup `%s'"), dst_path);
648 return 1;
650 else
651 dst_backup = NULL;
653 new_dst = 1;
655 else if (flag_force)
657 if (S_ISDIR (dst_sb.st_mode))
659 /* Temporarily change mode to allow overwriting. */
660 if (euidaccess (dst_path, W_OK | X_OK) != 0)
662 if (chmod (dst_path, 0700))
664 error (0, errno, "%s", dst_path);
665 return 1;
667 else
668 fix_mode = 1;
671 else
673 if (unlink (dst_path) && errno != ENOENT)
675 error (0, errno, _("cannot remove old link to `%s'"),
676 dst_path);
677 return 1;
679 new_dst = 1;
685 /* If the source is a directory, we don't always create the destination
686 directory. So --verbose should not announce anything until we're
687 sure we'll create a directory. */
688 if (flag_verbose && !S_ISDIR (src_type))
689 printf ("%s -> %s\n", src_path, dst_path);
691 /* Did we copy this inode somewhere else (in this command line argument)
692 and therefore this is a second hard link to the inode? */
694 if (!flag_dereference && src_sb.st_nlink > 1 && earlier_file)
696 if (link (earlier_file, dst_path))
698 error (0, errno, "%s", dst_path);
699 goto un_backup;
701 return 0;
704 if (S_ISDIR (src_type))
706 struct dir_list *dir;
708 /* If this directory has been copied before during the
709 recursion, there is a symbolic link to an ancestor
710 directory of the symbolic link. It is impossible to
711 continue to copy this, unless we've got an infinite disk. */
713 if (is_ancestor (&src_sb, ancestors))
715 error (0, 0, _("%s: cannot copy cyclic symbolic link"), src_path);
716 goto un_backup;
719 /* Insert the current directory in the list of parents. */
721 dir = (struct dir_list *) alloca (sizeof (struct dir_list));
722 dir->parent = ancestors;
723 dir->ino = src_sb.st_ino;
724 dir->dev = src_sb.st_dev;
726 if (new_dst || !S_ISDIR (dst_sb.st_mode))
728 /* Create the new directory writable and searchable, so
729 we can create new entries in it. */
731 if (mkdir (dst_path, (src_mode & umask_kill) | 0700))
733 error (0, errno, _("cannot create directory `%s'"), dst_path);
734 goto un_backup;
737 /* Insert the created directory's inode and device
738 numbers into the search structure, so that we can
739 avoid copying it again. */
741 if (remember_created (dst_path))
742 goto un_backup;
744 if (flag_verbose)
745 printf ("%s -> %s\n", src_path, dst_path);
748 /* Copy the contents of the directory. */
750 if (copy_dir (src_path, dst_path, new_dst, &src_sb, dir))
751 return 1;
753 #ifdef S_ISLNK
754 else if (flag_symbolic_link)
756 if (*src_path == '/'
757 || (!strncmp (dst_path, "./", 2) && strchr (dst_path + 2, '/') == 0)
758 || strchr (dst_path, '/') == 0)
760 if (symlink (src_path, dst_path))
762 error (0, errno, "%s", dst_path);
763 goto un_backup;
765 return 0;
767 else
769 error (0, 0,
770 _("%s: can only make relative symbolic links in current directory"), dst_path);
771 goto un_backup;
774 #endif
775 else if (flag_hard_link)
777 if (link (src_path, dst_path))
779 error (0, errno, _("cannot create link `%s'"), dst_path);
780 goto un_backup;
782 return 0;
784 else if (S_ISREG (src_type)
785 || (flag_copy_as_regular && !S_ISDIR (src_type)
786 #ifdef S_ISLNK
787 && !S_ISLNK (src_type)
788 #endif
791 if (copy_reg (src_path, dst_path))
792 goto un_backup;
794 else
795 #ifdef S_ISFIFO
796 if (S_ISFIFO (src_type))
798 if (mkfifo (dst_path, src_mode & umask_kill))
800 error (0, errno, _("cannot create fifo `%s'"), dst_path);
801 goto un_backup;
804 else
805 #endif
806 if (S_ISBLK (src_type) || S_ISCHR (src_type)
807 #ifdef S_ISSOCK
808 || S_ISSOCK (src_type)
809 #endif
812 if (mknod (dst_path, src_mode & umask_kill, src_sb.st_rdev))
814 error (0, errno, _("cannot create special file `%s'"), dst_path);
815 goto un_backup;
818 else
819 #ifdef S_ISLNK
820 if (S_ISLNK (src_type))
822 char *link_val;
823 int link_size;
825 link_val = (char *) alloca (PATH_MAX + 2);
826 link_size = readlink (src_path, link_val, PATH_MAX + 1);
827 if (link_size < 0)
829 error (0, errno, _("cannot read symbolic link `%s'"), src_path);
830 goto un_backup;
832 link_val[link_size] = '\0';
834 if (symlink (link_val, dst_path))
836 error (0, errno, _("cannot create symbolic link `%s'"), dst_path);
837 goto un_backup;
839 return 0;
841 else
842 #endif
844 error (0, 0, _("%s: unknown file type"), src_path);
845 goto un_backup;
848 /* Adjust the times (and if possible, ownership) for the copy.
849 chown turns off set[ug]id bits for non-root,
850 so do the chmod last. */
852 if (flag_preserve)
854 struct utimbuf utb;
856 utb.actime = src_sb.st_atime;
857 utb.modtime = src_sb.st_mtime;
859 if (utime (dst_path, &utb))
861 error (0, errno, "%s", dst_path);
862 return 1;
865 /* If non-root uses -p, it's ok if we can't preserve ownership.
866 But root probably wants to know, e.g. if NFS disallows it. */
867 if (chown (dst_path,
868 (myeuid == 0 ? src_sb.st_uid : myeuid),
869 src_sb.st_gid)
870 && (errno != EPERM || myeuid == 0))
872 error (0, errno, "%s", dst_path);
873 return 1;
877 if ((flag_preserve || new_dst)
878 && (flag_copy_as_regular || S_ISREG (src_type) || S_ISDIR (src_type)))
880 if (chmod (dst_path, src_mode & umask_kill))
882 error (0, errno, "%s", dst_path);
883 return 1;
886 else if (fix_mode)
888 /* Reset the temporarily changed mode. */
889 if (chmod (dst_path, dst_sb.st_mode))
891 error (0, errno, "%s", dst_path);
892 return 1;
896 return 0;
898 un_backup:
899 if (dst_backup)
901 if (rename (dst_backup, dst_path))
902 error (0, errno, _("cannot un-backup `%s'"), dst_path);
904 return 1;
907 /* Ensure that the parent directory of CONST_DIRPATH exists, for
908 the --parents option.
910 SRC_OFFSET is the index in CONST_DIRPATH (which is a destination
911 path) of the beginning of the source directory name.
912 Create any leading directories that don't already exist,
913 giving them permissions MODE.
914 If VERBOSE_FMT_STRING is nonzero, use it as a printf format
915 string for printing a message after successfully making a directory.
916 The format should take two string arguments: the names of the
917 source and destination directories.
918 Creates a linked list of attributes of intermediate directories,
919 *ATTR_LIST, for re_protect to use after calling copy.
920 Sets *NEW_DST to 1 if this function creates parent of CONST_DIRPATH.
922 Return 0 if parent of CONST_DIRPATH exists as a directory with the proper
923 permissions when done, otherwise 1. */
925 static int
926 make_path_private (char *const_dirpath, int src_offset, int mode,
927 char *verbose_fmt_string, struct dir_attr **attr_list,
928 int *new_dst)
930 struct stat stats;
931 char *dirpath; /* A copy of CONST_DIRPATH we can change. */
932 char *src; /* Source name in `dirpath'. */
933 char *tmp_dst_dirname; /* Leading path of `dirpath', malloc. */
934 char *dst_dirname; /* Leading path of `dirpath', alloca. */
936 dirpath = (char *) alloca (strlen (const_dirpath) + 1);
937 strcpy (dirpath, const_dirpath);
939 src = dirpath + src_offset;
941 tmp_dst_dirname = dirname (dirpath);
942 dst_dirname = (char *) alloca (strlen (tmp_dst_dirname) + 1);
943 strcpy (dst_dirname, tmp_dst_dirname);
944 free (tmp_dst_dirname);
946 *attr_list = NULL;
948 if ((*xstat) (dst_dirname, &stats))
950 /* Parent of CONST_DIRNAME does not exist.
951 Make all missing intermediate directories. */
952 char *slash;
954 slash = src;
955 while (*slash == '/')
956 slash++;
957 while ((slash = strchr (slash, '/')))
959 /* Add this directory to the list of directories whose modes need
960 fixing later. */
961 struct dir_attr *new =
962 (struct dir_attr *) xmalloc (sizeof (struct dir_attr));
963 new->slash_offset = slash - dirpath;
964 new->next = *attr_list;
965 *attr_list = new;
967 *slash = '\0';
968 if ((*xstat) (dirpath, &stats))
970 /* This element of the path does not exist. We must set
971 *new_dst and new->is_new_dir inside this loop because,
972 for example, in the command `cp --parents ../a/../b/c e_dir',
973 make_path_private creates only e_dir/../a if ./b already
974 exists. */
975 *new_dst = 1;
976 new->is_new_dir = 1;
977 if (mkdir (dirpath, mode))
979 error (0, errno, _("cannot make directory `%s'"), dirpath);
980 return 1;
982 else
984 if (verbose_fmt_string != NULL)
985 printf (verbose_fmt_string, src, dirpath);
988 else if (!S_ISDIR (stats.st_mode))
990 error (0, 0, _("`%s' exists but is not a directory"), dirpath);
991 return 1;
993 else
995 new->is_new_dir = 0;
996 *new_dst = 0;
998 *slash++ = '/';
1000 /* Avoid unnecessary calls to `stat' when given
1001 pathnames containing multiple adjacent slashes. */
1002 while (*slash == '/')
1003 slash++;
1007 /* We get here if the parent of `dirpath' already exists. */
1009 else if (!S_ISDIR (stats.st_mode))
1011 error (0, 0, _("`%s' exists but is not a directory"), dst_dirname);
1012 return 1;
1014 else
1016 *new_dst = 0;
1018 return 0;
1021 /* Ensure that the parent directories of CONST_DST_PATH have the
1022 correct protections, for the --parents option. This is done
1023 after all copying has been completed, to allow permissions
1024 that don't include user write/execute.
1026 SRC_OFFSET is the index in CONST_DST_PATH of the beginning of the
1027 source directory name.
1029 ATTR_LIST is a null-terminated linked list of structures that
1030 indicates the end of the filename of each intermediate directory
1031 in CONST_DST_PATH that may need to have its attributes changed.
1032 The command `cp --parents --preserve a/b/c d/e_dir' changes the
1033 attributes of the directories d/e_dir/a and d/e_dir/a/b to match
1034 the corresponding source directories regardless of whether they
1035 existed before the `cp' command was given.
1037 Return 0 if the parent of CONST_DST_PATH and any intermediate
1038 directories specified by ATTR_LIST have the proper permissions
1039 when done, otherwise 1. */
1041 static int
1042 re_protect (char *const_dst_path, int src_offset, struct dir_attr *attr_list)
1044 struct dir_attr *p;
1045 char *dst_path; /* A copy of CONST_DST_PATH we can change. */
1046 char *src_path; /* The source name in `dst_path'. */
1048 dst_path = (char *) alloca (strlen (const_dst_path) + 1);
1049 strcpy (dst_path, const_dst_path);
1050 src_path = dst_path + src_offset;
1052 for (p = attr_list; p; p = p->next)
1054 struct stat src_sb;
1056 dst_path[p->slash_offset] = '\0';
1058 if ((*xstat) (src_path, &src_sb))
1060 error (0, errno, "%s", src_path);
1061 return 1;
1064 /* Adjust the times (and if possible, ownership) for the copy.
1065 chown turns off set[ug]id bits for non-root,
1066 so do the chmod last. */
1068 if (flag_preserve)
1070 struct utimbuf utb;
1072 utb.actime = src_sb.st_atime;
1073 utb.modtime = src_sb.st_mtime;
1075 if (utime (dst_path, &utb))
1077 error (0, errno, "%s", dst_path);
1078 return 1;
1081 /* If non-root uses -p, it's ok if we can't preserve ownership.
1082 But root probably wants to know, e.g. if NFS disallows it. */
1083 if (chown (dst_path, src_sb.st_uid, src_sb.st_gid)
1084 && (errno != EPERM || myeuid == 0))
1086 error (0, errno, "%s", dst_path);
1087 return 1;
1091 if (flag_preserve || p->is_new_dir)
1093 if (chmod (dst_path, src_sb.st_mode & umask_kill))
1095 error (0, errno, "%s", dst_path);
1096 return 1;
1100 dst_path[p->slash_offset] = '/';
1102 return 0;
1105 /* Read the contents of the directory SRC_PATH_IN, and recursively
1106 copy the contents to DST_PATH_IN. NEW_DST is nonzero if
1107 DST_PATH_IN is a directory that was created previously in the
1108 recursion. SRC_SB and ANCESTORS describe SRC_PATH_IN.
1109 Return 0 if successful, -1 if an error occurs. */
1111 static int
1112 copy_dir (char *src_path_in, char *dst_path_in, int new_dst,
1113 struct stat *src_sb, struct dir_list *ancestors)
1115 char *name_space;
1116 char *namep;
1117 char *src_path;
1118 char *dst_path;
1119 int ret = 0;
1121 errno = 0;
1122 name_space = savedir (src_path_in, src_sb->st_size);
1123 if (name_space == 0)
1125 if (errno)
1127 error (0, errno, "%s", src_path_in);
1128 return -1;
1130 else
1131 error (1, 0, _("virtual memory exhausted"));
1134 namep = name_space;
1135 while (*namep != '\0')
1137 int fn_length = strlen (namep) + 1;
1139 dst_path = xmalloc (strlen (dst_path_in) + fn_length + 1);
1140 src_path = xmalloc (strlen (src_path_in) + fn_length + 1);
1142 stpcpy (stpcpy (stpcpy (src_path, src_path_in), "/"), namep);
1143 stpcpy (stpcpy (stpcpy (dst_path, dst_path_in), "/"), namep);
1145 ret |= copy (src_path, dst_path, new_dst, src_sb->st_dev, ancestors);
1147 /* Free the memory for `src_path'. The memory for `dst_path'
1148 cannot be deallocated, since it is used to create multiple
1149 hard links. */
1151 free (src_path);
1153 namep += fn_length;
1155 free (name_space);
1156 return -ret;
1159 /* Copy a regular file from SRC_PATH to DST_PATH.
1160 If the source file contains holes, copies holes and blocks of zeros
1161 in the source file as holes in the destination file.
1162 (Holes are read as zeroes by the `read' system call.)
1163 Return 0 if successful, -1 if an error occurred. */
1165 static int
1166 copy_reg (char *src_path, char *dst_path)
1168 char *buf;
1169 int buf_size;
1170 int dest_desc;
1171 int source_desc;
1172 int n_read;
1173 struct stat sb;
1174 char *cp;
1175 int *ip;
1176 int return_val = 0;
1177 long n_read_total = 0;
1178 int last_write_made_hole = 0;
1179 int make_holes = (flag_sparse == SPARSE_ALWAYS);
1181 source_desc = open (src_path, O_RDONLY);
1182 if (source_desc < 0)
1184 error (0, errno, "%s", src_path);
1185 return -1;
1188 /* Create the new regular file with small permissions initially,
1189 to not create a security hole. */
1191 dest_desc = open (dst_path, O_WRONLY | O_CREAT | O_TRUNC, 0600);
1192 if (dest_desc < 0)
1194 error (0, errno, _("cannot create regular file `%s'"), dst_path);
1195 return_val = -1;
1196 goto ret2;
1199 /* Find out the optimal buffer size. */
1201 if (fstat (dest_desc, &sb))
1203 error (0, errno, "%s", dst_path);
1204 return_val = -1;
1205 goto ret;
1208 buf_size = ST_BLKSIZE (sb);
1210 #ifdef HAVE_ST_BLOCKS
1211 if (flag_sparse == SPARSE_AUTO && S_ISREG (sb.st_mode))
1213 /* Find out whether the file contains any sparse blocks. */
1215 if (fstat (source_desc, &sb))
1217 error (0, errno, "%s", src_path);
1218 return_val = -1;
1219 goto ret;
1222 /* If the file has fewer blocks than would normally
1223 be needed for a file of its size, then
1224 at least one of the blocks in the file is a hole. */
1225 if (S_ISREG (sb.st_mode) && sb.st_size > sb.st_blocks * DEV_BSIZE)
1226 make_holes = 1;
1228 #endif
1230 /* Make a buffer with space for a sentinel at the end. */
1232 buf = (char *) alloca (buf_size + sizeof (int));
1234 for (;;)
1236 n_read = read (source_desc, buf, buf_size);
1237 if (n_read < 0)
1239 #ifdef EINTR
1240 if (errno == EINTR)
1241 continue;
1242 #endif
1243 error (0, errno, "%s", src_path);
1244 return_val = -1;
1245 goto ret;
1247 if (n_read == 0)
1248 break;
1250 n_read_total += n_read;
1252 ip = 0;
1253 if (make_holes)
1255 buf[n_read] = 1; /* Sentinel to stop loop. */
1257 /* Find first nonzero *word*, or the word with the sentinel. */
1259 ip = (int *) buf;
1260 while (*ip++ == 0)
1263 /* Find the first nonzero *byte*, or the sentinel. */
1265 cp = (char *) (ip - 1);
1266 while (*cp++ == 0)
1269 /* If we found the sentinel, the whole input block was zero,
1270 and we can make a hole. */
1272 if (cp > buf + n_read)
1274 /* Make a hole. */
1275 if (lseek (dest_desc, (off_t) n_read, SEEK_CUR) < 0L)
1277 error (0, errno, "%s", dst_path);
1278 return_val = -1;
1279 goto ret;
1281 last_write_made_hole = 1;
1283 else
1284 /* Clear to indicate that a normal write is needed. */
1285 ip = 0;
1287 if (ip == 0)
1289 if (full_write (dest_desc, buf, n_read) < 0)
1291 error (0, errno, "%s", dst_path);
1292 return_val = -1;
1293 goto ret;
1295 last_write_made_hole = 0;
1299 /* If the file ends with a `hole', something needs to be written at
1300 the end. Otherwise the kernel would truncate the file at the end
1301 of the last write operation. */
1303 if (last_write_made_hole)
1305 #ifdef HAVE_FTRUNCATE
1306 /* Write a null character and truncate it again. */
1307 if (full_write (dest_desc, "", 1) < 0
1308 || ftruncate (dest_desc, n_read_total) < 0)
1309 #else
1310 /* Seek backwards one character and write a null. */
1311 if (lseek (dest_desc, (off_t) -1, SEEK_CUR) < 0L
1312 || full_write (dest_desc, "", 1) < 0)
1313 #endif
1315 error (0, errno, "%s", dst_path);
1316 return_val = -1;
1320 ret:
1321 if (close (dest_desc) < 0)
1323 error (0, errno, "%s", dst_path);
1324 return_val = -1;
1326 ret2:
1327 if (close (source_desc) < 0)
1329 error (0, errno, "%s", src_path);
1330 return_val = -1;
1333 return return_val;