home *** CD-ROM | disk | FTP | other *** search
/ Fresh Fish 2 / FFMCD02.bin / useful / dist / gnu / fileutils / fileutils-3.9-amiga / src / cp.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-12-13  |  31.2 KB  |  1,292 lines

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