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