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