(add_tabstop): Give correct size when reallocating tab_list buffer.
[platform/upstream/coreutils.git] / src / cp.c
1 /* cp.c  -- file copying (main routines)
2    Copyright (C) 1989, 1990, 1991, 1995 Free Software Foundation.
3
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.
8
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.
13
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.
17
18    Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. */
19
20 #ifdef _AIX
21  #pragma alloca
22 #endif
23
24 #include <config.h>
25 #include <stdio.h>
26 #include <getopt.h>
27 #include "cp.h"
28 #include "backupfile.h"
29 #include "version.h"
30 #include "safe-stat.h"
31 #include "safe-lstat.h"
32
33 #ifndef _POSIX_VERSION
34 uid_t geteuid ();
35 #endif
36
37 /* Used by do_copy, make_path_private, and re_protect
38    to keep a list of leading directories whose protections
39    need to be fixed after copying. */
40 struct dir_attr
41 {
42   int is_new_dir;
43   int slash_offset;
44   struct dir_attr *next;
45 };
46
47 char *dirname ();
48 char *xstrdup ();
49 enum backup_type get_version ();
50 int eaccess_stat ();
51 int full_write ();
52
53 static int do_copy ();
54 static int copy ();
55 static int copy_dir ();
56 static int make_path_private ();
57 static int copy_reg ();
58 static int re_protect ();
59
60 /* Initial number of entries in each hash table entry's table of inodes.  */
61 #define INITIAL_HASH_MODULE 100
62
63 /* Initial number of entries in the inode hash table.  */
64 #define INITIAL_ENTRY_TAB_SIZE 70
65
66 /* The invocation name of this program.  */
67 char *program_name;
68
69 /* A pointer to either lstat or stat, depending on
70    whether dereferencing of symlinks is done.  */
71 static int (*xstat) ();
72
73 /* If nonzero, copy all files except (directories and, if not dereferencing
74    them, symbolic links,) as if they were regular files. */
75 static int flag_copy_as_regular = 1;
76
77 /* If nonzero, dereference symbolic links (copy the files they point to). */
78 static int flag_dereference = 1;
79
80 /* If nonzero, remove existing destination nondirectories. */
81 static int flag_force = 0;
82
83 /* If nonzero, create hard links instead of copying files.
84    Create destination directories as usual. */
85 static int flag_hard_link = 0;
86
87 /* If nonzero, query before overwriting existing destinations
88    with regular files. */
89 static int flag_interactive = 0;
90
91 /* If nonzero, the command "cp x/e_file e_dir" uses "e_dir/x/e_file"
92    as its destination instead of the usual "e_dir/e_file." */
93 static int flag_path = 0;
94
95 /* If nonzero, give the copies the original files' permissions,
96    ownership, and timestamps. */
97 static int flag_preserve = 0;
98
99 /* If nonzero, copy directories recursively and copy special files
100    as themselves rather than copying their contents. */
101 static int flag_recursive = 0;
102
103 /* If nonzero, create symbolic links instead of copying files.
104    Create destination directories as usual. */
105 static int flag_symbolic_link = 0;
106
107 /* If nonzero, when copying recursively, skip any subdirectories that are
108    on different filesystems from the one we started on. */
109 static int flag_one_file_system = 0;
110
111 /* If nonzero, do not copy a nondirectory that has an existing destination
112    with the same or newer modification time. */
113 static int flag_update = 0;
114
115 /* If nonzero, display the names of the files before copying them. */
116 static int flag_verbose = 0;
117
118 /* The error code to return to the system. */
119 static int exit_status = 0;
120
121 /* The bits to preserve in created files' modes. */
122 static int umask_kill;
123
124 /* This process's effective user ID.  */
125 static uid_t myeuid;
126
127 /* If non-zero, display usage information and exit.  */
128 static int show_help;
129
130 /* If non-zero, print the version on standard output and exit.  */
131 static int show_version;
132
133 static struct option const long_opts[] =
134 {
135   {"archive", no_argument, NULL, 'a'},
136   {"backup", no_argument, NULL, 'b'},
137   {"force", no_argument, NULL, 'f'},
138   {"interactive", no_argument, NULL, 'i'},
139   {"link", no_argument, NULL, 'l'},
140   {"no-dereference", no_argument, &flag_dereference, 0},
141   {"one-file-system", no_argument, &flag_one_file_system, 1},
142   {"parents", no_argument, &flag_path, 1},
143   {"path", no_argument, &flag_path, 1},
144   {"preserve", no_argument, &flag_preserve, 1},
145   {"recursive", no_argument, NULL, 'R'},
146   {"suffix", required_argument, NULL, 'S'},
147   {"symbolic-link", no_argument, NULL, 's'},
148   {"update", no_argument, &flag_update, 1},
149   {"verbose", no_argument, &flag_verbose, 1},
150   {"version-control", required_argument, NULL, 'V'},
151   {"help", no_argument, &show_help, 1},
152   {"version", no_argument, &show_version, 1},
153   {NULL, 0, NULL, 0}
154 };
155 \f
156 void
157 main (argc, argv)
158      int argc;
159      char *argv[];
160 {
161   int c;
162   int make_backups = 0;
163   char *version;
164
165   program_name = argv[0];
166   myeuid = geteuid ();
167
168   version = getenv ("SIMPLE_BACKUP_SUFFIX");
169   if (version)
170     simple_backup_suffix = version;
171   version = getenv ("VERSION_CONTROL");
172
173   /* Find out the current file creation mask, to knock the right bits
174      when using chmod.  The creation mask is set to to be liberal, so
175      that created directories can be written, even if it would not
176      have been allowed with the mask this process was started with.  */
177
178   umask_kill = 0777777 ^ umask (0);
179
180   while ((c = getopt_long (argc, argv, "abdfilprsuvxPRS:V:", long_opts,
181                            (int *) 0)) != EOF)
182     {
183       switch (c)
184         {
185         case 0:
186           break;
187
188         case 'a':               /* Like -dpR. */
189           flag_dereference = 0;
190           flag_preserve = 1;
191           flag_recursive = 1;
192           flag_copy_as_regular = 0;
193           break;
194
195         case 'b':
196           make_backups = 1;
197           break;
198
199         case 'd':
200           flag_dereference = 0;
201           break;
202
203         case 'f':
204           flag_force = 1;
205           flag_interactive = 0;
206           break;
207
208         case 'i':
209           flag_force = 0;
210           flag_interactive = 1;
211           break;
212
213         case 'l':
214           flag_hard_link = 1;
215           break;
216
217         case 'p':
218           flag_preserve = 1;
219           break;
220
221         case 'P':
222           flag_path = 1;
223           break;
224
225         case 'r':
226           flag_recursive = 1;
227           flag_copy_as_regular = 1;
228           break;
229
230         case 'R':
231           flag_recursive = 1;
232           flag_copy_as_regular = 0;
233           break;
234
235         case 's':
236 #ifdef S_ISLNK
237           flag_symbolic_link = 1;
238 #else
239           error (1, 0, "symbolic links are not supported on this system");
240 #endif
241           break;
242
243         case 'u':
244           flag_update = 1;
245           break;
246
247         case 'v':
248           flag_verbose = 1;
249           break;
250
251         case 'x':
252           flag_one_file_system = 1;
253           break;
254
255         case 'S':
256           simple_backup_suffix = optarg;
257           break;
258
259         case 'V':
260           version = optarg;
261           break;
262
263         default:
264           usage (2, (char *) 0);
265         }
266     }
267
268   if (show_version)
269     {
270       printf ("%s\n", version_string);
271       exit (0);
272     }
273
274   if (show_help)
275     usage (0, NULL);
276
277   if (flag_hard_link && flag_symbolic_link)
278     usage (2, "cannot make both hard and symbolic links");
279
280   if (make_backups)
281     backup_type = get_version (version);
282
283   if (flag_preserve == 1)
284     umask_kill = 0777777;
285
286   /* The key difference between -d (--no-dereference) and not is the version
287      of `stat' to call.  */
288
289   if (flag_dereference)
290     xstat = safe_stat;
291   else
292     xstat = safe_lstat;
293
294   /* Allocate space for remembering copied and created files.  */
295
296   hash_init (INITIAL_HASH_MODULE, INITIAL_ENTRY_TAB_SIZE);
297
298   exit_status |= do_copy (argc, argv);
299
300   exit (exit_status);
301 }
302 \f
303 /* Scan the arguments, and copy each by calling copy.
304    Return 0 if successful, 1 if any errors occur. */
305
306 static int
307 do_copy (argc, argv)
308      int argc;
309      char *argv[];
310 {
311   char *dest;
312   struct stat sb;
313   int new_dst = 0;
314   int ret = 0;
315
316   if (optind >= argc)
317     usage (2, "missing file arguments");
318   if (optind >= argc - 1)
319     usage (2, "missing file argument");
320
321   dest = argv[argc - 1];
322
323   if (safe_lstat (dest, &sb))
324     {
325       if (errno != ENOENT)
326         {
327           error (0, errno, "%s", dest);
328           return 1;
329         }
330       else
331         new_dst = 1;
332     }
333   else
334     {
335       struct stat sbx;
336
337       /* If `dest' is not a symlink to a nonexistent file, use
338          the results of stat instead of lstat, so we can copy files
339          into symlinks to directories. */
340       if (safe_stat (dest, &sbx) == 0)
341         sb = sbx;
342     }
343
344   if (!new_dst && S_ISDIR (sb.st_mode))
345     {
346       /* cp file1...filen edir
347          Copy the files `file1' through `filen'
348          to the existing directory `edir'. */
349
350       for (;;)
351         {
352           char *arg;
353           char *ap;
354           char *dst_path;
355           int parent_exists = 1; /* True if dirname (dst_path) exists. */
356           struct dir_attr *attr_list;
357
358           arg = argv[optind];
359
360           strip_trailing_slashes (arg);
361
362           if (flag_path)
363             {
364               /* Append all of `arg' to `dest'.  */
365               dst_path = xmalloc (strlen (dest) + strlen (arg) + 2);
366               stpcpy (stpcpy (stpcpy (dst_path, dest), "/"), arg);
367
368               /* For --parents, we have to make sure that the directory
369                  dirname (dst_path) exists.  We may have to create a few
370                  leading directories. */
371               parent_exists = !make_path_private (dst_path,
372                                           strlen (dest) + 1, 0700,
373                                           flag_verbose ? "%s -> %s\n" :
374                                           (char *) NULL,
375                                           &attr_list, &new_dst);
376             }
377           else
378             {
379               /* Append the last component of `arg' to `dest'.  */
380
381               ap = basename (arg);
382               /* For `cp -R source/.. dest', don't copy into `dest/..'. */
383               if (!strcmp (ap, ".."))
384                 dst_path = xstrdup (dest);
385               else
386                 {
387                   dst_path = xmalloc (strlen (dest) + strlen (ap) + 2);
388                   stpcpy (stpcpy (stpcpy (dst_path, dest), "/"), ap);
389                 }
390             }
391
392           if (!parent_exists)
393             {
394               /* make_path_private failed, so we shouldn't even attempt the copy. */
395               ret = 1;
396             }
397           else
398             {
399               ret |= copy (arg, dst_path, new_dst, 0, (struct dir_list *) 0);
400               forget_all ();
401
402               if (flag_path)
403                 {
404                   ret |= re_protect (dst_path, strlen (dest) + 1,
405                                         attr_list);
406                 }
407             }
408
409           free (dst_path);
410           ++optind;
411           if (optind == argc - 1)
412             break;
413         }
414       return ret;
415     }
416   else if (argc - optind == 2)
417     {
418       char *new_dest;
419       char *source;
420       struct stat source_stats;
421
422       if (flag_path)
423         usage (2, "when preserving paths, last argument must be a directory");
424
425       source = argv[optind];
426
427       /* When the destination is specified with a trailing slash and the
428          source exists but is not a directory, convert the user's command
429          `cp source dest/' to `cp source dest/basename(source)'.  */
430
431       if (dest[strlen (dest) - 1] == '/'
432           && safe_lstat (source, &source_stats) == 0
433           && !S_ISDIR (source_stats.st_mode))
434         {
435           char *source_base;
436           char *tmp_source;
437
438           tmp_source = (char *) alloca (strlen (source) + 1);
439           strcpy (tmp_source, source);
440           strip_trailing_slashes (tmp_source);
441           source_base = basename (tmp_source);
442
443           new_dest = (char *) alloca (strlen (dest) + 1 +
444                                       strlen (source_base) + 1);
445           stpcpy (stpcpy (stpcpy (new_dest, dest), "/"), source_base);
446         }
447       else
448         {
449           new_dest = dest;
450         }
451
452       return copy (source, new_dest, new_dst, 0, (struct dir_list *) 0);
453     }
454   else
455     usage (2,
456            "when copying multiple files, last argument must be a directory");
457 }
458 \f
459 /* Copy the file SRC_PATH to the file DST_PATH.  The files may be of
460    any type.  NEW_DST should be non-zero if the file DST_PATH cannot
461    exist because its parent directory was just created; NEW_DST should
462    be zero if DST_PATH might already exist.  DEVICE is the device
463    number of the parent directory, or 0 if the parent of this file is
464    not known.  ANCESTORS points to a linked, null terminated list of
465    devices and inodes of parent directories of SRC_PATH.
466    Return 0 if successful, 1 if an error occurs. */
467
468 static int
469 copy (src_path, dst_path, new_dst, device, ancestors)
470      char *src_path;
471      char *dst_path;
472      int new_dst;
473      dev_t device;
474      struct dir_list *ancestors;
475 {
476   struct stat src_sb;
477   struct stat dst_sb;
478   int src_mode;
479   int src_type;
480   char *earlier_file;
481   char *dst_backup = NULL;
482   int fix_mode = 0;
483
484   if ((*xstat) (src_path, &src_sb))
485     {
486       error (0, errno, "%s", src_path);
487       return 1;
488     }
489
490   /* Are we crossing a file system boundary?  */
491   if (flag_one_file_system && device != 0 && device != src_sb.st_dev)
492     return 0;
493
494   /* We wouldn't insert a node unless nlink > 1, except that we need to
495      find created files so as to not copy infinitely if a directory is
496      copied into itself.  */
497
498   earlier_file = remember_copied (dst_path, src_sb.st_ino, src_sb.st_dev);
499
500   /* Did we just create this file?  */
501
502   if (earlier_file == &new_file)
503     return 0;
504
505   src_mode = src_sb.st_mode;
506   src_type = src_sb.st_mode;
507
508   if (S_ISDIR (src_type) && !flag_recursive)
509     {
510       error (0, 0, "%s: omitting directory", src_path);
511       return 1;
512     }
513
514   if (!new_dst)
515     {
516       if ((*xstat) (dst_path, &dst_sb))
517         {
518           if (errno != ENOENT)
519             {
520               error (0, errno, "%s", dst_path);
521               return 1;
522             }
523           else
524             new_dst = 1;
525         }
526       else
527         {
528           /* The file exists already.  */
529
530           if (src_sb.st_ino == dst_sb.st_ino && src_sb.st_dev == dst_sb.st_dev)
531             {
532               if (flag_hard_link)
533                 return 0;
534
535               error (0, 0, "`%s' and `%s' are the same file",
536                      src_path, dst_path);
537               return 1;
538             }
539
540           if (!S_ISDIR (src_type))
541             {
542               if (S_ISDIR (dst_sb.st_mode))
543                 {
544                   error (0, 0,
545                          "%s: cannot overwrite directory with non-directory",
546                          dst_path);
547                   return 1;
548                 }
549
550               if (flag_update && src_sb.st_mtime <= dst_sb.st_mtime)
551                 return 0;
552             }
553
554           if (S_ISREG (src_type) && !flag_force)
555             {
556               if (flag_interactive)
557                 {
558                   if (eaccess_stat (&dst_sb, W_OK, dst_path) != 0)
559                     fprintf (stderr,
560                              "%s: overwrite `%s', overriding mode %04o? ",
561                              program_name, dst_path,
562                              (unsigned int) (dst_sb.st_mode & 07777));
563                   else
564                     fprintf (stderr, "%s: overwrite `%s'? ",
565                              program_name, dst_path);
566                   if (!yesno ())
567                     return 0;
568                 }
569             }
570
571           if (backup_type != none && !S_ISDIR (dst_sb.st_mode))
572             {
573               char *tmp_backup = find_backup_file_name (dst_path);
574               if (tmp_backup == NULL)
575                 error (1, 0, "virtual memory exhausted");
576               dst_backup = (char *) alloca (strlen (tmp_backup) + 1);
577               strcpy (dst_backup, tmp_backup);
578               free (tmp_backup);
579               if (rename (dst_path, dst_backup))
580                 {
581                   if (errno != ENOENT)
582                     {
583                       error (0, errno, "cannot backup `%s'", dst_path);
584                       return 1;
585                     }
586                   else
587                     dst_backup = NULL;
588                 }
589               new_dst = 1;
590             }
591           else if (flag_force)
592             {
593               if (S_ISDIR (dst_sb.st_mode))
594                 {
595                   /* Temporarily change mode to allow overwriting. */
596                   if (eaccess_stat (&dst_sb, W_OK | X_OK) != 0)
597                     {
598                       if (chmod (dst_path, 0700))
599                         {
600                           error (0, errno, "%s", dst_path);
601                           return 1;
602                         }
603                       else
604                         fix_mode = 1;
605                     }
606                 }
607               else
608                 {
609                   if (unlink (dst_path) && errno != ENOENT)
610                     {
611                       error (0, errno, "cannot remove old link to `%s'",
612                              dst_path);
613                       return 1;
614                     }
615                   new_dst = 1;
616                 }
617             }
618         }
619     }
620
621   /* If the source is a directory, we don't always create the destination
622      directory.  So --verbose should not announce anything until we're
623      sure we'll create a directory. */
624   if (flag_verbose && !S_ISDIR (src_type))
625     printf ("%s -> %s\n", src_path, dst_path);
626
627   /* Did we copy this inode somewhere else (in this command line argument)
628      and therefore this is a second hard link to the inode?  */
629
630   if (!flag_dereference && src_sb.st_nlink > 1 && earlier_file)
631     {
632       if (link (earlier_file, dst_path))
633         {
634           error (0, errno, "%s", dst_path);
635           goto un_backup;
636         }
637       return 0;
638     }
639
640   if (S_ISDIR (src_type))
641     {
642       struct dir_list *dir;
643
644       /* If this directory has been copied before during the
645          recursion, there is a symbolic link to an ancestor
646          directory of the symbolic link.  It is impossible to
647          continue to copy this, unless we've got an infinite disk.  */
648
649       if (is_ancestor (&src_sb, ancestors))
650         {
651           error (0, 0, "%s: cannot copy cyclic symbolic link", src_path);
652           goto un_backup;
653         }
654
655       /* Insert the current directory in the list of parents.  */
656
657       dir = (struct dir_list *) alloca (sizeof (struct dir_list));
658       dir->parent = ancestors;
659       dir->ino = src_sb.st_ino;
660       dir->dev = src_sb.st_dev;
661
662       if (new_dst || !S_ISDIR (dst_sb.st_mode))
663         {
664           /* Create the new directory writable and searchable, so
665              we can create new entries in it.  */
666
667           if (mkdir (dst_path, (src_mode & umask_kill) | 0700))
668             {
669               error (0, errno, "cannot create directory `%s'", dst_path);
670               goto un_backup;
671             }
672
673           /* Insert the created directory's inode and device
674              numbers into the search structure, so that we can
675              avoid copying it again.  */
676
677           if (remember_created (dst_path))
678             goto un_backup;
679
680           if (flag_verbose)
681             printf ("%s -> %s\n", src_path, dst_path);
682         }
683
684       /* Copy the contents of the directory.  */
685
686       if (copy_dir (src_path, dst_path, new_dst, &src_sb, dir))
687         return 1;
688     }
689 #ifdef S_ISLNK
690   else if (flag_symbolic_link)
691     {
692       if (*src_path == '/'
693           || (!strncmp (dst_path, "./", 2) && strchr (dst_path + 2, '/') == 0)
694           || strchr (dst_path, '/') == 0)
695         {
696           if (symlink (src_path, dst_path))
697             {
698               error (0, errno, "%s", dst_path);
699               goto un_backup;
700             }
701           return 0;
702         }
703       else
704         {
705           error (0, 0,
706                  "%s: can only make relative symbolic links in current directory", dst_path);
707           goto un_backup;
708         }
709     }
710 #endif
711   else if (flag_hard_link)
712     {
713       if (link (src_path, dst_path))
714         {
715           error (0, errno, "cannot create link `%s'", dst_path);
716           goto un_backup;
717         }
718       return 0;
719     }
720   else if (S_ISREG (src_type)
721            || (flag_copy_as_regular && !S_ISDIR (src_type)
722 #ifdef S_ISLNK
723                && !S_ISLNK (src_type)
724 #endif
725                ))
726     {
727       if (copy_reg (src_path, dst_path))
728         goto un_backup;
729     }
730   else
731 #ifdef S_ISFIFO
732   if (S_ISFIFO (src_type))
733     {
734       if (mkfifo (dst_path, src_mode & umask_kill))
735         {
736           error (0, errno, "cannot create fifo `%s'", dst_path);
737           goto un_backup;
738         }
739     }
740   else
741 #endif
742     if (S_ISBLK (src_type) || S_ISCHR (src_type)
743 #ifdef S_ISSOCK
744         || S_ISSOCK (src_type)
745 #endif
746         )
747     {
748       if (mknod (dst_path, src_mode & umask_kill, src_sb.st_rdev))
749         {
750           error (0, errno, "cannot create special file `%s'", dst_path);
751           goto un_backup;
752         }
753     }
754   else
755 #ifdef S_ISLNK
756   if (S_ISLNK (src_type))
757     {
758       char *link_val;
759       int link_size;
760
761       link_val = (char *) alloca (PATH_MAX + 2);
762       link_size = readlink (src_path, link_val, PATH_MAX + 1);
763       if (link_size < 0)
764         {
765           error (0, errno, "cannot read symbolic link `%s'", src_path);
766           goto un_backup;
767         }
768       link_val[link_size] = '\0';
769
770       if (symlink (link_val, dst_path))
771         {
772           error (0, errno, "cannot create symbolic link `%s'", dst_path);
773           goto un_backup;
774         }
775       return 0;
776     }
777   else
778 #endif
779     {
780       error (0, 0, "%s: unknown file type", src_path);
781       goto un_backup;
782     }
783
784   /* Adjust the times (and if possible, ownership) for the copy.
785      chown turns off set[ug]id bits for non-root,
786      so do the chmod last.  */
787
788   if (flag_preserve)
789     {
790       struct utimbuf utb;
791
792       utb.actime = src_sb.st_atime;
793       utb.modtime = src_sb.st_mtime;
794
795       if (utime (dst_path, &utb))
796         {
797           error (0, errno, "%s", dst_path);
798           return 1;
799         }
800
801       /* If non-root uses -p, it's ok if we can't preserve ownership.
802          But root probably wants to know, e.g. if NFS disallows it.  */
803       if (chown (dst_path,
804                  (myeuid == 0 ? src_sb.st_uid : myeuid),
805                  src_sb.st_gid)
806           && (errno != EPERM || myeuid == 0))
807         {
808           error (0, errno, "%s", dst_path);
809           return 1;
810         }
811     }
812
813   if ((flag_preserve || new_dst)
814       && (flag_copy_as_regular || S_ISREG (src_type) || S_ISDIR (src_type)))
815     {
816       if (chmod (dst_path, src_mode & umask_kill))
817         {
818           error (0, errno, "%s", dst_path);
819           return 1;
820         }
821     }
822   else if (fix_mode)
823     {
824       /* Reset the temporarily changed mode.  */
825       if (chmod (dst_path, dst_sb.st_mode))
826         {
827           error (0, errno, "%s", dst_path);
828           return 1;
829         }
830     }
831
832   return 0;
833
834 un_backup:
835   if (dst_backup)
836     {
837       if (rename (dst_backup, dst_path))
838         error (0, errno, "cannot un-backup `%s'", dst_path);
839     }
840   return 1;
841 }
842 \f
843 /* Ensure that the parent directory of CONST_DIRPATH exists, for
844    the --parents option.
845
846    SRC_OFFSET is the index in CONST_DIRPATH (which is a destination
847    path) of the beginning of the source directory name.
848    Create any leading directories that don't already exist,
849    giving them permissions MODE.
850    If VERBOSE_FMT_STRING is nonzero, use it as a printf format
851    string for printing a message after successfully making a directory.
852    The format should take two string arguments: the names of the
853    source and destination directories.
854    Creates a linked list of attributes of intermediate directories,
855    *ATTR_LIST, for re_protect to use after calling copy.
856    Sets *NEW_DST to 1 if this function creates parent of CONST_DIRPATH.
857
858    Return 0 if parent of CONST_DIRPATH exists as a directory with the proper
859    permissions when done, otherwise 1. */
860
861 static int
862 make_path_private (const_dirpath, src_offset, mode, verbose_fmt_string,
863                    attr_list, new_dst)
864      char *const_dirpath;
865      int src_offset;
866      int mode;
867      char *verbose_fmt_string;
868      struct dir_attr **attr_list;
869      int *new_dst;
870 {
871   struct stat stats;
872   char *dirpath;                /* A copy of CONST_DIRPATH we can change. */
873   char *src;                    /* Source name in `dirpath'. */
874   char *tmp_dst_dirname;        /* Leading path of `dirpath', malloc. */
875   char *dst_dirname;            /* Leading path of `dirpath', alloca. */
876
877   dirpath = (char *) alloca (strlen (const_dirpath) + 1);
878   strcpy (dirpath, const_dirpath);
879
880   src = dirpath + src_offset;
881
882   tmp_dst_dirname = dirname (dirpath);
883   dst_dirname = (char *) alloca (strlen (tmp_dst_dirname) + 1);
884   strcpy (dst_dirname, tmp_dst_dirname);
885   free (tmp_dst_dirname);
886
887   *attr_list = NULL;
888
889   if ((*xstat) (dst_dirname, &stats))
890     {
891       /* Parent of CONST_DIRNAME does not exist.
892          Make all missing intermediate directories. */
893       char *slash;
894
895       slash = src;
896       while (*slash == '/')
897         slash++;
898       while ((slash = strchr (slash, '/')))
899         {
900           /* Add this directory to the list of directories whose modes need
901              fixing later. */
902           struct dir_attr *new =
903             (struct dir_attr *) xmalloc (sizeof (struct dir_attr));
904           new->slash_offset = slash - dirpath;
905           new->next = *attr_list;
906           *attr_list = new;
907
908           *slash = '\0';
909           if ((*xstat) (dirpath, &stats))
910             {
911               /* This element of the path does not exist.  We must set
912                  *new_dst and new->is_new_dir inside this loop because,
913                  for example, in the command `cp --parents ../a/../b/c e_dir',
914                  make_path_private creates only e_dir/../a if ./b already
915                  exists. */
916               *new_dst = 1;
917               new->is_new_dir = 1;
918               if (mkdir (dirpath, mode))
919                 {
920                   error (0, errno, "cannot make directory `%s'", dirpath);
921                   return 1;
922                 }
923               else
924                 {
925                   if (verbose_fmt_string != NULL)
926                     printf (verbose_fmt_string, src, dirpath);
927                 }
928             }
929           else if (!S_ISDIR (stats.st_mode))
930             {
931               error (0, 0, "`%s' exists but is not a directory", dirpath);
932               return 1;
933             }
934           else
935             {
936               new->is_new_dir = 0;
937               *new_dst = 0;
938             }
939           *slash++ = '/';
940
941           /* Avoid unnecessary calls to `stat' when given
942              pathnames containing multiple adjacent slashes.  */
943           while (*slash == '/')
944             slash++;
945         }
946     }
947
948   /* We get here if the parent of `dirpath' already exists. */
949
950   else if (!S_ISDIR (stats.st_mode))
951     {
952       error (0, 0, "`%s' exists but is not a directory", dst_dirname);
953       return 1;
954     }
955   else
956     {
957       *new_dst = 0;
958     }
959   return 0;
960 }
961 \f
962 /* Ensure that the parent directories of CONST_DST_PATH have the
963    correct protections, for the --parents option.  This is done
964    after all copying has been completed, to allow permissions
965    that don't include user write/execute.
966
967    SRC_OFFSET is the index in CONST_DST_PATH of the beginning of the
968    source directory name.
969
970    ATTR_LIST is a null-terminated linked list of structures that
971    indicates the end of the filename of each intermediate directory
972    in CONST_DST_PATH that may need to have its attributes changed.
973    The command `cp --parents --preserve a/b/c d/e_dir' changes the
974    attributes of the directories d/e_dir/a and d/e_dir/a/b to match
975    the corresponding source directories regardless of whether they
976    existed before the `cp' command was given.
977
978    Return 0 if the parent of CONST_DST_PATH and any intermediate
979    directories specified by ATTR_LIST have the proper permissions
980    when done, otherwise 1. */
981
982 static int
983 re_protect (const_dst_path, src_offset, attr_list)
984      char *const_dst_path;
985      int src_offset;
986      struct dir_attr *attr_list;
987 {
988   struct dir_attr *p;
989   char *dst_path;               /* A copy of CONST_DST_PATH we can change. */
990   char *src_path;               /* The source name in `dst_path'. */
991
992   dst_path = (char *) alloca (strlen (const_dst_path) + 1);
993   strcpy (dst_path, const_dst_path);
994   src_path = dst_path + src_offset;
995
996   for (p = attr_list; p; p = p->next)
997     {
998       struct stat src_sb;
999
1000       dst_path[p->slash_offset] = '\0';
1001
1002       if ((*xstat) (src_path, &src_sb))
1003         {
1004           error (0, errno, "%s", src_path);
1005           return 1;
1006         }
1007
1008       /* Adjust the times (and if possible, ownership) for the copy.
1009          chown turns off set[ug]id bits for non-root,
1010          so do the chmod last.  */
1011
1012       if (flag_preserve)
1013         {
1014           struct utimbuf utb;
1015
1016           utb.actime = src_sb.st_atime;
1017           utb.modtime = src_sb.st_mtime;
1018
1019           if (utime (dst_path, &utb))
1020             {
1021               error (0, errno, "%s", dst_path);
1022               return 1;
1023             }
1024
1025           /* If non-root uses -p, it's ok if we can't preserve ownership.
1026              But root probably wants to know, e.g. if NFS disallows it.  */
1027           if (chown (dst_path, src_sb.st_uid, src_sb.st_gid)
1028               && (errno != EPERM || myeuid == 0))
1029             {
1030               error (0, errno, "%s", dst_path);
1031               return 1;
1032             }
1033         }
1034
1035       if (flag_preserve || p->is_new_dir)
1036         {
1037           if (chmod (dst_path, src_sb.st_mode & umask_kill))
1038             {
1039               error (0, errno, "%s", dst_path);
1040               return 1;
1041             }
1042         }
1043
1044       dst_path[p->slash_offset] = '/';
1045     }
1046   return 0;
1047 }
1048 \f
1049 /* Read the contents of the directory SRC_PATH_IN, and recursively
1050    copy the contents to DST_PATH_IN.  NEW_DST is non-zero if
1051    DST_PATH_IN is a directory that was created previously in the
1052    recursion.   SRC_SB and ANCESTORS describe SRC_PATH_IN.
1053    Return 0 if successful, -1 if an error occurs. */
1054
1055 static int
1056 copy_dir (src_path_in, dst_path_in, new_dst, src_sb, ancestors)
1057      char *src_path_in;
1058      char *dst_path_in;
1059      int new_dst;
1060      struct stat *src_sb;
1061      struct dir_list *ancestors;
1062 {
1063   char *name_space;
1064   char *namep;
1065   char *src_path;
1066   char *dst_path;
1067   int ret = 0;
1068
1069   errno = 0;
1070   name_space = savedir (src_path_in, src_sb->st_size);
1071   if (name_space == 0)
1072     {
1073       if (errno)
1074         {
1075           error (0, errno, "%s", src_path_in);
1076           return -1;
1077         }
1078       else
1079         error (1, 0, "virtual memory exhausted");
1080     }
1081
1082   namep = name_space;
1083   while (*namep != '\0')
1084     {
1085       int fn_length = strlen (namep) + 1;
1086
1087       dst_path = xmalloc (strlen (dst_path_in) + fn_length + 1);
1088       src_path = xmalloc (strlen (src_path_in) + fn_length + 1);
1089
1090       stpcpy (stpcpy (stpcpy (src_path, src_path_in), "/"), namep);
1091       stpcpy (stpcpy (stpcpy (dst_path, dst_path_in), "/"), namep);
1092
1093       ret |= copy (src_path, dst_path, new_dst, src_sb->st_dev, ancestors);
1094
1095       /* Free the memory for `src_path'.  The memory for `dst_path'
1096          cannot be deallocated, since it is used to create multiple
1097          hard links.  */
1098
1099       free (src_path);
1100
1101       namep += fn_length;
1102     }
1103   free (name_space);
1104   return -ret;
1105 }
1106 \f
1107 /* Copy a regular file from SRC_PATH to DST_PATH.
1108    If the source file contains holes, copies holes and blocks of zeros
1109    in the source file as holes in the destination file.
1110    (Holes are read as zeroes by the `read' system call.)
1111    Return 0 if successful, -1 if an error occurred. */
1112
1113 static int
1114 copy_reg (src_path, dst_path)
1115      char *src_path;
1116      char *dst_path;
1117 {
1118   char *buf;
1119   int buf_size;
1120   int dest_desc;
1121   int source_desc;
1122   int n_read;
1123   struct stat sb;
1124   char *cp;
1125   int *ip;
1126   int return_val = 0;
1127   long n_read_total = 0;
1128   int last_write_made_hole = 0;
1129   int make_holes = 0;
1130
1131   source_desc = open (src_path, O_RDONLY);
1132   if (source_desc < 0)
1133     {
1134       error (0, errno, "%s", src_path);
1135       return -1;
1136     }
1137
1138   /* Create the new regular file with small permissions initially,
1139      to not create a security hole.  */
1140
1141   dest_desc = open (dst_path, O_WRONLY | O_CREAT | O_TRUNC, 0600);
1142   if (dest_desc < 0)
1143     {
1144       error (0, errno, "cannot create regular file `%s'", dst_path);
1145       return_val = -1;
1146       goto ret2;
1147     }
1148
1149   /* Find out the optimal buffer size.  */
1150
1151   if (fstat (dest_desc, &sb))
1152     {
1153       error (0, errno, "%s", dst_path);
1154       return_val = -1;
1155       goto ret;
1156     }
1157
1158   buf_size = ST_BLKSIZE (sb);
1159
1160 #ifdef HAVE_ST_BLOCKS
1161   if (S_ISREG (sb.st_mode))
1162     {
1163       /* Find out whether the file contains any sparse blocks. */
1164
1165       if (fstat (source_desc, &sb))
1166         {
1167           error (0, errno, "%s", src_path);
1168           return_val = -1;
1169           goto ret;
1170         }
1171
1172       /* If the file has fewer blocks than would normally
1173          be needed for a file of its size, then
1174          at least one of the blocks in the file is a hole. */
1175       if (S_ISREG (sb.st_mode) && sb.st_size > sb.st_blocks * DEV_BSIZE)
1176         make_holes = 1;
1177     }
1178 #endif
1179
1180   /* Make a buffer with space for a sentinel at the end.  */
1181
1182   buf = (char *) alloca (buf_size + sizeof (int));
1183
1184   for (;;)
1185     {
1186       n_read = read (source_desc, buf, buf_size);
1187       if (n_read < 0)
1188         {
1189 #ifdef EINTR
1190           if (errno == EINTR)
1191             continue;
1192 #endif
1193           error (0, errno, "%s", src_path);
1194           return_val = -1;
1195           goto ret;
1196         }
1197       if (n_read == 0)
1198         break;
1199
1200       n_read_total += n_read;
1201
1202       ip = 0;
1203       if (make_holes)
1204         {
1205           buf[n_read] = 1;      /* Sentinel to stop loop.  */
1206
1207           /* Find first non-zero *word*, or the word with the sentinel.  */
1208
1209           ip = (int *) buf;
1210           while (*ip++ == 0)
1211             ;
1212
1213           /* Find the first non-zero *byte*, or the sentinel.  */
1214
1215           cp = (char *) (ip - 1);
1216           while (*cp++ == 0)
1217             ;
1218
1219           /* If we found the sentinel, the whole input block was zero,
1220              and we can make a hole.  */
1221
1222           if (cp > buf + n_read)
1223             {
1224               /* Make a hole.  */
1225               if (lseek (dest_desc, (off_t) n_read, SEEK_CUR) < 0L)
1226                 {
1227                   error (0, errno, "%s", dst_path);
1228                   return_val = -1;
1229                   goto ret;
1230                 }
1231               last_write_made_hole = 1;
1232             }
1233           else
1234             /* Clear to indicate that a normal write is needed. */
1235             ip = 0;
1236         }
1237       if (ip == 0)
1238         {
1239           if (full_write (dest_desc, buf, n_read) < 0)
1240             {
1241               error (0, errno, "%s", dst_path);
1242               return_val = -1;
1243               goto ret;
1244             }
1245           last_write_made_hole = 0;
1246         }
1247     }
1248
1249   /* If the file ends with a `hole', something needs to be written at
1250      the end.  Otherwise the kernel would truncate the file at the end
1251      of the last write operation.  */
1252
1253   if (last_write_made_hole)
1254     {
1255 #ifdef HAVE_FTRUNCATE
1256       /* Write a null character and truncate it again.  */
1257       if (full_write (dest_desc, "", 1) < 0
1258           || ftruncate (dest_desc, n_read_total) < 0)
1259 #else
1260       /* Seek backwards one character and write a null.  */
1261       if (lseek (dest_desc, (off_t) -1, SEEK_CUR) < 0L
1262           || full_write (dest_desc, "", 1) < 0)
1263 #endif
1264         {
1265           error (0, errno, "%s", dst_path);
1266           return_val = -1;
1267         }
1268     }
1269
1270 ret:
1271   if (close (dest_desc) < 0)
1272     {
1273       error (0, errno, "%s", dst_path);
1274       return_val = -1;
1275     }
1276 ret2:
1277   if (close (source_desc) < 0)
1278     {
1279       error (0, errno, "%s", src_path);
1280       return_val = -1;
1281     }
1282
1283   return return_val;
1284 }