Don't include version.h.
[coreutils.git] / src / cp.c
blob3000aa66a003674ebd7aba147d364124eb967f62
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 "argmatch.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 /* Control creation of sparse files (files with holes). */
46 enum Sparse_type
48 /* Never create holes in DEST. */
49 SPARSE_NEVER,
51 /* This is the default. Use a crude (and sometimes inaccurate)
52 heuristic to determine if SOURCE has holes. If so, try to create
53 holes in DEST. */
54 SPARSE_AUTO,
56 /* For every sufficiently long sequence of bytes in SOURCE, try to
57 create a corresponding hole in DEST. There is a performance penalty
58 here because CP has to search for holes in SRC. But if the holes are
59 big enough, that penalty can be offset by the decrease in the amount
60 of data written to disk. */
61 SPARSE_ALWAYS
64 int stat ();
65 int lstat ();
67 char *dirname ();
68 char *xstrdup ();
69 enum backup_type get_version ();
70 int euidaccess ();
71 int full_write ();
73 static int do_copy __P ((int argc, char **argv));
74 static int copy __P ((char *src_path, char *dst_path, int new_dst,
75 dev_t device, struct dir_list *ancestors));
76 static int copy_dir __P ((char *src_path_in, char *dst_path_in, int new_dst,
77 struct stat *src_sb, struct dir_list *ancestors));
78 static int make_path_private __P ((char *const_dirpath, int src_offset,
79 int mode, char *verbose_fmt_string,
80 struct dir_attr **attr_list, int *new_dst));
81 static int copy_reg __P ((char *src_path, char *dst_path));
82 static int re_protect __P ((char *const_dst_path, int src_offset,
83 struct dir_attr *attr_list));
85 /* Initial number of entries in each hash table entry's table of inodes. */
86 #define INITIAL_HASH_MODULE 100
88 /* Initial number of entries in the inode hash table. */
89 #define INITIAL_ENTRY_TAB_SIZE 70
91 /* The invocation name of this program. */
92 char *program_name;
94 /* A pointer to either lstat or stat, depending on
95 whether dereferencing of symlinks is done. */
96 static int (*xstat) ();
98 /* If nonzero, copy all files except (directories and, if not dereferencing
99 them, symbolic links,) as if they were regular files. */
100 static int flag_copy_as_regular = 1;
102 /* If nonzero, dereference symbolic links (copy the files they point to). */
103 static int flag_dereference = 1;
105 /* If nonzero, remove existing destination nondirectories. */
106 static int flag_force = 0;
108 /* If nonzero, create hard links instead of copying files.
109 Create destination directories as usual. */
110 static int flag_hard_link = 0;
112 /* If nonzero, query before overwriting existing destinations
113 with regular files. */
114 static int flag_interactive = 0;
116 /* If nonzero, the command "cp x/e_file e_dir" uses "e_dir/x/e_file"
117 as its destination instead of the usual "e_dir/e_file." */
118 static int flag_path = 0;
120 /* If nonzero, give the copies the original files' permissions,
121 ownership, and timestamps. */
122 static int flag_preserve = 0;
124 /* If nonzero, copy directories recursively and copy special files
125 as themselves rather than copying their contents. */
126 static int flag_recursive = 0;
128 /* If nonzero, create symbolic links instead of copying files.
129 Create destination directories as usual. */
130 static int flag_symbolic_link = 0;
132 /* If nonzero, when copying recursively, skip any subdirectories that are
133 on different filesystems from the one we started on. */
134 static int flag_one_file_system = 0;
136 /* If nonzero, do not copy a nondirectory that has an existing destination
137 with the same or newer modification time. */
138 static int flag_update = 0;
140 /* If nonzero, display the names of the files before copying them. */
141 static int flag_verbose = 0;
143 static char const *const sparse_type_string[] =
145 "never", "auto", "always", 0
148 static enum Sparse_type const sparse_type[] =
150 SPARSE_NEVER, SPARSE_AUTO, SPARSE_ALWAYS
153 /* Control creation of sparse files. */
154 static int flag_sparse = SPARSE_AUTO;
156 /* The error code to return to the system. */
157 static int exit_status = 0;
159 /* The bits to preserve in created files' modes. */
160 static int umask_kill;
162 /* This process's effective user ID. */
163 static uid_t myeuid;
165 /* If nonzero, display usage information and exit. */
166 static int show_help;
168 /* If nonzero, print the version on standard output and exit. */
169 static int show_version;
171 static struct option const long_opts[] =
173 {"archive", no_argument, NULL, 'a'},
174 {"backup", no_argument, NULL, 'b'},
175 {"force", no_argument, NULL, 'f'},
176 {"sparse", required_argument, NULL, 2},
177 {"interactive", no_argument, NULL, 'i'},
178 {"link", no_argument, NULL, 'l'},
179 {"no-dereference", no_argument, &flag_dereference, 0},
180 {"one-file-system", no_argument, &flag_one_file_system, 1},
181 {"parents", no_argument, &flag_path, 1},
182 {"path", no_argument, &flag_path, 1},
183 {"preserve", no_argument, &flag_preserve, 1},
184 {"recursive", no_argument, NULL, 'R'},
185 {"suffix", required_argument, NULL, 'S'},
186 {"symbolic-link", no_argument, NULL, 's'},
187 {"update", no_argument, &flag_update, 1},
188 {"verbose", no_argument, &flag_verbose, 1},
189 {"version-control", required_argument, NULL, 'V'},
190 {"help", no_argument, &show_help, 1},
191 {"version", no_argument, &show_version, 1},
192 {NULL, 0, NULL, 0}
195 void
196 main (int argc, char **argv)
198 int c;
199 int make_backups = 0;
200 char *version;
202 program_name = argv[0];
203 setlocale (LC_ALL, "");
204 bindtextdomain (PACKAGE, LOCALEDIR);
205 textdomain (PACKAGE);
207 myeuid = geteuid ();
209 version = getenv ("SIMPLE_BACKUP_SUFFIX");
210 if (version)
211 simple_backup_suffix = version;
212 version = getenv ("VERSION_CONTROL");
214 /* Find out the current file creation mask, to knock the right bits
215 when using chmod. The creation mask is set to to be liberal, so
216 that created directories can be written, even if it would not
217 have been allowed with the mask this process was started with. */
219 umask_kill = 0777777 ^ umask (0);
221 while ((c = getopt_long (argc, argv, "abdfilprsuvxPRS:V:", long_opts,
222 (int *) 0)) != EOF)
224 switch (c)
226 case 0:
227 break;
229 case 2:
231 int i;
233 /* --sparse={never,auto,always} */
234 i = argmatch (optarg, sparse_type_string);
235 if (i < 0)
237 invalid_arg (_("sparse type"), optarg, i);
238 usage (2, NULL);
240 flag_sparse = sparse_type[i];
242 break;
244 case 'a': /* Like -dpR. */
245 flag_dereference = 0;
246 flag_preserve = 1;
247 flag_recursive = 1;
248 flag_copy_as_regular = 0;
249 break;
251 case 'b':
252 make_backups = 1;
253 break;
255 case 'd':
256 flag_dereference = 0;
257 break;
259 case 'f':
260 flag_force = 1;
261 flag_interactive = 0;
262 break;
264 case 'i':
265 flag_force = 0;
266 flag_interactive = 1;
267 break;
269 case 'l':
270 flag_hard_link = 1;
271 break;
273 case 'p':
274 flag_preserve = 1;
275 break;
277 case 'P':
278 flag_path = 1;
279 break;
281 case 'r':
282 flag_recursive = 1;
283 flag_copy_as_regular = 1;
284 break;
286 case 'R':
287 flag_recursive = 1;
288 flag_copy_as_regular = 0;
289 break;
291 case 's':
292 #ifdef S_ISLNK
293 flag_symbolic_link = 1;
294 #else
295 error (1, 0, _("symbolic links are not supported on this system"));
296 #endif
297 break;
299 case 'u':
300 flag_update = 1;
301 break;
303 case 'v':
304 flag_verbose = 1;
305 break;
307 case 'x':
308 flag_one_file_system = 1;
309 break;
311 case 'S':
312 simple_backup_suffix = optarg;
313 break;
315 case 'V':
316 version = optarg;
317 break;
319 default:
320 usage (2, (char *) 0);
324 if (show_version)
326 printf ("cp - %s\n", PACKAGE_VERSION);
327 exit (0);
330 if (show_help)
331 usage (0, NULL);
333 if (flag_hard_link && flag_symbolic_link)
334 usage (2, _("cannot make both hard and symbolic links"));
336 if (make_backups)
337 backup_type = get_version (version);
339 if (flag_preserve == 1)
340 umask_kill = 0777777;
342 /* The key difference between -d (--no-dereference) and not is the version
343 of `stat' to call. */
345 if (flag_dereference)
346 xstat = stat;
347 else
348 xstat = lstat;
350 /* Allocate space for remembering copied and created files. */
352 hash_init (INITIAL_HASH_MODULE, INITIAL_ENTRY_TAB_SIZE);
354 exit_status |= do_copy (argc, argv);
356 exit (exit_status);
359 /* Scan the arguments, and copy each by calling copy.
360 Return 0 if successful, 1 if any errors occur. */
362 static int
363 do_copy (int argc, char **argv)
365 char *dest;
366 struct stat sb;
367 int new_dst = 0;
368 int ret = 0;
370 if (optind >= argc)
371 usage (2, _("missing file arguments"));
372 if (optind >= argc - 1)
373 usage (2, _("missing file argument"));
375 dest = argv[argc - 1];
377 if (lstat (dest, &sb))
379 if (errno != ENOENT)
381 error (0, errno, "%s", dest);
382 return 1;
384 else
385 new_dst = 1;
387 else
389 struct stat sbx;
391 /* If `dest' is not a symlink to a nonexistent file, use
392 the results of stat instead of lstat, so we can copy files
393 into symlinks to directories. */
394 if (stat (dest, &sbx) == 0)
395 sb = sbx;
398 if (!new_dst && S_ISDIR (sb.st_mode))
400 /* cp file1...filen edir
401 Copy the files `file1' through `filen'
402 to the existing directory `edir'. */
404 for (;;)
406 char *arg;
407 char *ap;
408 char *dst_path;
409 int parent_exists = 1; /* True if dirname (dst_path) exists. */
410 struct dir_attr *attr_list;
412 arg = argv[optind];
414 strip_trailing_slashes (arg);
416 if (flag_path)
418 /* Append all of `arg' to `dest'. */
419 dst_path = xmalloc (strlen (dest) + strlen (arg) + 2);
420 stpcpy (stpcpy (stpcpy (dst_path, dest), "/"), arg);
422 /* For --parents, we have to make sure that the directory
423 dirname (dst_path) exists. We may have to create a few
424 leading directories. */
425 parent_exists = !make_path_private (dst_path,
426 strlen (dest) + 1, 0700,
427 flag_verbose ? "%s -> %s\n" :
428 (char *) NULL,
429 &attr_list, &new_dst);
431 else
433 /* Append the last component of `arg' to `dest'. */
435 ap = basename (arg);
436 /* For `cp -R source/.. dest', don't copy into `dest/..'. */
437 if (!strcmp (ap, ".."))
438 dst_path = xstrdup (dest);
439 else
441 dst_path = xmalloc (strlen (dest) + strlen (ap) + 2);
442 stpcpy (stpcpy (stpcpy (dst_path, dest), "/"), ap);
446 if (!parent_exists)
448 /* make_path_private failed, so we shouldn't even attempt the copy. */
449 ret = 1;
451 else
453 ret |= copy (arg, dst_path, new_dst, 0, (struct dir_list *) 0);
454 forget_all ();
456 if (flag_path)
458 ret |= re_protect (dst_path, strlen (dest) + 1,
459 attr_list);
463 free (dst_path);
464 ++optind;
465 if (optind == argc - 1)
466 break;
468 return ret;
470 else if (argc - optind == 2)
472 char *new_dest;
473 char *source;
474 struct stat source_stats;
476 if (flag_path)
477 usage (2, _("when preserving paths, last argument must be a directory"));
479 source = argv[optind];
481 /* When the destination is specified with a trailing slash and the
482 source exists but is not a directory, convert the user's command
483 `cp source dest/' to `cp source dest/basename(source)'. */
485 if (dest[strlen (dest) - 1] == '/'
486 && lstat (source, &source_stats) == 0
487 && !S_ISDIR (source_stats.st_mode))
489 char *source_base;
490 char *tmp_source;
492 tmp_source = (char *) alloca (strlen (source) + 1);
493 strcpy (tmp_source, source);
494 strip_trailing_slashes (tmp_source);
495 source_base = basename (tmp_source);
497 new_dest = (char *) alloca (strlen (dest) + 1 +
498 strlen (source_base) + 1);
499 stpcpy (stpcpy (stpcpy (new_dest, dest), "/"), source_base);
501 else
503 new_dest = dest;
506 return copy (source, new_dest, new_dst, 0, (struct dir_list *) 0);
508 else
509 usage (2,
510 _("when copying multiple files, last argument must be a directory"));
513 /* Copy the file SRC_PATH to the file DST_PATH. The files may be of
514 any type. NEW_DST should be nonzero if the file DST_PATH cannot
515 exist because its parent directory was just created; NEW_DST should
516 be zero if DST_PATH might already exist. DEVICE is the device
517 number of the parent directory, or 0 if the parent of this file is
518 not known. ANCESTORS points to a linked, null terminated list of
519 devices and inodes of parent directories of SRC_PATH.
520 Return 0 if successful, 1 if an error occurs. */
522 static int
523 copy (char *src_path, char *dst_path, int new_dst, dev_t device,
524 struct dir_list *ancestors)
526 struct stat src_sb;
527 struct stat dst_sb;
528 int src_mode;
529 int src_type;
530 char *earlier_file;
531 char *dst_backup = NULL;
532 int fix_mode = 0;
534 if ((*xstat) (src_path, &src_sb))
536 error (0, errno, "%s", src_path);
537 return 1;
540 /* Are we crossing a file system boundary? */
541 if (flag_one_file_system && device != 0 && device != src_sb.st_dev)
542 return 0;
544 /* We wouldn't insert a node unless nlink > 1, except that we need to
545 find created files so as to not copy infinitely if a directory is
546 copied into itself. */
548 earlier_file = remember_copied (dst_path, src_sb.st_ino, src_sb.st_dev);
550 /* Did we just create this file? */
552 if (earlier_file == &new_file)
553 return 0;
555 src_mode = src_sb.st_mode;
556 src_type = src_sb.st_mode;
558 if (S_ISDIR (src_type) && !flag_recursive)
560 error (0, 0, _("%s: omitting directory"), src_path);
561 return 1;
564 if (!new_dst)
566 if ((*xstat) (dst_path, &dst_sb))
568 if (errno != ENOENT)
570 error (0, errno, "%s", dst_path);
571 return 1;
573 else
574 new_dst = 1;
576 else
578 /* The file exists already. */
580 if (src_sb.st_ino == dst_sb.st_ino && src_sb.st_dev == dst_sb.st_dev)
582 if (flag_hard_link)
583 return 0;
585 error (0, 0, _("`%s' and `%s' are the same file"),
586 src_path, dst_path);
587 return 1;
590 if (!S_ISDIR (src_type))
592 if (S_ISDIR (dst_sb.st_mode))
594 error (0, 0,
595 _("%s: cannot overwrite directory with non-directory"),
596 dst_path);
597 return 1;
600 if (flag_update && src_sb.st_mtime <= dst_sb.st_mtime)
601 return 0;
604 if (S_ISREG (src_type) && !flag_force)
606 if (flag_interactive)
608 if (euidaccess (dst_path, W_OK) != 0)
609 fprintf (stderr,
610 _("%s: overwrite `%s', overriding mode %04o? "),
611 program_name, dst_path,
612 (unsigned int) (dst_sb.st_mode & 07777));
613 else
614 fprintf (stderr, _("%s: overwrite `%s'? "),
615 program_name, dst_path);
616 if (!yesno ())
617 return 0;
621 if (backup_type != none && !S_ISDIR (dst_sb.st_mode))
623 char *tmp_backup = find_backup_file_name (dst_path);
624 if (tmp_backup == NULL)
625 error (1, 0, _("virtual memory exhausted"));
627 /* Detect (and fail) when creating the backup file would
628 destroy the source file. Before, running the commands
629 cd /tmp; rm -f a a~; : > a; echo A > a~; cp -b -V simple a~ a
630 would leave two zero-length files: a and a~. */
631 if (strcmp (tmp_backup, src_path) == 0)
633 error (0, 0,
634 _("backing up `%s' would destroy source; `%s' not copied"),
635 dst_path, src_path);
636 return 1;
639 dst_backup = (char *) alloca (strlen (tmp_backup) + 1);
640 strcpy (dst_backup, tmp_backup);
641 free (tmp_backup);
642 if (rename (dst_path, dst_backup))
644 if (errno != ENOENT)
646 error (0, errno, _("cannot backup `%s'"), dst_path);
647 return 1;
649 else
650 dst_backup = NULL;
652 new_dst = 1;
654 else if (flag_force)
656 if (S_ISDIR (dst_sb.st_mode))
658 /* Temporarily change mode to allow overwriting. */
659 if (euidaccess (dst_path, W_OK | X_OK) != 0)
661 if (chmod (dst_path, 0700))
663 error (0, errno, "%s", dst_path);
664 return 1;
666 else
667 fix_mode = 1;
670 else
672 if (unlink (dst_path) && errno != ENOENT)
674 error (0, errno, _("cannot remove old link to `%s'"),
675 dst_path);
676 return 1;
678 new_dst = 1;
684 /* If the source is a directory, we don't always create the destination
685 directory. So --verbose should not announce anything until we're
686 sure we'll create a directory. */
687 if (flag_verbose && !S_ISDIR (src_type))
688 printf ("%s -> %s\n", src_path, dst_path);
690 /* Did we copy this inode somewhere else (in this command line argument)
691 and therefore this is a second hard link to the inode? */
693 if (!flag_dereference && src_sb.st_nlink > 1 && earlier_file)
695 if (link (earlier_file, dst_path))
697 error (0, errno, "%s", dst_path);
698 goto un_backup;
700 return 0;
703 if (S_ISDIR (src_type))
705 struct dir_list *dir;
707 /* If this directory has been copied before during the
708 recursion, there is a symbolic link to an ancestor
709 directory of the symbolic link. It is impossible to
710 continue to copy this, unless we've got an infinite disk. */
712 if (is_ancestor (&src_sb, ancestors))
714 error (0, 0, _("%s: cannot copy cyclic symbolic link"), src_path);
715 goto un_backup;
718 /* Insert the current directory in the list of parents. */
720 dir = (struct dir_list *) alloca (sizeof (struct dir_list));
721 dir->parent = ancestors;
722 dir->ino = src_sb.st_ino;
723 dir->dev = src_sb.st_dev;
725 if (new_dst || !S_ISDIR (dst_sb.st_mode))
727 /* Create the new directory writable and searchable, so
728 we can create new entries in it. */
730 if (mkdir (dst_path, (src_mode & umask_kill) | 0700))
732 error (0, errno, _("cannot create directory `%s'"), dst_path);
733 goto un_backup;
736 /* Insert the created directory's inode and device
737 numbers into the search structure, so that we can
738 avoid copying it again. */
740 if (remember_created (dst_path))
741 goto un_backup;
743 if (flag_verbose)
744 printf ("%s -> %s\n", src_path, dst_path);
747 /* Copy the contents of the directory. */
749 if (copy_dir (src_path, dst_path, new_dst, &src_sb, dir))
750 return 1;
752 #ifdef S_ISLNK
753 else if (flag_symbolic_link)
755 if (*src_path == '/'
756 || (!strncmp (dst_path, "./", 2) && strchr (dst_path + 2, '/') == 0)
757 || strchr (dst_path, '/') == 0)
759 if (symlink (src_path, dst_path))
761 error (0, errno, "%s", dst_path);
762 goto un_backup;
764 return 0;
766 else
768 error (0, 0,
769 _("%s: can only make relative symbolic links in current directory"), dst_path);
770 goto un_backup;
773 #endif
774 else if (flag_hard_link)
776 if (link (src_path, dst_path))
778 error (0, errno, _("cannot create link `%s'"), dst_path);
779 goto un_backup;
781 return 0;
783 else if (S_ISREG (src_type)
784 || (flag_copy_as_regular && !S_ISDIR (src_type)
785 #ifdef S_ISLNK
786 && !S_ISLNK (src_type)
787 #endif
790 if (copy_reg (src_path, dst_path))
791 goto un_backup;
793 else
794 #ifdef S_ISFIFO
795 if (S_ISFIFO (src_type))
797 if (mkfifo (dst_path, src_mode & umask_kill))
799 error (0, errno, _("cannot create fifo `%s'"), dst_path);
800 goto un_backup;
803 else
804 #endif
805 if (S_ISBLK (src_type) || S_ISCHR (src_type)
806 #ifdef S_ISSOCK
807 || S_ISSOCK (src_type)
808 #endif
811 if (mknod (dst_path, src_mode & umask_kill, src_sb.st_rdev))
813 error (0, errno, _("cannot create special file `%s'"), dst_path);
814 goto un_backup;
817 else
818 #ifdef S_ISLNK
819 if (S_ISLNK (src_type))
821 char *link_val;
822 int link_size;
824 link_val = (char *) alloca (PATH_MAX + 2);
825 link_size = readlink (src_path, link_val, PATH_MAX + 1);
826 if (link_size < 0)
828 error (0, errno, _("cannot read symbolic link `%s'"), src_path);
829 goto un_backup;
831 link_val[link_size] = '\0';
833 if (symlink (link_val, dst_path))
835 error (0, errno, _("cannot create symbolic link `%s'"), dst_path);
836 goto un_backup;
838 return 0;
840 else
841 #endif
843 error (0, 0, _("%s: unknown file type"), src_path);
844 goto un_backup;
847 /* Adjust the times (and if possible, ownership) for the copy.
848 chown turns off set[ug]id bits for non-root,
849 so do the chmod last. */
851 if (flag_preserve)
853 struct utimbuf utb;
855 utb.actime = src_sb.st_atime;
856 utb.modtime = src_sb.st_mtime;
858 if (utime (dst_path, &utb))
860 error (0, errno, "%s", dst_path);
861 return 1;
864 /* If non-root uses -p, it's ok if we can't preserve ownership.
865 But root probably wants to know, e.g. if NFS disallows it. */
866 if (chown (dst_path,
867 (myeuid == 0 ? src_sb.st_uid : myeuid),
868 src_sb.st_gid)
869 && (errno != EPERM || myeuid == 0))
871 error (0, errno, "%s", dst_path);
872 return 1;
876 if ((flag_preserve || new_dst)
877 && (flag_copy_as_regular || S_ISREG (src_type) || S_ISDIR (src_type)))
879 if (chmod (dst_path, src_mode & umask_kill))
881 error (0, errno, "%s", dst_path);
882 return 1;
885 else if (fix_mode)
887 /* Reset the temporarily changed mode. */
888 if (chmod (dst_path, dst_sb.st_mode))
890 error (0, errno, "%s", dst_path);
891 return 1;
895 return 0;
897 un_backup:
898 if (dst_backup)
900 if (rename (dst_backup, dst_path))
901 error (0, errno, _("cannot un-backup `%s'"), dst_path);
903 return 1;
906 /* Ensure that the parent directory of CONST_DIRPATH exists, for
907 the --parents option.
909 SRC_OFFSET is the index in CONST_DIRPATH (which is a destination
910 path) of the beginning of the source directory name.
911 Create any leading directories that don't already exist,
912 giving them permissions MODE.
913 If VERBOSE_FMT_STRING is nonzero, use it as a printf format
914 string for printing a message after successfully making a directory.
915 The format should take two string arguments: the names of the
916 source and destination directories.
917 Creates a linked list of attributes of intermediate directories,
918 *ATTR_LIST, for re_protect to use after calling copy.
919 Sets *NEW_DST to 1 if this function creates parent of CONST_DIRPATH.
921 Return 0 if parent of CONST_DIRPATH exists as a directory with the proper
922 permissions when done, otherwise 1. */
924 static int
925 make_path_private (char *const_dirpath, int src_offset, int mode,
926 char *verbose_fmt_string, struct dir_attr **attr_list,
927 int *new_dst)
929 struct stat stats;
930 char *dirpath; /* A copy of CONST_DIRPATH we can change. */
931 char *src; /* Source name in `dirpath'. */
932 char *tmp_dst_dirname; /* Leading path of `dirpath', malloc. */
933 char *dst_dirname; /* Leading path of `dirpath', alloca. */
935 dirpath = (char *) alloca (strlen (const_dirpath) + 1);
936 strcpy (dirpath, const_dirpath);
938 src = dirpath + src_offset;
940 tmp_dst_dirname = dirname (dirpath);
941 dst_dirname = (char *) alloca (strlen (tmp_dst_dirname) + 1);
942 strcpy (dst_dirname, tmp_dst_dirname);
943 free (tmp_dst_dirname);
945 *attr_list = NULL;
947 if ((*xstat) (dst_dirname, &stats))
949 /* Parent of CONST_DIRNAME does not exist.
950 Make all missing intermediate directories. */
951 char *slash;
953 slash = src;
954 while (*slash == '/')
955 slash++;
956 while ((slash = strchr (slash, '/')))
958 /* Add this directory to the list of directories whose modes need
959 fixing later. */
960 struct dir_attr *new =
961 (struct dir_attr *) xmalloc (sizeof (struct dir_attr));
962 new->slash_offset = slash - dirpath;
963 new->next = *attr_list;
964 *attr_list = new;
966 *slash = '\0';
967 if ((*xstat) (dirpath, &stats))
969 /* This element of the path does not exist. We must set
970 *new_dst and new->is_new_dir inside this loop because,
971 for example, in the command `cp --parents ../a/../b/c e_dir',
972 make_path_private creates only e_dir/../a if ./b already
973 exists. */
974 *new_dst = 1;
975 new->is_new_dir = 1;
976 if (mkdir (dirpath, mode))
978 error (0, errno, _("cannot make directory `%s'"), dirpath);
979 return 1;
981 else
983 if (verbose_fmt_string != NULL)
984 printf (verbose_fmt_string, src, dirpath);
987 else if (!S_ISDIR (stats.st_mode))
989 error (0, 0, _("`%s' exists but is not a directory"), dirpath);
990 return 1;
992 else
994 new->is_new_dir = 0;
995 *new_dst = 0;
997 *slash++ = '/';
999 /* Avoid unnecessary calls to `stat' when given
1000 pathnames containing multiple adjacent slashes. */
1001 while (*slash == '/')
1002 slash++;
1006 /* We get here if the parent of `dirpath' already exists. */
1008 else if (!S_ISDIR (stats.st_mode))
1010 error (0, 0, _("`%s' exists but is not a directory"), dst_dirname);
1011 return 1;
1013 else
1015 *new_dst = 0;
1017 return 0;
1020 /* Ensure that the parent directories of CONST_DST_PATH have the
1021 correct protections, for the --parents option. This is done
1022 after all copying has been completed, to allow permissions
1023 that don't include user write/execute.
1025 SRC_OFFSET is the index in CONST_DST_PATH of the beginning of the
1026 source directory name.
1028 ATTR_LIST is a null-terminated linked list of structures that
1029 indicates the end of the filename of each intermediate directory
1030 in CONST_DST_PATH that may need to have its attributes changed.
1031 The command `cp --parents --preserve a/b/c d/e_dir' changes the
1032 attributes of the directories d/e_dir/a and d/e_dir/a/b to match
1033 the corresponding source directories regardless of whether they
1034 existed before the `cp' command was given.
1036 Return 0 if the parent of CONST_DST_PATH and any intermediate
1037 directories specified by ATTR_LIST have the proper permissions
1038 when done, otherwise 1. */
1040 static int
1041 re_protect (char *const_dst_path, int src_offset, struct dir_attr *attr_list)
1043 struct dir_attr *p;
1044 char *dst_path; /* A copy of CONST_DST_PATH we can change. */
1045 char *src_path; /* The source name in `dst_path'. */
1047 dst_path = (char *) alloca (strlen (const_dst_path) + 1);
1048 strcpy (dst_path, const_dst_path);
1049 src_path = dst_path + src_offset;
1051 for (p = attr_list; p; p = p->next)
1053 struct stat src_sb;
1055 dst_path[p->slash_offset] = '\0';
1057 if ((*xstat) (src_path, &src_sb))
1059 error (0, errno, "%s", src_path);
1060 return 1;
1063 /* Adjust the times (and if possible, ownership) for the copy.
1064 chown turns off set[ug]id bits for non-root,
1065 so do the chmod last. */
1067 if (flag_preserve)
1069 struct utimbuf utb;
1071 utb.actime = src_sb.st_atime;
1072 utb.modtime = src_sb.st_mtime;
1074 if (utime (dst_path, &utb))
1076 error (0, errno, "%s", dst_path);
1077 return 1;
1080 /* If non-root uses -p, it's ok if we can't preserve ownership.
1081 But root probably wants to know, e.g. if NFS disallows it. */
1082 if (chown (dst_path, src_sb.st_uid, src_sb.st_gid)
1083 && (errno != EPERM || myeuid == 0))
1085 error (0, errno, "%s", dst_path);
1086 return 1;
1090 if (flag_preserve || p->is_new_dir)
1092 if (chmod (dst_path, src_sb.st_mode & umask_kill))
1094 error (0, errno, "%s", dst_path);
1095 return 1;
1099 dst_path[p->slash_offset] = '/';
1101 return 0;
1104 /* Read the contents of the directory SRC_PATH_IN, and recursively
1105 copy the contents to DST_PATH_IN. NEW_DST is nonzero if
1106 DST_PATH_IN is a directory that was created previously in the
1107 recursion. SRC_SB and ANCESTORS describe SRC_PATH_IN.
1108 Return 0 if successful, -1 if an error occurs. */
1110 static int
1111 copy_dir (char *src_path_in, char *dst_path_in, int new_dst,
1112 struct stat *src_sb, struct dir_list *ancestors)
1114 char *name_space;
1115 char *namep;
1116 char *src_path;
1117 char *dst_path;
1118 int ret = 0;
1120 errno = 0;
1121 name_space = savedir (src_path_in, src_sb->st_size);
1122 if (name_space == 0)
1124 if (errno)
1126 error (0, errno, "%s", src_path_in);
1127 return -1;
1129 else
1130 error (1, 0, _("virtual memory exhausted"));
1133 namep = name_space;
1134 while (*namep != '\0')
1136 int fn_length = strlen (namep) + 1;
1138 dst_path = xmalloc (strlen (dst_path_in) + fn_length + 1);
1139 src_path = xmalloc (strlen (src_path_in) + fn_length + 1);
1141 stpcpy (stpcpy (stpcpy (src_path, src_path_in), "/"), namep);
1142 stpcpy (stpcpy (stpcpy (dst_path, dst_path_in), "/"), namep);
1144 ret |= copy (src_path, dst_path, new_dst, src_sb->st_dev, ancestors);
1146 /* Free the memory for `src_path'. The memory for `dst_path'
1147 cannot be deallocated, since it is used to create multiple
1148 hard links. */
1150 free (src_path);
1152 namep += fn_length;
1154 free (name_space);
1155 return -ret;
1158 /* Copy a regular file from SRC_PATH to DST_PATH.
1159 If the source file contains holes, copies holes and blocks of zeros
1160 in the source file as holes in the destination file.
1161 (Holes are read as zeroes by the `read' system call.)
1162 Return 0 if successful, -1 if an error occurred. */
1164 static int
1165 copy_reg (char *src_path, char *dst_path)
1167 char *buf;
1168 int buf_size;
1169 int dest_desc;
1170 int source_desc;
1171 int n_read;
1172 struct stat sb;
1173 char *cp;
1174 int *ip;
1175 int return_val = 0;
1176 long n_read_total = 0;
1177 int last_write_made_hole = 0;
1178 int make_holes = (flag_sparse == SPARSE_ALWAYS);
1180 source_desc = open (src_path, O_RDONLY);
1181 if (source_desc < 0)
1183 error (0, errno, "%s", src_path);
1184 return -1;
1187 /* Create the new regular file with small permissions initially,
1188 to not create a security hole. */
1190 dest_desc = open (dst_path, O_WRONLY | O_CREAT | O_TRUNC, 0600);
1191 if (dest_desc < 0)
1193 error (0, errno, _("cannot create regular file `%s'"), dst_path);
1194 return_val = -1;
1195 goto ret2;
1198 /* Find out the optimal buffer size. */
1200 if (fstat (dest_desc, &sb))
1202 error (0, errno, "%s", dst_path);
1203 return_val = -1;
1204 goto ret;
1207 buf_size = ST_BLKSIZE (sb);
1209 #ifdef HAVE_ST_BLOCKS
1210 if (flag_sparse == SPARSE_AUTO && S_ISREG (sb.st_mode))
1212 /* Find out whether the file contains any sparse blocks. */
1214 if (fstat (source_desc, &sb))
1216 error (0, errno, "%s", src_path);
1217 return_val = -1;
1218 goto ret;
1221 /* If the file has fewer blocks than would normally
1222 be needed for a file of its size, then
1223 at least one of the blocks in the file is a hole. */
1224 if (S_ISREG (sb.st_mode) && sb.st_size > sb.st_blocks * DEV_BSIZE)
1225 make_holes = 1;
1227 #endif
1229 /* Make a buffer with space for a sentinel at the end. */
1231 buf = (char *) alloca (buf_size + sizeof (int));
1233 for (;;)
1235 n_read = read (source_desc, buf, buf_size);
1236 if (n_read < 0)
1238 #ifdef EINTR
1239 if (errno == EINTR)
1240 continue;
1241 #endif
1242 error (0, errno, "%s", src_path);
1243 return_val = -1;
1244 goto ret;
1246 if (n_read == 0)
1247 break;
1249 n_read_total += n_read;
1251 ip = 0;
1252 if (make_holes)
1254 buf[n_read] = 1; /* Sentinel to stop loop. */
1256 /* Find first nonzero *word*, or the word with the sentinel. */
1258 ip = (int *) buf;
1259 while (*ip++ == 0)
1262 /* Find the first nonzero *byte*, or the sentinel. */
1264 cp = (char *) (ip - 1);
1265 while (*cp++ == 0)
1268 /* If we found the sentinel, the whole input block was zero,
1269 and we can make a hole. */
1271 if (cp > buf + n_read)
1273 /* Make a hole. */
1274 if (lseek (dest_desc, (off_t) n_read, SEEK_CUR) < 0L)
1276 error (0, errno, "%s", dst_path);
1277 return_val = -1;
1278 goto ret;
1280 last_write_made_hole = 1;
1282 else
1283 /* Clear to indicate that a normal write is needed. */
1284 ip = 0;
1286 if (ip == 0)
1288 if (full_write (dest_desc, buf, n_read) < 0)
1290 error (0, errno, "%s", dst_path);
1291 return_val = -1;
1292 goto ret;
1294 last_write_made_hole = 0;
1298 /* If the file ends with a `hole', something needs to be written at
1299 the end. Otherwise the kernel would truncate the file at the end
1300 of the last write operation. */
1302 if (last_write_made_hole)
1304 #ifdef HAVE_FTRUNCATE
1305 /* Write a null character and truncate it again. */
1306 if (full_write (dest_desc, "", 1) < 0
1307 || ftruncate (dest_desc, n_read_total) < 0)
1308 #else
1309 /* Seek backwards one character and write a null. */
1310 if (lseek (dest_desc, (off_t) -1, SEEK_CUR) < 0L
1311 || full_write (dest_desc, "", 1) < 0)
1312 #endif
1314 error (0, errno, "%s", dst_path);
1315 return_val = -1;
1319 ret:
1320 if (close (dest_desc) < 0)
1322 error (0, errno, "%s", dst_path);
1323 return_val = -1;
1325 ret2:
1326 if (close (source_desc) < 0)
1328 error (0, errno, "%s", src_path);
1329 return_val = -1;
1332 return return_val;