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