.
[coreutils.git] / src / cp.c
blob93dce2c1635393ebec0a0337ed9960d1403c0881
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"
34 #include "path-concat.h"
36 #ifndef _POSIX_VERSION
37 uid_t geteuid ();
38 #endif
40 /* On Linux (from slackware-1.2.13 to 2.0.2?) there is no lchown function.
41 To change ownership of symlinks, you must run chown with an effective
42 UID of 0. */
43 #ifdef __linux__
44 # define ROOT_CHOWN_AFFECTS_SYMLINKS
45 #endif
47 #define DO_CHOWN(Chown, File, New_uid, New_gid) \
48 (Chown ((File), (myeuid == 0 ? (New_uid) : myeuid), (New_gid)) \
49 /* If non-root uses -p, it's ok if we can't preserve ownership. \
50 But root probably wants to know, e.g. if NFS disallows it. */ \
51 && (errno != EPERM || myeuid == 0))
53 /* Used by do_copy, make_path_private, and re_protect
54 to keep a list of leading directories whose protections
55 need to be fixed after copying. */
56 struct dir_attr
58 int is_new_dir;
59 int slash_offset;
60 struct dir_attr *next;
63 /* Control creation of sparse files (files with holes). */
64 enum Sparse_type
66 /* Never create holes in DEST. */
67 SPARSE_NEVER,
69 /* This is the default. Use a crude (and sometimes inaccurate)
70 heuristic to determine if SOURCE has holes. If so, try to create
71 holes in DEST. */
72 SPARSE_AUTO,
74 /* For every sufficiently long sequence of bytes in SOURCE, try to
75 create a corresponding hole in DEST. There is a performance penalty
76 here because CP has to search for holes in SRC. But if the holes are
77 big enough, that penalty can be offset by the decrease in the amount
78 of data written to disk. */
79 SPARSE_ALWAYS
82 int stat ();
83 int lstat ();
85 char *dirname ();
86 char *xstrdup ();
87 enum backup_type get_version ();
88 int euidaccess ();
89 int full_write ();
91 static int do_copy __P ((int argc, char **argv));
92 static int copy __P ((const char *src_path, const char *dst_path, int new_dst,
93 dev_t device, struct dir_list *ancestors));
94 static int copy_dir __P ((const char *src_path_in, const char *dst_path_in,
95 int new_dst, const struct stat *src_sb,
96 struct dir_list *ancestors));
97 static int make_path_private __P ((const char *const_dirpath, int src_offset,
98 int mode, const char *verbose_fmt_string,
99 struct dir_attr **attr_list, int *new_dst));
100 static int copy_reg __P ((const char *src_path, const char *dst_path));
101 static int re_protect __P ((const char *const_dst_path, int src_offset,
102 struct dir_attr *attr_list));
104 /* Initial number of entries in each hash table entry's table of inodes. */
105 #define INITIAL_HASH_MODULE 100
107 /* Initial number of entries in the inode hash table. */
108 #define INITIAL_ENTRY_TAB_SIZE 70
110 /* The invocation name of this program. */
111 char *program_name;
113 /* A pointer to either lstat or stat, depending on
114 whether dereferencing of symlinks is done. */
115 static int (*xstat) ();
117 /* If nonzero, copy all files except (directories and, if not dereferencing
118 them, symbolic links,) as if they were regular files. */
119 static int flag_copy_as_regular = 1;
121 /* If nonzero, dereference symbolic links (copy the files they point to). */
122 static int flag_dereference = 1;
124 /* If nonzero, remove existing destination nondirectories. */
125 static int flag_force = 0;
127 /* If nonzero, create hard links instead of copying files.
128 Create destination directories as usual. */
129 static int flag_hard_link = 0;
131 /* If nonzero, query before overwriting existing destinations
132 with regular files. */
133 static int flag_interactive = 0;
135 /* If nonzero, the command "cp x/e_file e_dir" uses "e_dir/x/e_file"
136 as its destination instead of the usual "e_dir/e_file." */
137 static int flag_path = 0;
139 /* If nonzero, give the copies the original files' permissions,
140 ownership, and timestamps. */
141 static int flag_preserve = 0;
143 /* If nonzero, copy directories recursively and copy special files
144 as themselves rather than copying their contents. */
145 static int flag_recursive = 0;
147 /* If nonzero, create symbolic links instead of copying files.
148 Create destination directories as usual. */
149 static int flag_symbolic_link = 0;
151 /* If nonzero, when copying recursively, skip any subdirectories that are
152 on different filesystems from the one we started on. */
153 static int flag_one_file_system = 0;
155 /* If nonzero, do not copy a nondirectory that has an existing destination
156 with the same or newer modification time. */
157 static int flag_update = 0;
159 /* If nonzero, display the names of the files before copying them. */
160 static int flag_verbose = 0;
162 static char const *const sparse_type_string[] =
164 "never", "auto", "always", 0
167 static enum Sparse_type const sparse_type[] =
169 SPARSE_NEVER, SPARSE_AUTO, SPARSE_ALWAYS
172 /* Control creation of sparse files. */
173 static int flag_sparse = SPARSE_AUTO;
175 /* The error code to return to the system. */
176 static int exit_status = 0;
178 /* The bits to preserve in created files' modes. */
179 static int umask_kill;
181 /* This process's effective user ID. */
182 static uid_t myeuid;
184 /* If nonzero, display usage information and exit. */
185 static int show_help;
187 /* If nonzero, print the version on standard output and exit. */
188 static int show_version;
190 static struct option const long_opts[] =
192 {"archive", no_argument, NULL, 'a'},
193 {"backup", no_argument, NULL, 'b'},
194 {"force", no_argument, NULL, 'f'},
195 {"sparse", required_argument, NULL, 2},
196 {"interactive", no_argument, NULL, 'i'},
197 {"link", no_argument, NULL, 'l'},
198 {"no-dereference", no_argument, &flag_dereference, 0},
199 {"one-file-system", no_argument, &flag_one_file_system, 1},
200 {"parents", no_argument, &flag_path, 1},
201 {"path", no_argument, &flag_path, 1},
202 {"preserve", no_argument, &flag_preserve, 1},
203 {"recursive", no_argument, NULL, 'R'},
204 {"suffix", required_argument, NULL, 'S'},
205 {"symbolic-link", no_argument, NULL, 's'},
206 {"update", no_argument, &flag_update, 1},
207 {"verbose", no_argument, &flag_verbose, 1},
208 {"version-control", required_argument, NULL, 'V'},
209 {"help", no_argument, &show_help, 1},
210 {"version", no_argument, &show_version, 1},
211 {NULL, 0, NULL, 0}
215 main (int argc, char **argv)
217 int c;
218 int make_backups = 0;
219 char *version;
221 program_name = argv[0];
222 setlocale (LC_ALL, "");
223 bindtextdomain (PACKAGE, LOCALEDIR);
224 textdomain (PACKAGE);
226 myeuid = geteuid ();
228 version = getenv ("SIMPLE_BACKUP_SUFFIX");
229 if (version)
230 simple_backup_suffix = version;
231 version = getenv ("VERSION_CONTROL");
233 /* Find out the current file creation mask, to knock the right bits
234 when using chmod. The creation mask is set to to be liberal, so
235 that created directories can be written, even if it would not
236 have been allowed with the mask this process was started with. */
238 umask_kill = 0777777 ^ umask (0);
240 while ((c = getopt_long (argc, argv, "abdfilprsuvxPRS:V:", long_opts,
241 (int *) 0)) != EOF)
243 switch (c)
245 case 0:
246 break;
248 case 2:
250 int i;
252 /* --sparse={never,auto,always} */
253 i = argmatch (optarg, sparse_type_string);
254 if (i < 0)
256 invalid_arg (_("sparse type"), optarg, i);
257 usage (1);
259 flag_sparse = sparse_type[i];
261 break;
263 case 'a': /* Like -dpR. */
264 flag_dereference = 0;
265 flag_preserve = 1;
266 flag_recursive = 1;
267 flag_copy_as_regular = 0;
268 break;
270 case 'b':
271 make_backups = 1;
272 break;
274 case 'd':
275 flag_dereference = 0;
276 break;
278 case 'f':
279 flag_force = 1;
280 flag_interactive = 0;
281 break;
283 case 'i':
284 flag_force = 0;
285 flag_interactive = 1;
286 break;
288 case 'l':
289 flag_hard_link = 1;
290 break;
292 case 'p':
293 flag_preserve = 1;
294 break;
296 case 'P':
297 flag_path = 1;
298 break;
300 case 'r':
301 flag_recursive = 1;
302 flag_copy_as_regular = 1;
303 break;
305 case 'R':
306 flag_recursive = 1;
307 flag_copy_as_regular = 0;
308 break;
310 case 's':
311 #ifdef S_ISLNK
312 flag_symbolic_link = 1;
313 #else
314 error (1, 0, _("symbolic links are not supported on this system"));
315 #endif
316 break;
318 case 'u':
319 flag_update = 1;
320 break;
322 case 'v':
323 flag_verbose = 1;
324 break;
326 case 'x':
327 flag_one_file_system = 1;
328 break;
330 case 'S':
331 simple_backup_suffix = optarg;
332 break;
334 case 'V':
335 version = optarg;
336 break;
338 default:
339 usage (1);
343 if (show_version)
345 printf ("cp (%s) %s\n", GNU_PACKAGE, VERSION);
346 exit (0);
349 if (show_help)
350 usage (0);
352 if (flag_hard_link && flag_symbolic_link)
354 error (0, 0, _("cannot make both hard and symbolic links"));
355 usage (1);
358 if (make_backups)
359 backup_type = get_version (version);
361 if (flag_preserve == 1)
362 umask_kill = 0777777;
364 /* The key difference between -d (--no-dereference) and not is the version
365 of `stat' to call. */
367 if (flag_dereference)
368 xstat = stat;
369 else
370 xstat = lstat;
372 /* Allocate space for remembering copied and created files. */
374 hash_init (INITIAL_HASH_MODULE, INITIAL_ENTRY_TAB_SIZE);
376 exit_status |= do_copy (argc, argv);
378 exit (exit_status);
381 /* Scan the arguments, and copy each by calling copy.
382 Return 0 if successful, 1 if any errors occur. */
384 static int
385 do_copy (int argc, char **argv)
387 char *dest;
388 struct stat sb;
389 int new_dst = 0;
390 int ret = 0;
392 if (optind >= argc)
394 error (0, 0, _("missing file arguments"));
395 usage (1);
397 if (optind >= argc - 1)
399 error (0, 0, _("missing destination file"));
400 usage (1);
403 dest = argv[argc - 1];
405 if (lstat (dest, &sb))
407 if (errno != ENOENT)
409 error (0, errno, "%s", dest);
410 return 1;
412 else
413 new_dst = 1;
415 else
417 struct stat sbx;
419 /* If `dest' is not a symlink to a nonexistent file, use
420 the results of stat instead of lstat, so we can copy files
421 into symlinks to directories. */
422 if (stat (dest, &sbx) == 0)
423 sb = sbx;
426 if (!new_dst && S_ISDIR (sb.st_mode))
428 /* cp file1...filen edir
429 Copy the files `file1' through `filen'
430 to the existing directory `edir'. */
432 for (;;)
434 char *arg;
435 char *ap;
436 char *dst_path;
437 int parent_exists = 1; /* True if dirname (dst_path) exists. */
438 struct dir_attr *attr_list;
439 char *arg_in_concat = NULL;
441 arg = argv[optind];
443 strip_trailing_slashes (arg);
445 if (flag_path)
447 /* Append all of `arg' to `dest'. */
448 dst_path = path_concat (dest, arg, &arg_in_concat);
449 if (dst_path == NULL)
450 error (1, 0, _("virtual memory exhausted"));
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 arg_in_concat - dst_path,
457 0700,
458 (flag_verbose
459 ? "%s -> %s\n" : NULL),
460 &attr_list, &new_dst);
462 else
464 /* Append the last component of `arg' to `dest'. */
466 ap = basename (arg);
467 /* For `cp -R source/.. dest', don't copy into `dest/..'. */
468 dst_path = (STREQ (ap, "..")
469 ? xstrdup (dest)
470 : path_concat (dest, ap, NULL));
473 if (!parent_exists)
475 /* make_path_private failed, so don't even attempt the copy. */
476 ret = 1;
478 else
480 ret |= copy (arg, dst_path, new_dst, 0, (struct dir_list *) 0);
481 forget_all ();
483 if (flag_path)
485 ret |= re_protect (dst_path, arg_in_concat - dst_path,
486 attr_list);
490 free (dst_path);
491 ++optind;
492 if (optind == argc - 1)
493 break;
495 return ret;
497 else if (argc - optind == 2)
499 char *new_dest;
500 char *source;
501 struct stat source_stats;
503 if (flag_path)
505 error (0, 0,
506 _("when preserving paths, last argument must be a directory"));
507 usage (1);
510 source = argv[optind];
512 /* When the force and backup options have been specified and
513 the source and destination are the same name for an existing
514 regular file, convert the user's command, e.g.,
515 `cp --force --backup foo foo' to `cp --force foo fooSUFFIX'
516 where SUFFIX is determined by any version control options used. */
518 if (flag_force
519 && backup_type != none
520 && STREQ (source, dest)
521 && !new_dst && S_ISREG (sb.st_mode))
523 new_dest = find_backup_file_name (dest);
524 /* Set backup_type to `none' so that the normal backup
525 mechanism is not used when performing the actual copy.
526 backup_type must be set to `none' only *after* the above
527 call to find_backup_file_name -- that function uses
528 backup_type to determine the suffix it applies. */
529 backup_type = none;
530 if (new_dest == NULL)
531 error (1, 0, _("virtual memory exhausted"));
534 /* When the destination is specified with a trailing slash and the
535 source exists but is not a directory, convert the user's command
536 `cp source dest/' to `cp source dest/basename(source)'. Doing
537 this ensures that the command `cp non-directory file/' will now
538 fail rather than performing the copy. COPY diagnoses the case of
539 `cp directory non-directory'. */
541 else if (dest[strlen (dest) - 1] == '/'
542 && lstat (source, &source_stats) == 0
543 && !S_ISDIR (source_stats.st_mode))
545 char *source_base;
546 char *tmp_source;
548 tmp_source = (char *) alloca (strlen (source) + 1);
549 strcpy (tmp_source, source);
550 strip_trailing_slashes (tmp_source);
551 source_base = basename (tmp_source);
553 new_dest = (char *) alloca (strlen (dest)
554 + strlen (source_base) + 1);
555 stpcpy (stpcpy (new_dest, dest), source_base);
557 else
559 new_dest = dest;
562 return copy (source, new_dest, new_dst, 0, (struct dir_list *) 0);
564 else
566 error (0, 0,
567 _("copying multiple files, but last argument (%s) \
568 is not a directory"),
569 dest);
570 usage (1);
574 /* Copy the file SRC_PATH to the file DST_PATH. The files may be of
575 any type. NEW_DST should be nonzero if the file DST_PATH cannot
576 exist because its parent directory was just created; NEW_DST should
577 be zero if DST_PATH might already exist. DEVICE is the device
578 number of the parent directory, or 0 if the parent of this file is
579 not known. ANCESTORS points to a linked, null terminated list of
580 devices and inodes of parent directories of SRC_PATH.
581 Return 0 if successful, 1 if an error occurs. */
583 static int
584 copy (const char *src_path, const char *dst_path, int new_dst, dev_t device,
585 struct dir_list *ancestors)
587 struct stat src_sb;
588 struct stat dst_sb;
589 int src_mode;
590 int src_type;
591 char *earlier_file;
592 char *dst_backup = NULL;
593 int fix_mode = 0;
595 if ((*xstat) (src_path, &src_sb))
597 error (0, errno, "%s", src_path);
598 return 1;
601 /* Are we crossing a file system boundary? */
602 if (flag_one_file_system && device != 0 && device != src_sb.st_dev)
603 return 0;
605 /* We wouldn't insert a node unless nlink > 1, except that we need to
606 find created files so as to not copy infinitely if a directory is
607 copied into itself. */
609 earlier_file = remember_copied (dst_path, src_sb.st_ino, src_sb.st_dev);
611 /* Did we just create this file? */
613 if (earlier_file == &new_file)
614 return 0;
616 src_mode = src_sb.st_mode;
617 src_type = src_sb.st_mode;
619 if (S_ISDIR (src_type) && !flag_recursive)
621 error (0, 0, _("%s: omitting directory"), src_path);
622 return 1;
625 if (!new_dst)
627 if ((*xstat) (dst_path, &dst_sb))
629 if (errno != ENOENT)
631 error (0, errno, "%s", dst_path);
632 return 1;
634 else
635 new_dst = 1;
637 else
639 /* The file exists already. */
641 if (src_sb.st_ino == dst_sb.st_ino && src_sb.st_dev == dst_sb.st_dev)
643 if (flag_hard_link)
644 return 0;
646 error (0, 0, _("`%s' and `%s' are the same file"),
647 src_path, dst_path);
648 return 1;
651 if (!S_ISDIR (src_type))
653 if (S_ISDIR (dst_sb.st_mode))
655 error (0, 0,
656 _("%s: cannot overwrite directory with non-directory"),
657 dst_path);
658 return 1;
661 if (flag_update && src_sb.st_mtime <= dst_sb.st_mtime)
662 return 0;
665 if (!S_ISDIR (src_type) && !flag_force && flag_interactive)
667 if (euidaccess (dst_path, W_OK) != 0)
669 fprintf (stderr,
670 _("%s: overwrite `%s', overriding mode %04o? "),
671 program_name, dst_path,
672 (unsigned int) (dst_sb.st_mode & 07777));
674 else
676 fprintf (stderr, _("%s: overwrite `%s'? "),
677 program_name, dst_path);
679 if (!yesno ())
680 return 0;
683 if (backup_type != none && !S_ISDIR (dst_sb.st_mode))
685 char *tmp_backup = find_backup_file_name (dst_path);
686 if (tmp_backup == NULL)
687 error (1, 0, _("virtual memory exhausted"));
689 /* Detect (and fail) when creating the backup file would
690 destroy the source file. Before, running the commands
691 cd /tmp; rm -f a a~; : > a; echo A > a~; cp -b -V simple a~ a
692 would leave two zero-length files: a and a~. */
693 if (STREQ (tmp_backup, src_path))
695 error (0, 0,
696 _("backing up `%s' would destroy source; `%s' not copied"),
697 dst_path, src_path);
698 return 1;
701 dst_backup = (char *) alloca (strlen (tmp_backup) + 1);
702 strcpy (dst_backup, tmp_backup);
703 free (tmp_backup);
704 if (rename (dst_path, dst_backup))
706 if (errno != ENOENT)
708 error (0, errno, _("cannot backup `%s'"), dst_path);
709 return 1;
711 else
712 dst_backup = NULL;
714 new_dst = 1;
716 else if (flag_force)
718 if (S_ISDIR (dst_sb.st_mode))
720 /* Temporarily change mode to allow overwriting. */
721 if (euidaccess (dst_path, W_OK | X_OK) != 0)
723 if (chmod (dst_path, 0700))
725 error (0, errno, "%s", dst_path);
726 return 1;
728 else
729 fix_mode = 1;
732 else
734 if (unlink (dst_path) && errno != ENOENT)
736 error (0, errno, _("cannot remove old link to `%s'"),
737 dst_path);
738 return 1;
740 new_dst = 1;
746 /* If the source is a directory, we don't always create the destination
747 directory. So --verbose should not announce anything until we're
748 sure we'll create a directory. */
749 if (flag_verbose && !S_ISDIR (src_type))
750 printf ("%s -> %s\n", src_path, dst_path);
752 /* Did we copy this inode somewhere else (in this command line argument)
753 and therefore this is a second hard link to the inode? */
755 if (!flag_dereference && src_sb.st_nlink > 1 && earlier_file)
757 if (link (earlier_file, dst_path))
759 error (0, errno, "%s", dst_path);
760 goto un_backup;
762 return 0;
765 if (S_ISDIR (src_type))
767 struct dir_list *dir;
769 /* If this directory has been copied before during the
770 recursion, there is a symbolic link to an ancestor
771 directory of the symbolic link. It is impossible to
772 continue to copy this, unless we've got an infinite disk. */
774 if (is_ancestor (&src_sb, ancestors))
776 error (0, 0, _("%s: cannot copy cyclic symbolic link"), src_path);
777 goto un_backup;
780 /* Insert the current directory in the list of parents. */
782 dir = (struct dir_list *) alloca (sizeof (struct dir_list));
783 dir->parent = ancestors;
784 dir->ino = src_sb.st_ino;
785 dir->dev = src_sb.st_dev;
787 if (new_dst || !S_ISDIR (dst_sb.st_mode))
789 /* Create the new directory writable and searchable, so
790 we can create new entries in it. */
792 if (mkdir (dst_path, (src_mode & umask_kill) | 0700))
794 error (0, errno, _("cannot create directory `%s'"), dst_path);
795 goto un_backup;
798 /* Insert the created directory's inode and device
799 numbers into the search structure, so that we can
800 avoid copying it again. */
802 if (remember_created (dst_path))
803 goto un_backup;
805 if (flag_verbose)
806 printf ("%s -> %s\n", src_path, dst_path);
809 /* Copy the contents of the directory. */
811 if (copy_dir (src_path, dst_path, new_dst, &src_sb, dir))
812 return 1;
814 #ifdef S_ISLNK
815 else if (flag_symbolic_link)
817 if (*src_path == '/'
818 || (!strncmp (dst_path, "./", 2) && strchr (dst_path + 2, '/') == 0)
819 || strchr (dst_path, '/') == 0)
821 if (symlink (src_path, dst_path))
823 error (0, errno, "%s", dst_path);
824 goto un_backup;
827 return 0;
829 else
831 error (0, 0,
832 _("%s: can make relative symbolic links only in current directory"),
833 dst_path);
834 goto un_backup;
837 #endif
838 else if (flag_hard_link)
840 if (link (src_path, dst_path))
842 error (0, errno, _("cannot create link `%s'"), dst_path);
843 goto un_backup;
845 return 0;
847 else if (S_ISREG (src_type)
848 || (flag_copy_as_regular && !S_ISDIR (src_type)
849 #ifdef S_ISLNK
850 && !S_ISLNK (src_type)
851 #endif
854 if (copy_reg (src_path, dst_path))
855 goto un_backup;
857 else
858 #ifdef S_ISFIFO
859 if (S_ISFIFO (src_type))
861 if (mkfifo (dst_path, src_mode & umask_kill))
863 error (0, errno, _("cannot create fifo `%s'"), dst_path);
864 goto un_backup;
867 else
868 #endif
869 if (S_ISBLK (src_type) || S_ISCHR (src_type)
870 #ifdef S_ISSOCK
871 || S_ISSOCK (src_type)
872 #endif
875 if (mknod (dst_path, src_mode & umask_kill, src_sb.st_rdev))
877 error (0, errno, _("cannot create special file `%s'"), dst_path);
878 goto un_backup;
881 else
882 #ifdef S_ISLNK
883 if (S_ISLNK (src_type))
885 char *link_val;
886 int link_size;
888 link_val = (char *) alloca (PATH_MAX + 2);
889 link_size = readlink (src_path, link_val, PATH_MAX + 1);
890 if (link_size < 0)
892 error (0, errno, _("cannot read symbolic link `%s'"), src_path);
893 goto un_backup;
895 link_val[link_size] = '\0';
897 if (symlink (link_val, dst_path))
899 error (0, errno, _("cannot create symbolic link `%s'"), dst_path);
900 goto un_backup;
903 if (flag_preserve)
905 /* Preserve the owner and group of the just-`copied'
906 symbolic link, if possible. */
907 #ifdef HAVE_LCHOWN
908 if (DO_CHOWN (lchown, dst_path, src_sb.st_uid, src_sb.st_gid))
910 error (0, errno, "%s", dst_path);
911 goto un_backup;
913 #else
914 # ifdef ROOT_CHOWN_AFFECTS_SYMLINKS
915 if (myeuid == 0)
917 if (DO_CHOWN (chown, dst_path, src_sb.st_uid, src_sb.st_gid))
919 error (0, errno, "%s", dst_path);
920 goto un_backup;
923 else
925 /* FIXME: maybe give a diagnostic: you must be root
926 to preserve ownership and group of symlinks. */
928 # else
929 /* Can't preserve ownership of symlinks.
930 FIXME: maybe give a warning or even error for symlinks
931 in directories with the sticky bit set -- there, not
932 preserving owner/group is a potential security problem. */
933 # endif
934 #endif
937 return 0;
939 else
940 #endif
942 error (0, 0, _("%s: unknown file type"), src_path);
943 goto un_backup;
946 /* Adjust the times (and if possible, ownership) for the copy.
947 chown turns off set[ug]id bits for non-root,
948 so do the chmod last. */
950 if (flag_preserve)
952 struct utimbuf utb;
954 utb.actime = src_sb.st_atime;
955 utb.modtime = src_sb.st_mtime;
957 if (utime (dst_path, &utb))
959 error (0, errno, "%s", dst_path);
960 return 1;
963 if (DO_CHOWN (chown, dst_path, src_sb.st_uid, src_sb.st_gid))
965 error (0, errno, "%s", dst_path);
966 return 1;
970 if ((flag_preserve || new_dst)
971 && (flag_copy_as_regular || S_ISREG (src_type) || S_ISDIR (src_type)))
973 if (chmod (dst_path, src_mode & umask_kill))
975 error (0, errno, "%s", dst_path);
976 return 1;
979 else if (fix_mode)
981 /* Reset the temporarily changed mode. */
982 if (chmod (dst_path, dst_sb.st_mode))
984 error (0, errno, "%s", dst_path);
985 return 1;
989 return 0;
991 un_backup:
992 if (dst_backup)
994 if (rename (dst_backup, dst_path))
995 error (0, errno, _("cannot un-backup `%s'"), dst_path);
997 return 1;
1000 /* Ensure that the parent directory of CONST_DIRPATH exists, for
1001 the --parents option.
1003 SRC_OFFSET is the index in CONST_DIRPATH (which is a destination
1004 path) of the beginning of the source directory name.
1005 Create any leading directories that don't already exist,
1006 giving them permissions MODE.
1007 If VERBOSE_FMT_STRING is nonzero, use it as a printf format
1008 string for printing a message after successfully making a directory.
1009 The format should take two string arguments: the names of the
1010 source and destination directories.
1011 Creates a linked list of attributes of intermediate directories,
1012 *ATTR_LIST, for re_protect to use after calling copy.
1013 Sets *NEW_DST to 1 if this function creates parent of CONST_DIRPATH.
1015 Return 0 if parent of CONST_DIRPATH exists as a directory with the proper
1016 permissions when done, otherwise 1. */
1018 static int
1019 make_path_private (const char *const_dirpath, int src_offset, int mode,
1020 const char *verbose_fmt_string, struct dir_attr **attr_list,
1021 int *new_dst)
1023 struct stat stats;
1024 char *dirpath; /* A copy of CONST_DIRPATH we can change. */
1025 char *src; /* Source name in `dirpath'. */
1026 char *tmp_dst_dirname; /* Leading path of `dirpath', malloc. */
1027 char *dst_dirname; /* Leading path of `dirpath', alloca. */
1029 dirpath = (char *) alloca (strlen (const_dirpath) + 1);
1030 strcpy (dirpath, const_dirpath);
1032 src = dirpath + src_offset;
1034 tmp_dst_dirname = dirname (dirpath);
1035 dst_dirname = (char *) alloca (strlen (tmp_dst_dirname) + 1);
1036 strcpy (dst_dirname, tmp_dst_dirname);
1037 free (tmp_dst_dirname);
1039 *attr_list = NULL;
1041 if ((*xstat) (dst_dirname, &stats))
1043 /* Parent of CONST_DIRNAME does not exist.
1044 Make all missing intermediate directories. */
1045 char *slash;
1047 slash = src;
1048 while (*slash == '/')
1049 slash++;
1050 while ((slash = strchr (slash, '/')))
1052 /* Add this directory to the list of directories whose modes need
1053 fixing later. */
1054 struct dir_attr *new =
1055 (struct dir_attr *) xmalloc (sizeof (struct dir_attr));
1056 new->slash_offset = slash - dirpath;
1057 new->next = *attr_list;
1058 *attr_list = new;
1060 *slash = '\0';
1061 if ((*xstat) (dirpath, &stats))
1063 /* This element of the path does not exist. We must set
1064 *new_dst and new->is_new_dir inside this loop because,
1065 for example, in the command `cp --parents ../a/../b/c e_dir',
1066 make_path_private creates only e_dir/../a if ./b already
1067 exists. */
1068 *new_dst = 1;
1069 new->is_new_dir = 1;
1070 if (mkdir (dirpath, mode))
1072 error (0, errno, _("cannot make directory `%s'"), dirpath);
1073 return 1;
1075 else
1077 if (verbose_fmt_string != NULL)
1078 printf (verbose_fmt_string, src, dirpath);
1081 else if (!S_ISDIR (stats.st_mode))
1083 error (0, 0, _("`%s' exists but is not a directory"), dirpath);
1084 return 1;
1086 else
1088 new->is_new_dir = 0;
1089 *new_dst = 0;
1091 *slash++ = '/';
1093 /* Avoid unnecessary calls to `stat' when given
1094 pathnames containing multiple adjacent slashes. */
1095 while (*slash == '/')
1096 slash++;
1100 /* We get here if the parent of `dirpath' already exists. */
1102 else if (!S_ISDIR (stats.st_mode))
1104 error (0, 0, _("`%s' exists but is not a directory"), dst_dirname);
1105 return 1;
1107 else
1109 *new_dst = 0;
1111 return 0;
1114 /* Ensure that the parent directories of CONST_DST_PATH have the
1115 correct protections, for the --parents option. This is done
1116 after all copying has been completed, to allow permissions
1117 that don't include user write/execute.
1119 SRC_OFFSET is the index in CONST_DST_PATH of the beginning of the
1120 source directory name.
1122 ATTR_LIST is a null-terminated linked list of structures that
1123 indicates the end of the filename of each intermediate directory
1124 in CONST_DST_PATH that may need to have its attributes changed.
1125 The command `cp --parents --preserve a/b/c d/e_dir' changes the
1126 attributes of the directories d/e_dir/a and d/e_dir/a/b to match
1127 the corresponding source directories regardless of whether they
1128 existed before the `cp' command was given.
1130 Return 0 if the parent of CONST_DST_PATH and any intermediate
1131 directories specified by ATTR_LIST have the proper permissions
1132 when done, otherwise 1. */
1134 static int
1135 re_protect (const char *const_dst_path, int src_offset,
1136 struct dir_attr *attr_list)
1138 struct dir_attr *p;
1139 char *dst_path; /* A copy of CONST_DST_PATH we can change. */
1140 char *src_path; /* The source name in `dst_path'. */
1142 dst_path = (char *) alloca (strlen (const_dst_path) + 1);
1143 strcpy (dst_path, const_dst_path);
1144 src_path = dst_path + src_offset;
1146 for (p = attr_list; p; p = p->next)
1148 struct stat src_sb;
1150 dst_path[p->slash_offset] = '\0';
1152 if ((*xstat) (src_path, &src_sb))
1154 error (0, errno, "%s", src_path);
1155 return 1;
1158 /* Adjust the times (and if possible, ownership) for the copy.
1159 chown turns off set[ug]id bits for non-root,
1160 so do the chmod last. */
1162 if (flag_preserve)
1164 struct utimbuf utb;
1166 utb.actime = src_sb.st_atime;
1167 utb.modtime = src_sb.st_mtime;
1169 if (utime (dst_path, &utb))
1171 error (0, errno, "%s", dst_path);
1172 return 1;
1175 /* If non-root uses -p, it's ok if we can't preserve ownership.
1176 But root probably wants to know, e.g. if NFS disallows it. */
1177 if (chown (dst_path, src_sb.st_uid, src_sb.st_gid)
1178 && (errno != EPERM || myeuid == 0))
1180 error (0, errno, "%s", dst_path);
1181 return 1;
1185 if (flag_preserve || p->is_new_dir)
1187 if (chmod (dst_path, src_sb.st_mode & umask_kill))
1189 error (0, errno, "%s", dst_path);
1190 return 1;
1194 dst_path[p->slash_offset] = '/';
1196 return 0;
1199 /* Read the contents of the directory SRC_PATH_IN, and recursively
1200 copy the contents to DST_PATH_IN. NEW_DST is nonzero if
1201 DST_PATH_IN is a directory that was created previously in the
1202 recursion. SRC_SB and ANCESTORS describe SRC_PATH_IN.
1203 Return 0 if successful, -1 if an error occurs. */
1205 static int
1206 copy_dir (const char *src_path_in, const char *dst_path_in, int new_dst,
1207 const struct stat *src_sb, struct dir_list *ancestors)
1209 char *name_space;
1210 char *namep;
1211 char *src_path;
1212 char *dst_path;
1213 int ret = 0;
1215 errno = 0;
1216 name_space = savedir (src_path_in, src_sb->st_size);
1217 if (name_space == 0)
1219 if (errno)
1221 error (0, errno, "%s", src_path_in);
1222 return -1;
1224 else
1225 error (1, 0, _("virtual memory exhausted"));
1228 namep = name_space;
1229 while (*namep != '\0')
1231 int fn_length = strlen (namep) + 1;
1233 dst_path = xmalloc (strlen (dst_path_in) + fn_length + 1);
1234 src_path = xmalloc (strlen (src_path_in) + fn_length + 1);
1236 stpcpy (stpcpy (stpcpy (src_path, src_path_in), "/"), namep);
1237 stpcpy (stpcpy (stpcpy (dst_path, dst_path_in), "/"), namep);
1239 ret |= copy (src_path, dst_path, new_dst, src_sb->st_dev, ancestors);
1241 /* Free the memory for `src_path'. The memory for `dst_path'
1242 cannot be deallocated, since it is used to create multiple
1243 hard links. */
1245 free (src_path);
1247 namep += fn_length;
1249 free (name_space);
1250 return -ret;
1253 /* Copy a regular file from SRC_PATH to DST_PATH.
1254 If the source file contains holes, copies holes and blocks of zeros
1255 in the source file as holes in the destination file.
1256 (Holes are read as zeroes by the `read' system call.)
1257 Return 0 if successful, -1 if an error occurred. */
1259 static int
1260 copy_reg (const char *src_path, const char *dst_path)
1262 char *buf;
1263 int buf_size;
1264 int dest_desc;
1265 int source_desc;
1266 int n_read;
1267 struct stat sb;
1268 char *cp;
1269 int *ip;
1270 int return_val = 0;
1271 long n_read_total = 0;
1272 int last_write_made_hole = 0;
1273 int make_holes = (flag_sparse == SPARSE_ALWAYS);
1275 source_desc = open (src_path, O_RDONLY);
1276 if (source_desc < 0)
1278 error (0, errno, "%s", src_path);
1279 return -1;
1282 /* Create the new regular file with small permissions initially,
1283 to not create a security hole. */
1285 dest_desc = open (dst_path, O_WRONLY | O_CREAT | O_TRUNC, 0600);
1286 if (dest_desc < 0)
1288 error (0, errno, _("cannot create regular file `%s'"), dst_path);
1289 return_val = -1;
1290 goto ret2;
1293 /* Find out the optimal buffer size. */
1295 if (fstat (dest_desc, &sb))
1297 error (0, errno, "%s", dst_path);
1298 return_val = -1;
1299 goto ret;
1302 buf_size = ST_BLKSIZE (sb);
1304 #ifdef HAVE_ST_BLOCKS
1305 if (flag_sparse == SPARSE_AUTO && S_ISREG (sb.st_mode))
1307 /* Use a heuristic to determine whether SRC_PATH contains any
1308 sparse blocks. */
1310 if (fstat (source_desc, &sb))
1312 error (0, errno, "%s", src_path);
1313 return_val = -1;
1314 goto ret;
1317 /* If the file has fewer blocks than would normally
1318 be needed for a file of its size, then
1319 at least one of the blocks in the file is a hole. */
1320 if (S_ISREG (sb.st_mode)
1321 && (size_t) (sb.st_size / 512) > (size_t) ST_NBLOCKS (sb))
1322 make_holes = 1;
1324 #endif
1326 /* Make a buffer with space for a sentinel at the end. */
1328 buf = (char *) alloca (buf_size + sizeof (int));
1330 for (;;)
1332 n_read = read (source_desc, buf, buf_size);
1333 if (n_read < 0)
1335 #ifdef EINTR
1336 if (errno == EINTR)
1337 continue;
1338 #endif
1339 error (0, errno, "%s", src_path);
1340 return_val = -1;
1341 goto ret;
1343 if (n_read == 0)
1344 break;
1346 n_read_total += n_read;
1348 ip = 0;
1349 if (make_holes)
1351 buf[n_read] = 1; /* Sentinel to stop loop. */
1353 /* Find first nonzero *word*, or the word with the sentinel. */
1355 ip = (int *) buf;
1356 while (*ip++ == 0)
1359 /* Find the first nonzero *byte*, or the sentinel. */
1361 cp = (char *) (ip - 1);
1362 while (*cp++ == 0)
1365 /* If we found the sentinel, the whole input block was zero,
1366 and we can make a hole. */
1368 if (cp > buf + n_read)
1370 /* Make a hole. */
1371 if (lseek (dest_desc, (off_t) n_read, SEEK_CUR) < 0L)
1373 error (0, errno, "%s", dst_path);
1374 return_val = -1;
1375 goto ret;
1377 last_write_made_hole = 1;
1379 else
1380 /* Clear to indicate that a normal write is needed. */
1381 ip = 0;
1383 if (ip == 0)
1385 if (full_write (dest_desc, buf, n_read) < 0)
1387 error (0, errno, "%s", dst_path);
1388 return_val = -1;
1389 goto ret;
1391 last_write_made_hole = 0;
1395 /* If the file ends with a `hole', something needs to be written at
1396 the end. Otherwise the kernel would truncate the file at the end
1397 of the last write operation. */
1399 if (last_write_made_hole)
1401 #ifdef HAVE_FTRUNCATE
1402 /* Write a null character and truncate it again. */
1403 if (full_write (dest_desc, "", 1) < 0
1404 || ftruncate (dest_desc, n_read_total) < 0)
1405 #else
1406 /* Seek backwards one character and write a null. */
1407 if (lseek (dest_desc, (off_t) -1, SEEK_CUR) < 0L
1408 || full_write (dest_desc, "", 1) < 0)
1409 #endif
1411 error (0, errno, "%s", dst_path);
1412 return_val = -1;
1416 ret:
1417 if (close (dest_desc) < 0)
1419 error (0, errno, "%s", dst_path);
1420 return_val = -1;
1422 ret2:
1423 if (close (source_desc) < 0)
1425 error (0, errno, "%s", src_path);
1426 return_val = -1;
1429 return return_val;