.
[coreutils.git] / src / cp.c
blob2be3a3a68d89f99829de4e724a10728d516dc97e
1 /* cp.c -- file copying (main routines)
2 Copyright (C) 89, 90, 91, 95, 1996 Free Software Foundation.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
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 Foundation,
16 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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>
27 #define NDEBUG
28 #include <assert.h>
30 #include <getopt.h>
31 #include "cp.h"
32 #include "backupfile.h"
33 #include "argmatch.h"
35 #ifndef _POSIX_VERSION
36 uid_t geteuid ();
37 #endif
39 #ifdef HAVE_LCHOWN
40 # define chown(PATH, OWNER, GROUP) lchown(PATH, OWNER, GROUP)
41 #endif
43 /* Used by do_copy, make_path_private, and re_protect
44 to keep a list of leading directories whose protections
45 need to be fixed after copying. */
46 struct dir_attr
48 int is_new_dir;
49 int slash_offset;
50 struct dir_attr *next;
53 /* Control creation of sparse files (files with holes). */
54 enum Sparse_type
56 /* Never create holes in DEST. */
57 SPARSE_NEVER,
59 /* This is the default. Use a crude (and sometimes inaccurate)
60 heuristic to determine if SOURCE has holes. If so, try to create
61 holes in DEST. */
62 SPARSE_AUTO,
64 /* For every sufficiently long sequence of bytes in SOURCE, try to
65 create a corresponding hole in DEST. There is a performance penalty
66 here because CP has to search for holes in SRC. But if the holes are
67 big enough, that penalty can be offset by the decrease in the amount
68 of data written to disk. */
69 SPARSE_ALWAYS
72 int stat ();
73 int lstat ();
75 char *dirname ();
76 char *xstrdup ();
77 enum backup_type get_version ();
78 int euidaccess ();
79 int full_write ();
81 static int do_copy __P ((int argc, char **argv));
82 static int copy __P ((const char *src_path, const char *dst_path, int new_dst,
83 dev_t device, struct dir_list *ancestors));
84 static int copy_dir __P ((const char *src_path_in, const char *dst_path_in,
85 int new_dst, const struct stat *src_sb,
86 struct dir_list *ancestors));
87 static int make_path_private __P ((const char *const_dirpath, int src_offset,
88 int mode, const char *verbose_fmt_string,
89 struct dir_attr **attr_list, int *new_dst));
90 static int copy_reg __P ((const char *src_path, const char *dst_path));
91 static int re_protect __P ((const char *const_dst_path, int src_offset,
92 struct dir_attr *attr_list));
94 /* Initial number of entries in each hash table entry's table of inodes. */
95 #define INITIAL_HASH_MODULE 100
97 /* Initial number of entries in the inode hash table. */
98 #define INITIAL_ENTRY_TAB_SIZE 70
100 /* The invocation name of this program. */
101 char *program_name;
103 /* A pointer to either lstat or stat, depending on
104 whether dereferencing of symlinks is done. */
105 static int (*xstat) ();
107 /* If nonzero, copy all files except (directories and, if not dereferencing
108 them, symbolic links,) as if they were regular files. */
109 static int flag_copy_as_regular = 1;
111 /* If nonzero, dereference symbolic links (copy the files they point to). */
112 static int flag_dereference = 1;
114 /* If nonzero, remove existing destination nondirectories. */
115 static int flag_force = 0;
117 /* If nonzero, create hard links instead of copying files.
118 Create destination directories as usual. */
119 static int flag_hard_link = 0;
121 /* If nonzero, query before overwriting existing destinations
122 with regular files. */
123 static int flag_interactive = 0;
125 /* If nonzero, the command "cp x/e_file e_dir" uses "e_dir/x/e_file"
126 as its destination instead of the usual "e_dir/e_file." */
127 static int flag_path = 0;
129 /* If nonzero, give the copies the original files' permissions,
130 ownership, and timestamps. */
131 static int flag_preserve = 0;
133 /* If nonzero, copy directories recursively and copy special files
134 as themselves rather than copying their contents. */
135 static int flag_recursive = 0;
137 /* If nonzero, create symbolic links instead of copying files.
138 Create destination directories as usual. */
139 static int flag_symbolic_link = 0;
141 /* If nonzero, when copying recursively, skip any subdirectories that are
142 on different filesystems from the one we started on. */
143 static int flag_one_file_system = 0;
145 /* If nonzero, do not copy a nondirectory that has an existing destination
146 with the same or newer modification time. */
147 static int flag_update = 0;
149 /* If nonzero, display the names of the files before copying them. */
150 static int flag_verbose = 0;
152 static char const *const sparse_type_string[] =
154 "never", "auto", "always", 0
157 static enum Sparse_type const sparse_type[] =
159 SPARSE_NEVER, SPARSE_AUTO, SPARSE_ALWAYS
162 /* Control creation of sparse files. */
163 static int flag_sparse = SPARSE_AUTO;
165 /* The error code to return to the system. */
166 static int exit_status = 0;
168 /* The bits to preserve in created files' modes. */
169 static int umask_kill;
171 /* This process's effective user ID. */
172 static uid_t myeuid;
174 /* If nonzero, display usage information and exit. */
175 static int show_help;
177 /* If nonzero, print the version on standard output and exit. */
178 static int show_version;
180 static struct option const long_opts[] =
182 {"archive", no_argument, NULL, 'a'},
183 {"backup", no_argument, NULL, 'b'},
184 {"force", no_argument, NULL, 'f'},
185 {"sparse", required_argument, NULL, 2},
186 {"interactive", no_argument, NULL, 'i'},
187 {"link", no_argument, NULL, 'l'},
188 {"no-dereference", no_argument, &flag_dereference, 0},
189 {"one-file-system", no_argument, &flag_one_file_system, 1},
190 {"parents", no_argument, &flag_path, 1},
191 {"path", no_argument, &flag_path, 1},
192 {"preserve", no_argument, &flag_preserve, 1},
193 {"recursive", no_argument, NULL, 'R'},
194 {"suffix", required_argument, NULL, 'S'},
195 {"symbolic-link", no_argument, NULL, 's'},
196 {"update", no_argument, &flag_update, 1},
197 {"verbose", no_argument, &flag_verbose, 1},
198 {"version-control", required_argument, NULL, 'V'},
199 {"help", no_argument, &show_help, 1},
200 {"version", no_argument, &show_version, 1},
201 {NULL, 0, NULL, 0}
205 main (int argc, char **argv)
207 int c;
208 int make_backups = 0;
209 char *version;
211 program_name = argv[0];
212 setlocale (LC_ALL, "");
213 bindtextdomain (PACKAGE, LOCALEDIR);
214 textdomain (PACKAGE);
216 myeuid = geteuid ();
218 version = getenv ("SIMPLE_BACKUP_SUFFIX");
219 if (version)
220 simple_backup_suffix = version;
221 version = getenv ("VERSION_CONTROL");
223 /* Find out the current file creation mask, to knock the right bits
224 when using chmod. The creation mask is set to to be liberal, so
225 that created directories can be written, even if it would not
226 have been allowed with the mask this process was started with. */
228 umask_kill = 0777777 ^ umask (0);
230 while ((c = getopt_long (argc, argv, "abdfilprsuvxPRS:V:", long_opts,
231 (int *) 0)) != EOF)
233 switch (c)
235 case 0:
236 break;
238 case 2:
240 int i;
242 /* --sparse={never,auto,always} */
243 i = argmatch (optarg, sparse_type_string);
244 if (i < 0)
246 invalid_arg (_("sparse type"), optarg, i);
247 usage (2, NULL);
249 flag_sparse = sparse_type[i];
251 break;
253 case 'a': /* Like -dpR. */
254 flag_dereference = 0;
255 flag_preserve = 1;
256 flag_recursive = 1;
257 flag_copy_as_regular = 0;
258 break;
260 case 'b':
261 make_backups = 1;
262 break;
264 case 'd':
265 flag_dereference = 0;
266 break;
268 case 'f':
269 flag_force = 1;
270 flag_interactive = 0;
271 break;
273 case 'i':
274 flag_force = 0;
275 flag_interactive = 1;
276 break;
278 case 'l':
279 flag_hard_link = 1;
280 break;
282 case 'p':
283 flag_preserve = 1;
284 break;
286 case 'P':
287 flag_path = 1;
288 break;
290 case 'r':
291 flag_recursive = 1;
292 flag_copy_as_regular = 1;
293 break;
295 case 'R':
296 flag_recursive = 1;
297 flag_copy_as_regular = 0;
298 break;
300 case 's':
301 #ifdef S_ISLNK
302 flag_symbolic_link = 1;
303 #else
304 error (1, 0, _("symbolic links are not supported on this system"));
305 #endif
306 break;
308 case 'u':
309 flag_update = 1;
310 break;
312 case 'v':
313 flag_verbose = 1;
314 break;
316 case 'x':
317 flag_one_file_system = 1;
318 break;
320 case 'S':
321 simple_backup_suffix = optarg;
322 break;
324 case 'V':
325 version = optarg;
326 break;
328 default:
329 usage (2, (char *) 0);
333 if (show_version)
335 printf ("cp - %s\n", PACKAGE_VERSION);
336 exit (0);
339 if (show_help)
340 usage (0, NULL);
342 if (flag_hard_link && flag_symbolic_link)
343 usage (2, _("cannot make both hard and symbolic links"));
345 if (make_backups)
346 backup_type = get_version (version);
348 if (flag_preserve == 1)
349 umask_kill = 0777777;
351 /* The key difference between -d (--no-dereference) and not is the version
352 of `stat' to call. */
354 if (flag_dereference)
355 xstat = stat;
356 else
357 xstat = lstat;
359 /* Allocate space for remembering copied and created files. */
361 hash_init (INITIAL_HASH_MODULE, INITIAL_ENTRY_TAB_SIZE);
363 exit_status |= do_copy (argc, argv);
365 exit (exit_status);
368 /* Concatenate two pathname components, DIR and BASE, in newly-allocated
369 storage and return the result. Be careful that in the result they are
370 separated by a slash. That is, if DIR ends with a slash or if BASE
371 begins with one, don't add a separating slash. Otherwise, add one. */
373 static char *
374 path_concat (const char *dir, const char *base)
376 char *dir_end;
377 char *p_concat;
379 assert (strlen (dir) > 0);
380 p_concat = xmalloc (strlen (dir) + strlen (base) + 2);
381 dir_end = stpcpy (p_concat, dir);
382 if (*(dir_end - 1) == '/')
383 --dir_end;
384 else if (*base == '/')
385 ++base;
386 stpcpy (stpcpy (dir_end, "/"), base);
387 return p_concat;
390 /* Scan the arguments, and copy each by calling copy.
391 Return 0 if successful, 1 if any errors occur. */
393 static int
394 do_copy (int argc, char **argv)
396 char *dest;
397 struct stat sb;
398 int new_dst = 0;
399 int ret = 0;
401 if (optind >= argc)
402 usage (2, _("missing file arguments"));
403 if (optind >= argc - 1)
404 usage (2, _("missing destination file"));
406 dest = argv[argc - 1];
408 if (lstat (dest, &sb))
410 if (errno != ENOENT)
412 error (0, errno, "%s", dest);
413 return 1;
415 else
416 new_dst = 1;
418 else
420 struct stat sbx;
422 /* If `dest' is not a symlink to a nonexistent file, use
423 the results of stat instead of lstat, so we can copy files
424 into symlinks to directories. */
425 if (stat (dest, &sbx) == 0)
426 sb = sbx;
429 if (!new_dst && S_ISDIR (sb.st_mode))
431 /* cp file1...filen edir
432 Copy the files `file1' through `filen'
433 to the existing directory `edir'. */
435 for (;;)
437 char *arg;
438 char *ap;
439 char *dst_path;
440 int parent_exists = 1; /* True if dirname (dst_path) exists. */
441 struct dir_attr *attr_list;
443 arg = argv[optind];
445 strip_trailing_slashes (arg);
447 if (flag_path)
449 /* Append all of `arg' to `dest'. */
450 dst_path = path_concat (dest, arg);
452 /* For --parents, we have to make sure that the directory
453 dirname (dst_path) exists. We may have to create a few
454 leading directories. */
455 parent_exists = !make_path_private (dst_path,
456 strlen (dest) + 1, 0700,
457 (flag_verbose
458 ? "%s -> %s\n" : NULL),
459 &attr_list, &new_dst);
461 else
463 /* Append the last component of `arg' to `dest'. */
465 ap = basename (arg);
466 /* For `cp -R source/.. dest', don't copy into `dest/..'. */
467 dst_path = (STREQ (ap, "..")
468 ? xstrdup (dest)
469 : path_concat (dest, ap));
472 if (!parent_exists)
474 /* make_path_private failed, so don't even attempt the copy. */
475 ret = 1;
477 else
479 ret |= copy (arg, dst_path, new_dst, 0, (struct dir_list *) 0);
480 forget_all ();
482 if (flag_path)
484 ret |= re_protect (dst_path, strlen (dest) + 1, attr_list);
488 free (dst_path);
489 ++optind;
490 if (optind == argc - 1)
491 break;
493 return ret;
495 else if (argc - optind == 2)
497 char *new_dest;
498 char *source;
499 struct stat source_stats;
501 if (flag_path)
502 usage (2,
503 _("when preserving paths, last argument must be a directory"));
505 source = argv[optind];
507 /* When the force and backup options have been specified and
508 the source and destination are the same name for an existing
509 regular file, convert the user's command, e.g.,
510 `cp --force --backup foo foo' to `cp --force foo fooSUFFIX'
511 where SUFFIX is determined by any version control options used. */
513 if (flag_force
514 && backup_type != none
515 && STREQ (source, dest)
516 && !new_dst && S_ISREG (sb.st_mode))
518 backup_type = none;
519 new_dest = find_backup_file_name (dest);
520 if (new_dest == NULL)
521 error (1, 0, _("virtual memory exhausted"));
524 /* When the destination is specified with a trailing slash and the
525 source exists but is not a directory, convert the user's command
526 `cp source dest/' to `cp source dest/basename(source)'. */
528 else if (dest[strlen (dest) - 1] == '/'
529 && lstat (source, &source_stats) == 0
530 && !S_ISDIR (source_stats.st_mode))
532 char *source_base;
533 char *tmp_source;
535 tmp_source = (char *) alloca (strlen (source) + 1);
536 strcpy (tmp_source, source);
537 strip_trailing_slashes (tmp_source);
538 source_base = basename (tmp_source);
540 new_dest = (char *) alloca (strlen (dest) + 1 +
541 strlen (source_base) + 1);
542 stpcpy (stpcpy (stpcpy (new_dest, dest), "/"), source_base);
544 else
546 new_dest = dest;
549 return copy (source, new_dest, new_dst, 0, (struct dir_list *) 0);
551 else
552 usage (2,
553 _("when copying multiple files, last argument must be a directory"));
556 /* Copy the file SRC_PATH to the file DST_PATH. The files may be of
557 any type. NEW_DST should be nonzero if the file DST_PATH cannot
558 exist because its parent directory was just created; NEW_DST should
559 be zero if DST_PATH might already exist. DEVICE is the device
560 number of the parent directory, or 0 if the parent of this file is
561 not known. ANCESTORS points to a linked, null terminated list of
562 devices and inodes of parent directories of SRC_PATH.
563 Return 0 if successful, 1 if an error occurs. */
565 static int
566 copy (const char *src_path, const char *dst_path, int new_dst, dev_t device,
567 struct dir_list *ancestors)
569 struct stat src_sb;
570 struct stat dst_sb;
571 int src_mode;
572 int src_type;
573 char *earlier_file;
574 char *dst_backup = NULL;
575 int fix_mode = 0;
577 if ((*xstat) (src_path, &src_sb))
579 error (0, errno, "%s", src_path);
580 return 1;
583 /* Are we crossing a file system boundary? */
584 if (flag_one_file_system && device != 0 && device != src_sb.st_dev)
585 return 0;
587 /* We wouldn't insert a node unless nlink > 1, except that we need to
588 find created files so as to not copy infinitely if a directory is
589 copied into itself. */
591 earlier_file = remember_copied (dst_path, src_sb.st_ino, src_sb.st_dev);
593 /* Did we just create this file? */
595 if (earlier_file == &new_file)
596 return 0;
598 src_mode = src_sb.st_mode;
599 src_type = src_sb.st_mode;
601 if (S_ISDIR (src_type) && !flag_recursive)
603 error (0, 0, _("%s: omitting directory"), src_path);
604 return 1;
607 if (!new_dst)
609 if ((*xstat) (dst_path, &dst_sb))
611 if (errno != ENOENT)
613 error (0, errno, "%s", dst_path);
614 return 1;
616 else
617 new_dst = 1;
619 else
621 /* The file exists already. */
623 if (src_sb.st_ino == dst_sb.st_ino && src_sb.st_dev == dst_sb.st_dev)
625 if (flag_hard_link)
626 return 0;
628 error (0, 0, _("`%s' and `%s' are the same file"),
629 src_path, dst_path);
630 return 1;
633 if (!S_ISDIR (src_type))
635 if (S_ISDIR (dst_sb.st_mode))
637 error (0, 0,
638 _("%s: cannot overwrite directory with non-directory"),
639 dst_path);
640 return 1;
643 if (flag_update && src_sb.st_mtime <= dst_sb.st_mtime)
644 return 0;
647 if (S_ISREG (src_type) && !flag_force)
649 if (flag_interactive)
651 if (euidaccess (dst_path, W_OK) != 0)
652 fprintf (stderr,
653 _("%s: overwrite `%s', overriding mode %04o? "),
654 program_name, dst_path,
655 (unsigned int) (dst_sb.st_mode & 07777));
656 else
657 fprintf (stderr, _("%s: overwrite `%s'? "),
658 program_name, dst_path);
659 if (!yesno ())
660 return 0;
664 if (backup_type != none && !S_ISDIR (dst_sb.st_mode))
666 char *tmp_backup = find_backup_file_name (dst_path);
667 if (tmp_backup == NULL)
668 error (1, 0, _("virtual memory exhausted"));
670 /* Detect (and fail) when creating the backup file would
671 destroy the source file. Before, running the commands
672 cd /tmp; rm -f a a~; : > a; echo A > a~; cp -b -V simple a~ a
673 would leave two zero-length files: a and a~. */
674 if (STREQ (tmp_backup, src_path))
676 error (0, 0,
677 _("backing up `%s' would destroy source; `%s' not copied"),
678 dst_path, src_path);
679 return 1;
682 dst_backup = (char *) alloca (strlen (tmp_backup) + 1);
683 strcpy (dst_backup, tmp_backup);
684 free (tmp_backup);
685 if (rename (dst_path, dst_backup))
687 if (errno != ENOENT)
689 error (0, errno, _("cannot backup `%s'"), dst_path);
690 return 1;
692 else
693 dst_backup = NULL;
695 new_dst = 1;
697 else if (flag_force)
699 if (S_ISDIR (dst_sb.st_mode))
701 /* Temporarily change mode to allow overwriting. */
702 if (euidaccess (dst_path, W_OK | X_OK) != 0)
704 if (chmod (dst_path, 0700))
706 error (0, errno, "%s", dst_path);
707 return 1;
709 else
710 fix_mode = 1;
713 else
715 if (unlink (dst_path) && errno != ENOENT)
717 error (0, errno, _("cannot remove old link to `%s'"),
718 dst_path);
719 return 1;
721 new_dst = 1;
727 /* If the source is a directory, we don't always create the destination
728 directory. So --verbose should not announce anything until we're
729 sure we'll create a directory. */
730 if (flag_verbose && !S_ISDIR (src_type))
731 printf ("%s -> %s\n", src_path, dst_path);
733 /* Did we copy this inode somewhere else (in this command line argument)
734 and therefore this is a second hard link to the inode? */
736 if (!flag_dereference && src_sb.st_nlink > 1 && earlier_file)
738 if (link (earlier_file, dst_path))
740 error (0, errno, "%s", dst_path);
741 goto un_backup;
743 return 0;
746 if (S_ISDIR (src_type))
748 struct dir_list *dir;
750 /* If this directory has been copied before during the
751 recursion, there is a symbolic link to an ancestor
752 directory of the symbolic link. It is impossible to
753 continue to copy this, unless we've got an infinite disk. */
755 if (is_ancestor (&src_sb, ancestors))
757 error (0, 0, _("%s: cannot copy cyclic symbolic link"), src_path);
758 goto un_backup;
761 /* Insert the current directory in the list of parents. */
763 dir = (struct dir_list *) alloca (sizeof (struct dir_list));
764 dir->parent = ancestors;
765 dir->ino = src_sb.st_ino;
766 dir->dev = src_sb.st_dev;
768 if (new_dst || !S_ISDIR (dst_sb.st_mode))
770 /* Create the new directory writable and searchable, so
771 we can create new entries in it. */
773 if (mkdir (dst_path, (src_mode & umask_kill) | 0700))
775 error (0, errno, _("cannot create directory `%s'"), dst_path);
776 goto un_backup;
779 /* Insert the created directory's inode and device
780 numbers into the search structure, so that we can
781 avoid copying it again. */
783 if (remember_created (dst_path))
784 goto un_backup;
786 if (flag_verbose)
787 printf ("%s -> %s\n", src_path, dst_path);
790 /* Copy the contents of the directory. */
792 if (copy_dir (src_path, dst_path, new_dst, &src_sb, dir))
793 return 1;
795 #ifdef S_ISLNK
796 else if (flag_symbolic_link)
798 if (*src_path == '/'
799 || (!strncmp (dst_path, "./", 2) && strchr (dst_path + 2, '/') == 0)
800 || strchr (dst_path, '/') == 0)
802 if (symlink (src_path, dst_path))
804 error (0, errno, "%s", dst_path);
805 goto un_backup;
807 return 0;
809 else
811 error (0, 0,
812 _("%s: can make relative symbolic links only in current directory"),
813 dst_path);
814 goto un_backup;
817 #endif
818 else if (flag_hard_link)
820 if (link (src_path, dst_path))
822 error (0, errno, _("cannot create link `%s'"), dst_path);
823 goto un_backup;
825 return 0;
827 else if (S_ISREG (src_type)
828 || (flag_copy_as_regular && !S_ISDIR (src_type)
829 #ifdef S_ISLNK
830 && !S_ISLNK (src_type)
831 #endif
834 if (copy_reg (src_path, dst_path))
835 goto un_backup;
837 else
838 #ifdef S_ISFIFO
839 if (S_ISFIFO (src_type))
841 if (mkfifo (dst_path, src_mode & umask_kill))
843 error (0, errno, _("cannot create fifo `%s'"), dst_path);
844 goto un_backup;
847 else
848 #endif
849 if (S_ISBLK (src_type) || S_ISCHR (src_type)
850 #ifdef S_ISSOCK
851 || S_ISSOCK (src_type)
852 #endif
855 if (mknod (dst_path, src_mode & umask_kill, src_sb.st_rdev))
857 error (0, errno, _("cannot create special file `%s'"), dst_path);
858 goto un_backup;
861 else
862 #ifdef S_ISLNK
863 if (S_ISLNK (src_type))
865 char *link_val;
866 int link_size;
868 link_val = (char *) alloca (PATH_MAX + 2);
869 link_size = readlink (src_path, link_val, PATH_MAX + 1);
870 if (link_size < 0)
872 error (0, errno, _("cannot read symbolic link `%s'"), src_path);
873 goto un_backup;
875 link_val[link_size] = '\0';
877 if (symlink (link_val, dst_path))
879 error (0, errno, _("cannot create symbolic link `%s'"), dst_path);
880 goto un_backup;
882 return 0;
884 else
885 #endif
887 error (0, 0, _("%s: unknown file type"), src_path);
888 goto un_backup;
891 /* Adjust the times (and if possible, ownership) for the copy.
892 chown turns off set[ug]id bits for non-root,
893 so do the chmod last. */
895 if (flag_preserve)
897 struct utimbuf utb;
899 utb.actime = src_sb.st_atime;
900 utb.modtime = src_sb.st_mtime;
902 if (utime (dst_path, &utb))
904 error (0, errno, "%s", dst_path);
905 return 1;
908 /* If non-root uses -p, it's ok if we can't preserve ownership.
909 But root probably wants to know, e.g. if NFS disallows it. */
910 if (chown (dst_path,
911 (myeuid == 0 ? src_sb.st_uid : myeuid),
912 src_sb.st_gid)
913 && (errno != EPERM || myeuid == 0))
915 error (0, errno, "%s", dst_path);
916 return 1;
920 if ((flag_preserve || new_dst)
921 && (flag_copy_as_regular || S_ISREG (src_type) || S_ISDIR (src_type)))
923 if (chmod (dst_path, src_mode & umask_kill))
925 error (0, errno, "%s", dst_path);
926 return 1;
929 else if (fix_mode)
931 /* Reset the temporarily changed mode. */
932 if (chmod (dst_path, dst_sb.st_mode))
934 error (0, errno, "%s", dst_path);
935 return 1;
939 return 0;
941 un_backup:
942 if (dst_backup)
944 if (rename (dst_backup, dst_path))
945 error (0, errno, _("cannot un-backup `%s'"), dst_path);
947 return 1;
950 /* Ensure that the parent directory of CONST_DIRPATH exists, for
951 the --parents option.
953 SRC_OFFSET is the index in CONST_DIRPATH (which is a destination
954 path) of the beginning of the source directory name.
955 Create any leading directories that don't already exist,
956 giving them permissions MODE.
957 If VERBOSE_FMT_STRING is nonzero, use it as a printf format
958 string for printing a message after successfully making a directory.
959 The format should take two string arguments: the names of the
960 source and destination directories.
961 Creates a linked list of attributes of intermediate directories,
962 *ATTR_LIST, for re_protect to use after calling copy.
963 Sets *NEW_DST to 1 if this function creates parent of CONST_DIRPATH.
965 Return 0 if parent of CONST_DIRPATH exists as a directory with the proper
966 permissions when done, otherwise 1. */
968 static int
969 make_path_private (const char *const_dirpath, int src_offset, int mode,
970 const char *verbose_fmt_string, struct dir_attr **attr_list,
971 int *new_dst)
973 struct stat stats;
974 char *dirpath; /* A copy of CONST_DIRPATH we can change. */
975 char *src; /* Source name in `dirpath'. */
976 char *tmp_dst_dirname; /* Leading path of `dirpath', malloc. */
977 char *dst_dirname; /* Leading path of `dirpath', alloca. */
979 dirpath = (char *) alloca (strlen (const_dirpath) + 1);
980 strcpy (dirpath, const_dirpath);
982 src = dirpath + src_offset;
984 tmp_dst_dirname = dirname (dirpath);
985 dst_dirname = (char *) alloca (strlen (tmp_dst_dirname) + 1);
986 strcpy (dst_dirname, tmp_dst_dirname);
987 free (tmp_dst_dirname);
989 *attr_list = NULL;
991 if ((*xstat) (dst_dirname, &stats))
993 /* Parent of CONST_DIRNAME does not exist.
994 Make all missing intermediate directories. */
995 char *slash;
997 slash = src;
998 while (*slash == '/')
999 slash++;
1000 while ((slash = strchr (slash, '/')))
1002 /* Add this directory to the list of directories whose modes need
1003 fixing later. */
1004 struct dir_attr *new =
1005 (struct dir_attr *) xmalloc (sizeof (struct dir_attr));
1006 new->slash_offset = slash - dirpath;
1007 new->next = *attr_list;
1008 *attr_list = new;
1010 *slash = '\0';
1011 if ((*xstat) (dirpath, &stats))
1013 /* This element of the path does not exist. We must set
1014 *new_dst and new->is_new_dir inside this loop because,
1015 for example, in the command `cp --parents ../a/../b/c e_dir',
1016 make_path_private creates only e_dir/../a if ./b already
1017 exists. */
1018 *new_dst = 1;
1019 new->is_new_dir = 1;
1020 if (mkdir (dirpath, mode))
1022 error (0, errno, _("cannot make directory `%s'"), dirpath);
1023 return 1;
1025 else
1027 if (verbose_fmt_string != NULL)
1028 printf (verbose_fmt_string, src, dirpath);
1031 else if (!S_ISDIR (stats.st_mode))
1033 error (0, 0, _("`%s' exists but is not a directory"), dirpath);
1034 return 1;
1036 else
1038 new->is_new_dir = 0;
1039 *new_dst = 0;
1041 *slash++ = '/';
1043 /* Avoid unnecessary calls to `stat' when given
1044 pathnames containing multiple adjacent slashes. */
1045 while (*slash == '/')
1046 slash++;
1050 /* We get here if the parent of `dirpath' already exists. */
1052 else if (!S_ISDIR (stats.st_mode))
1054 error (0, 0, _("`%s' exists but is not a directory"), dst_dirname);
1055 return 1;
1057 else
1059 *new_dst = 0;
1061 return 0;
1064 /* Ensure that the parent directories of CONST_DST_PATH have the
1065 correct protections, for the --parents option. This is done
1066 after all copying has been completed, to allow permissions
1067 that don't include user write/execute.
1069 SRC_OFFSET is the index in CONST_DST_PATH of the beginning of the
1070 source directory name.
1072 ATTR_LIST is a null-terminated linked list of structures that
1073 indicates the end of the filename of each intermediate directory
1074 in CONST_DST_PATH that may need to have its attributes changed.
1075 The command `cp --parents --preserve a/b/c d/e_dir' changes the
1076 attributes of the directories d/e_dir/a and d/e_dir/a/b to match
1077 the corresponding source directories regardless of whether they
1078 existed before the `cp' command was given.
1080 Return 0 if the parent of CONST_DST_PATH and any intermediate
1081 directories specified by ATTR_LIST have the proper permissions
1082 when done, otherwise 1. */
1084 static int
1085 re_protect (const char *const_dst_path, int src_offset,
1086 struct dir_attr *attr_list)
1088 struct dir_attr *p;
1089 char *dst_path; /* A copy of CONST_DST_PATH we can change. */
1090 char *src_path; /* The source name in `dst_path'. */
1092 dst_path = (char *) alloca (strlen (const_dst_path) + 1);
1093 strcpy (dst_path, const_dst_path);
1094 src_path = dst_path + src_offset;
1096 for (p = attr_list; p; p = p->next)
1098 struct stat src_sb;
1100 dst_path[p->slash_offset] = '\0';
1102 if ((*xstat) (src_path, &src_sb))
1104 error (0, errno, "%s", src_path);
1105 return 1;
1108 /* Adjust the times (and if possible, ownership) for the copy.
1109 chown turns off set[ug]id bits for non-root,
1110 so do the chmod last. */
1112 if (flag_preserve)
1114 struct utimbuf utb;
1116 utb.actime = src_sb.st_atime;
1117 utb.modtime = src_sb.st_mtime;
1119 if (utime (dst_path, &utb))
1121 error (0, errno, "%s", dst_path);
1122 return 1;
1125 /* If non-root uses -p, it's ok if we can't preserve ownership.
1126 But root probably wants to know, e.g. if NFS disallows it. */
1127 if (chown (dst_path, src_sb.st_uid, src_sb.st_gid)
1128 && (errno != EPERM || myeuid == 0))
1130 error (0, errno, "%s", dst_path);
1131 return 1;
1135 if (flag_preserve || p->is_new_dir)
1137 if (chmod (dst_path, src_sb.st_mode & umask_kill))
1139 error (0, errno, "%s", dst_path);
1140 return 1;
1144 dst_path[p->slash_offset] = '/';
1146 return 0;
1149 /* Read the contents of the directory SRC_PATH_IN, and recursively
1150 copy the contents to DST_PATH_IN. NEW_DST is nonzero if
1151 DST_PATH_IN is a directory that was created previously in the
1152 recursion. SRC_SB and ANCESTORS describe SRC_PATH_IN.
1153 Return 0 if successful, -1 if an error occurs. */
1155 static int
1156 copy_dir (const char *src_path_in, const char *dst_path_in, int new_dst,
1157 const struct stat *src_sb, struct dir_list *ancestors)
1159 char *name_space;
1160 char *namep;
1161 char *src_path;
1162 char *dst_path;
1163 int ret = 0;
1165 errno = 0;
1166 name_space = savedir (src_path_in, src_sb->st_size);
1167 if (name_space == 0)
1169 if (errno)
1171 error (0, errno, "%s", src_path_in);
1172 return -1;
1174 else
1175 error (1, 0, _("virtual memory exhausted"));
1178 namep = name_space;
1179 while (*namep != '\0')
1181 int fn_length = strlen (namep) + 1;
1183 dst_path = xmalloc (strlen (dst_path_in) + fn_length + 1);
1184 src_path = xmalloc (strlen (src_path_in) + fn_length + 1);
1186 stpcpy (stpcpy (stpcpy (src_path, src_path_in), "/"), namep);
1187 stpcpy (stpcpy (stpcpy (dst_path, dst_path_in), "/"), namep);
1189 ret |= copy (src_path, dst_path, new_dst, src_sb->st_dev, ancestors);
1191 /* Free the memory for `src_path'. The memory for `dst_path'
1192 cannot be deallocated, since it is used to create multiple
1193 hard links. */
1195 free (src_path);
1197 namep += fn_length;
1199 free (name_space);
1200 return -ret;
1203 /* Copy a regular file from SRC_PATH to DST_PATH.
1204 If the source file contains holes, copies holes and blocks of zeros
1205 in the source file as holes in the destination file.
1206 (Holes are read as zeroes by the `read' system call.)
1207 Return 0 if successful, -1 if an error occurred. */
1209 static int
1210 copy_reg (const char *src_path, const char *dst_path)
1212 char *buf;
1213 int buf_size;
1214 int dest_desc;
1215 int source_desc;
1216 int n_read;
1217 struct stat sb;
1218 char *cp;
1219 int *ip;
1220 int return_val = 0;
1221 long n_read_total = 0;
1222 int last_write_made_hole = 0;
1223 int make_holes = (flag_sparse == SPARSE_ALWAYS);
1225 source_desc = open (src_path, O_RDONLY);
1226 if (source_desc < 0)
1228 error (0, errno, "%s", src_path);
1229 return -1;
1232 /* Create the new regular file with small permissions initially,
1233 to not create a security hole. */
1235 dest_desc = open (dst_path, O_WRONLY | O_CREAT | O_TRUNC, 0600);
1236 if (dest_desc < 0)
1238 error (0, errno, _("cannot create regular file `%s'"), dst_path);
1239 return_val = -1;
1240 goto ret2;
1243 /* Find out the optimal buffer size. */
1245 if (fstat (dest_desc, &sb))
1247 error (0, errno, "%s", dst_path);
1248 return_val = -1;
1249 goto ret;
1252 buf_size = ST_BLKSIZE (sb);
1254 #ifdef HAVE_ST_BLOCKS
1255 if (flag_sparse == SPARSE_AUTO && S_ISREG (sb.st_mode))
1257 /* Use a heuristic to determine whether SRC_PATH contains any
1258 sparse blocks. */
1260 if (fstat (source_desc, &sb))
1262 error (0, errno, "%s", src_path);
1263 return_val = -1;
1264 goto ret;
1267 /* If the file has fewer blocks than would normally
1268 be needed for a file of its size, then
1269 at least one of the blocks in the file is a hole. */
1270 if (S_ISREG (sb.st_mode)
1271 && (size_t) (sb.st_size / 512) > (size_t) ST_NBLOCKS (sb))
1272 make_holes = 1;
1274 #endif
1276 /* Make a buffer with space for a sentinel at the end. */
1278 buf = (char *) alloca (buf_size + sizeof (int));
1280 for (;;)
1282 n_read = read (source_desc, buf, buf_size);
1283 if (n_read < 0)
1285 #ifdef EINTR
1286 if (errno == EINTR)
1287 continue;
1288 #endif
1289 error (0, errno, "%s", src_path);
1290 return_val = -1;
1291 goto ret;
1293 if (n_read == 0)
1294 break;
1296 n_read_total += n_read;
1298 ip = 0;
1299 if (make_holes)
1301 buf[n_read] = 1; /* Sentinel to stop loop. */
1303 /* Find first nonzero *word*, or the word with the sentinel. */
1305 ip = (int *) buf;
1306 while (*ip++ == 0)
1309 /* Find the first nonzero *byte*, or the sentinel. */
1311 cp = (char *) (ip - 1);
1312 while (*cp++ == 0)
1315 /* If we found the sentinel, the whole input block was zero,
1316 and we can make a hole. */
1318 if (cp > buf + n_read)
1320 /* Make a hole. */
1321 if (lseek (dest_desc, (off_t) n_read, SEEK_CUR) < 0L)
1323 error (0, errno, "%s", dst_path);
1324 return_val = -1;
1325 goto ret;
1327 last_write_made_hole = 1;
1329 else
1330 /* Clear to indicate that a normal write is needed. */
1331 ip = 0;
1333 if (ip == 0)
1335 if (full_write (dest_desc, buf, n_read) < 0)
1337 error (0, errno, "%s", dst_path);
1338 return_val = -1;
1339 goto ret;
1341 last_write_made_hole = 0;
1345 /* If the file ends with a `hole', something needs to be written at
1346 the end. Otherwise the kernel would truncate the file at the end
1347 of the last write operation. */
1349 if (last_write_made_hole)
1351 #ifdef HAVE_FTRUNCATE
1352 /* Write a null character and truncate it again. */
1353 if (full_write (dest_desc, "", 1) < 0
1354 || ftruncate (dest_desc, n_read_total) < 0)
1355 #else
1356 /* Seek backwards one character and write a null. */
1357 if (lseek (dest_desc, (off_t) -1, SEEK_CUR) < 0L
1358 || full_write (dest_desc, "", 1) < 0)
1359 #endif
1361 error (0, errno, "%s", dst_path);
1362 return_val = -1;
1366 ret:
1367 if (close (dest_desc) < 0)
1369 error (0, errno, "%s", dst_path);
1370 return_val = -1;
1372 ret2:
1373 if (close (source_desc) < 0)
1375 error (0, errno, "%s", src_path);
1376 return_val = -1;
1379 return return_val;