home *** CD-ROM | disk | FTP | other *** search
/ Il CD di internet / CD.iso / SOURCE / N / TCPIP / NETKIT-B.05 / NETKIT-B / NetKit-B-0.05 / rcp / rcp.c < prev   
Encoding:
C/C++ Source or Header  |  1994-05-23  |  20.9 KB  |  989 lines

  1. /*
  2.  * Copyright (c) 1983, 1990 The Regents of the University of California.
  3.  * All rights reserved.
  4.  *
  5.  * Redistribution and use in source and binary forms, with or without
  6.  * modification, are permitted provided that the following conditions
  7.  * are met:
  8.  * 1. Redistributions of source code must retain the above copyright
  9.  *    notice, this list of conditions and the following disclaimer.
  10.  * 2. Redistributions in binary form must reproduce the above copyright
  11.  *    notice, this list of conditions and the following disclaimer in the
  12.  *    documentation and/or other materials provided with the distribution.
  13.  * 3. All advertising materials mentioning features or use of this software
  14.  *    must display the following acknowledgement:
  15.  *    This product includes software developed by the University of
  16.  *    California, Berkeley and its contributors.
  17.  * 4. Neither the name of the University nor the names of its contributors
  18.  *    may be used to endorse or promote products derived from this software
  19.  *    without specific prior written permission.
  20.  *
  21.  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  22.  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  23.  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  24.  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  25.  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  26.  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  27.  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  28.  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  29.  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  30.  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  31.  * SUCH DAMAGE.
  32.  */
  33.  
  34. #ifndef lint
  35. char copyright[] =
  36. "@(#) Copyright (c) 1983, 1990 The Regents of the University of California.\n\
  37.  All rights reserved.\n";
  38. #endif /* not lint */
  39.  
  40. #ifndef lint
  41. /*static char sccsid[] = "from: @(#)rcp.c    5.32 (Berkeley) 2/25/91";*/
  42. static char rcsid[] = "$Id: rcp.c,v 1.1 1994/05/23 09:07:47 rzsfl Exp rzsfl $";
  43. #endif /* not lint */
  44.  
  45. /*
  46.  * rcp
  47.  */
  48. #include <sys/param.h>
  49. #include <sys/stat.h>
  50. #include <sys/time.h>
  51. #include <sys/ioctl.h>
  52. #include <sys/socket.h>
  53. #include <sys/wait.h>
  54. #include <netinet/in.h>
  55. #include <netinet/ip.h>
  56. #include <dirent.h>
  57. #include <fcntl.h>
  58. #include <signal.h>
  59. #include <pwd.h>
  60. #include <netdb.h>
  61. #include <errno.h>
  62. #include <unistd.h>
  63. #include <stdio.h>
  64. #include <stdlib.h>
  65. #include <string.h>
  66. #include <ctype.h>
  67. #include "pathnames.h"
  68.  
  69. #ifdef KERBEROS
  70. #include <kerberosIV/des.h>
  71. #include <kerberosIV/krb.h>
  72. char    dst_realm_buf[REALM_SZ];
  73. char    *dest_realm = NULL;
  74. int    use_kerberos = 1;
  75. CREDENTIALS     cred;
  76. Key_schedule    schedule;
  77. extern    char    *krb_realmofhost();
  78. #ifdef CRYPT
  79. int    doencrypt = 0;
  80. #define    OPTIONS    "dfk:prtx"
  81. #else
  82. #define    OPTIONS    "dfk:prt"
  83. #endif
  84. #else
  85. #define    OPTIONS "dfprt"
  86. #endif
  87.  
  88. struct passwd *pwd;
  89. u_short    port;
  90. uid_t    userid;
  91. int errs, rem;
  92. int pflag, iamremote, iamrecursive, targetshouldbedirectory;
  93.  
  94. #define    CMDNEEDS    64
  95. char cmd[CMDNEEDS];        /* must hold "rcp -r -p -d\0" */
  96.  
  97. typedef struct _buf {
  98.     int    cnt;
  99.     char    *buf;
  100. } BUF;
  101.  
  102. void lostconn();
  103.  
  104. main(argc, argv)
  105.     int argc;
  106.     char **argv;
  107. {
  108.     extern int optind;
  109.     extern char *optarg;
  110.     struct servent *sp;
  111.     int ch, fflag, tflag;
  112.     char *targ, *shell, *colon();
  113.  
  114.     fflag = tflag = 0;
  115.     while ((ch = getopt(argc, argv, OPTIONS)) != EOF)
  116.         switch(ch) {
  117.         /* user-visible flags */
  118.         case 'p':            /* preserve access/mod times */
  119.             ++pflag;
  120.             break;
  121.         case 'r':
  122.             ++iamrecursive;
  123.             break;
  124. #ifdef    KERBEROS
  125.         case 'k':
  126.             strncpy(dst_realm_buf, optarg, REALM_SZ);
  127.             dest_realm = dst_realm_buf;
  128.             break;
  129. #ifdef CRYPT
  130.         case 'x':
  131.             doencrypt = 1;
  132.             /* des_set_key(cred.session, schedule); */
  133.             break;
  134. #endif
  135. #endif
  136.         /* rshd-invoked options (server) */
  137.         case 'd':
  138.             targetshouldbedirectory = 1;
  139.             break;
  140.         case 'f':            /* "from" */
  141.             iamremote = 1;
  142.             fflag = 1;
  143.             break;
  144.         case 't':            /* "to" */
  145.             iamremote = 1;
  146.             tflag = 1;
  147.             break;
  148.  
  149.         case '?':
  150.         default:
  151.             usage();
  152.         }
  153.     argc -= optind;
  154.     argv += optind;
  155.  
  156. #ifdef KERBEROS
  157. #ifdef CRYPT
  158.     shell = doencrypt ? "ekshell" : "kshell";
  159. #else
  160.     shell = "kshell";
  161. #endif
  162.     sp = getservbyname(shell, "tcp");
  163.     if (sp == NULL) {
  164.         char    msgbuf[64];
  165.         use_kerberos = 0;
  166.         (void)snprintf(msgbuf, sizeof(msgbuf),
  167.             "can't get entry for %s/tcp service", shell);
  168.         old_warning(msgbuf);
  169.         sp = getservbyname(shell = "shell", "tcp");
  170.     }
  171. #else
  172.     sp = getservbyname(shell = "shell", "tcp");
  173. #endif
  174.     if (sp == NULL) {
  175.         (void)fprintf(stderr, "rcp: %s/tcp: unknown service\n", shell);
  176.         exit(1);
  177.     }
  178.     port = sp->s_port;
  179.  
  180.     if (!(pwd = getpwuid(userid = getuid()))) {
  181.         (void)fprintf(stderr, "rcp: unknown user %d.\n", (int)userid);
  182.         exit(1);
  183.     }
  184.  
  185.     if (fflag) {
  186.         /* follow "protocol", send data */
  187.         (void)response();
  188.         (void)setuid(userid);
  189.         source(argc, argv);
  190.         exit(errs);
  191.     }
  192.  
  193.     if (tflag) {
  194.         /* receive data */
  195.         (void)setuid(userid);
  196.         sink(argc, argv);
  197.         exit(errs);
  198.     }
  199.  
  200.     if (argc < 2)
  201.         usage();
  202.     if (argc > 2)
  203.         targetshouldbedirectory = 1;
  204.  
  205.     rem = -1;
  206.     /* command to be executed on remote system using "rsh" */
  207. #ifdef    KERBEROS
  208.     (void)snprintf(cmd, sizeof(cmd),
  209.         "rcp%s%s%s%s", iamrecursive ? " -r" : "",
  210. #ifdef CRYPT
  211.         ((doencrypt && use_kerberos) ? " -x" : ""),
  212. #else
  213.         "",
  214. #endif
  215.         pflag ? " -p" : "", targetshouldbedirectory ? " -d" : "");
  216. #else
  217.     (void)snprintf(cmd, sizeof(cmd), "rcp%s%s%s",
  218.         iamrecursive ? " -r" : "", pflag ? " -p" : "",
  219.         targetshouldbedirectory ? " -d" : "");
  220. #endif
  221.  
  222.     (void)signal(SIGPIPE, lostconn);
  223.  
  224.     if (targ = colon(argv[argc - 1]))
  225.         toremote(targ, argc, argv);    /* destination is remote host */
  226.     else {
  227.         tolocal(argc, argv);        /* destination is local host */
  228.         if (targetshouldbedirectory)
  229.             verifydir(argv[argc - 1]);
  230.     }
  231.     exit(errs);
  232. }
  233.  
  234. toremote(targ, argc, argv)
  235.     char *targ;
  236.     int argc;
  237.     char **argv;
  238. {
  239.     int i, len, tos;
  240.     char *bp, *host, *src, *suser, *thost, *tuser;
  241.     char *colon();
  242.  
  243.     *targ++ = 0;
  244.     if (*targ == 0)
  245.         targ = ".";
  246.  
  247.     if (thost = index(argv[argc - 1], '@')) {
  248.         /* user@host */
  249.         *thost++ = 0;
  250.         tuser = argv[argc - 1];
  251.         if (*tuser == '\0')
  252.             tuser = NULL;
  253.         else if (!okname(tuser))
  254.             exit(1);
  255.     } else {
  256.         thost = argv[argc - 1];
  257.         tuser = NULL;
  258.     }
  259.  
  260.     for (i = 0; i < argc - 1; i++) {
  261.         src = colon(argv[i]);
  262.         if (src) {            /* remote to remote */
  263.             *src++ = 0;
  264.             if (*src == 0)
  265.                 src = ".";
  266.             host = index(argv[i], '@');
  267.             len = strlen(_PATH_RSH) + strlen(argv[i]) +
  268.                 strlen(src) + (tuser ? strlen(tuser) : 0) +
  269.                 strlen(thost) + strlen(targ) + CMDNEEDS + 20;
  270.             if (!(bp = malloc(len)))
  271.                 nospace();
  272.             if (host) {
  273.                 *host++ = 0;
  274.                 suser = argv[i];
  275.                 if (*suser == '\0')
  276.                     suser = pwd->pw_name;
  277.                 else if (!okname(suser))
  278.                     continue;
  279.                 (void)snprintf(bp, len,
  280.                     "%s %s -l %s -n %s %s '%s%s%s:%s'",
  281.                     _PATH_RSH, host, suser, cmd, src,
  282.                     tuser ? tuser : "", tuser ? "@" : "",
  283.                     thost, targ);
  284.             } else
  285.                 (void)snprintf(bp, len,
  286.                     "%s %s -n %s %s '%s%s%s:%s'",
  287.                     _PATH_RSH, argv[i], cmd, src,
  288.                     tuser ? tuser : "", tuser ? "@" : "",
  289.                     thost, targ);
  290.             (void)susystem(bp);
  291.             (void)free(bp);
  292.         } else {            /* local to remote */
  293.             if (rem == -1) {
  294.                 len = strlen(targ) + CMDNEEDS + 20;
  295.                 if (!(bp = malloc(len)))
  296.                     nospace();
  297.                 (void)snprintf(bp, len, "%s -t %s", cmd, targ);
  298.                 host = thost;
  299. #ifdef KERBEROS
  300.                 if (use_kerberos)
  301.                     rem = kerberos(&host, bp,
  302.                         pwd->pw_name,
  303.                         tuser ? tuser : pwd->pw_name);
  304.                 else
  305. #endif
  306.                     rem = rcmd(&host, port, pwd->pw_name,
  307.                         tuser ? tuser : pwd->pw_name,
  308.                         bp, 0);
  309.                 if (rem < 0)
  310.                     exit(1);
  311. #ifdef IP_TOS
  312.                 tos = IPTOS_THROUGHPUT;
  313.                 if (setsockopt(rem, IPPROTO_IP, IP_TOS,
  314.                     (char *)&tos, sizeof(int)) < 0)
  315.                     perror("rcp: setsockopt TOS (ignored)");
  316. #endif
  317.                 if (response() < 0)
  318.                     exit(1);
  319.                 (void)free(bp);
  320.                 (void)setuid(userid);
  321.             }
  322.             source(1, argv+i);
  323.         }
  324.     }
  325. }
  326.  
  327. tolocal(argc, argv)
  328.     int argc;
  329.     char **argv;
  330. {
  331.     int i, len, tos;
  332.     char *bp, *host, *src, *suser;
  333.     char *colon();
  334.  
  335.     for (i = 0; i < argc - 1; i++) {
  336.         if (!(src = colon(argv[i]))) {    /* local to local */
  337.             len = strlen(_PATH_CP) + strlen(argv[i]) +
  338.                 strlen(argv[argc - 1]) + 20;
  339.             if (!(bp = malloc(len)))
  340.                 nospace();
  341.             (void)snprintf(bp, len, "%s%s%s %s %s", _PATH_CP,
  342.                 iamrecursive ? " -r" : "", pflag ? " -p" : "",
  343.                 argv[i], argv[argc - 1]);
  344.             (void)susystem(bp);
  345.             (void)free(bp);
  346.             continue;
  347.         }
  348.         *src++ = 0;
  349.         if (*src == 0)
  350.             src = ".";
  351.         host = index(argv[i], '@');
  352.         if (host) {
  353.             *host++ = 0;
  354.             suser = argv[i];
  355.             if (*suser == '\0')
  356.                 suser = pwd->pw_name;
  357.             else if (!okname(suser))
  358.                 continue;
  359.         } else {
  360.             host = argv[i];
  361.             suser = pwd->pw_name;
  362.         }
  363.         len = strlen(src) + CMDNEEDS + 20;
  364.         if (!(bp = malloc(len)))
  365.             nospace();
  366.         (void)snprintf(bp, len, "%s -f %s", cmd, src);
  367. #ifdef KERBEROS
  368.         if (use_kerberos)
  369.             rem = kerberos(&host, bp, pwd->pw_name, suser);
  370.         else
  371. #endif
  372.             rem = rcmd(&host, port, pwd->pw_name, suser, bp, 0);
  373.         (void)free(bp);
  374.         if (rem < 0)
  375.             continue;
  376.         (void)seteuid(userid);
  377. #ifdef IP_TOS
  378.         tos = IPTOS_THROUGHPUT;
  379.         if (setsockopt(rem, IPPROTO_IP, IP_TOS,
  380.             (char *)&tos, sizeof(int)) < 0)
  381.             perror("rcp: setsockopt TOS (ignored)");
  382. #endif
  383.         sink(1, argv + argc - 1);
  384.         (void)seteuid(0);
  385.         (void)close(rem);
  386.         rem = -1;
  387.     }
  388. }
  389.  
  390. verifydir(cp)
  391.     char *cp;
  392. {
  393.     struct stat stb;
  394.  
  395.     if (stat(cp, &stb) >= 0) {
  396.         if ((stb.st_mode & S_IFMT) == S_IFDIR)
  397.             return;
  398.         errno = ENOTDIR;
  399.     }
  400.     error("rcp: %s: %s.\n", cp, strerror(errno));
  401.     exit(1);
  402. }
  403.  
  404. char *
  405. colon(cp)
  406.     register char *cp;
  407. {
  408.     for (; *cp; ++cp) {
  409.         if (*cp == ':')
  410.             return(cp);
  411.         if (*cp == '/')
  412.             return(0);
  413.     }
  414.     return(0);
  415. }
  416.  
  417. okname(cp0)
  418.     char *cp0;
  419. {
  420.     register char *cp = cp0;
  421.     register int c;
  422.  
  423.     do {
  424.         c = *cp;
  425.         if (c & 0200)
  426.             goto bad;
  427.         if (!isalpha(c) && !isdigit(c) && c != '_' && c != '-')
  428.             goto bad;
  429.     } while (*++cp);
  430.     return(1);
  431. bad:
  432.     (void)fprintf(stderr, "rcp: invalid user name %s\n", cp0);
  433.     return(0);
  434. }
  435.  
  436. susystem(s)
  437.     char *s;
  438. {
  439.     int status, pid, w;
  440.     register sig_t istat, qstat;
  441.  
  442.     if ((pid = vfork()) == 0) {
  443.         (void)setuid(userid);
  444.         execl(_PATH_BSHELL, "sh", "-c", s, (char *)0);
  445.         _exit(127);
  446.     }
  447.     istat = signal(SIGINT, SIG_IGN);
  448.     qstat = signal(SIGQUIT, SIG_IGN);
  449.     while ((w = wait(&status)) != pid && w != -1)
  450.         ;
  451.     if (w == -1)
  452.         status = -1;
  453.     (void)signal(SIGINT, istat);
  454.     (void)signal(SIGQUIT, qstat);
  455.     return(status);
  456. }
  457.  
  458. source(argc, argv)
  459.     int argc;
  460.     char **argv;
  461. {
  462.     struct stat stb;
  463.     static BUF buffer;
  464.     BUF *bp;
  465.     off_t i;
  466.     int x, readerr, f, amt;
  467.     char *last, *name, buf[BUFSIZ];
  468.     BUF *allocbuf();
  469.  
  470.     for (x = 0; x < argc; x++) {
  471.         name = argv[x];
  472.         if ((f = open(name, O_RDONLY, 0)) < 0) {
  473.             error("rcp: %s: %s\n", name, strerror(errno));
  474.             continue;
  475.         }
  476.         if (fstat(f, &stb) < 0)
  477.             goto notreg;
  478.         switch (stb.st_mode&S_IFMT) {
  479.  
  480.         case S_IFREG:
  481.             break;
  482.  
  483.         case S_IFDIR:
  484.             if (iamrecursive) {
  485.                 (void)close(f);
  486.                 rsource(name, &stb);
  487.                 continue;
  488.             }
  489.             /* FALLTHROUGH */
  490.         default:
  491. notreg:            (void)close(f);
  492.             error("rcp: %s: not a plain file\n", name);
  493.             continue;
  494.         }
  495.         last = rindex(name, '/');
  496.         if (last == 0)
  497.             last = name;
  498.         else
  499.             last++;
  500.         if (pflag) {
  501.             /*
  502.              * Make it compatible with possible future
  503.              * versions expecting microseconds.
  504.              */
  505.             (void)snprintf(buf, sizeof(buf),
  506.                 "T%ld 0 %ld 0\n", stb.st_mtime, stb.st_atime);
  507.             (void)write(rem, buf, (int)strlen(buf));
  508.             if (response() < 0) {
  509.                 (void)close(f);
  510.                 continue;
  511.             }
  512.         }
  513.         (void)snprintf(buf, sizeof(buf),
  514.             "C%04o %ld %s\n", stb.st_mode&07777, stb.st_size, last);
  515.         (void)write(rem, buf, (int)strlen(buf));
  516.         if (response() < 0) {
  517.             (void)close(f);
  518.             continue;
  519.         }
  520.         if ((bp = allocbuf(&buffer, f, BUFSIZ)) == 0) {
  521.             (void)close(f);
  522.             continue;
  523.         }
  524.         readerr = 0;
  525.         for (i = 0; i < stb.st_size; i += bp->cnt) {
  526.             amt = bp->cnt;
  527.             if (i + amt > stb.st_size)
  528.                 amt = stb.st_size - i;
  529.             if (readerr == 0 && read(f, bp->buf, amt) != amt)
  530.                 readerr = errno;
  531.             (void)write(rem, bp->buf, amt);
  532.         }
  533.         (void)close(f);
  534.         if (readerr == 0)
  535.             (void)write(rem, "", 1);
  536.         else
  537.             error("rcp: %s: %s\n", name, strerror(readerr));
  538.         (void)response();
  539.     }
  540. }
  541.  
  542. rsource(name, statp)
  543.     char *name;
  544.     struct stat *statp;
  545. {
  546.     DIR *dirp;
  547.     struct dirent *dp;
  548.     char *last, *vect[1], path[MAXPATHLEN];
  549.  
  550.     if (!(dirp = opendir(name))) {
  551.         error("rcp: %s: %s\n", name, strerror(errno));
  552.         return;
  553.     }
  554.     last = rindex(name, '/');
  555.     if (last == 0)
  556.         last = name;
  557.     else
  558.         last++;
  559.     if (pflag) {
  560.         (void)snprintf(path, sizeof(path),
  561.             "T%ld 0 %ld 0\n", statp->st_mtime, statp->st_atime);
  562.         (void)write(rem, path, (int)strlen(path));
  563.         if (response() < 0) {
  564.             closedir(dirp);
  565.             return;
  566.         }
  567.     }
  568.     (void)snprintf(path, sizeof(path),
  569.         "D%04o %d %s\n", statp->st_mode&07777, 0, last);
  570.     (void)write(rem, path, (int)strlen(path));
  571.     if (response() < 0) {
  572.         closedir(dirp);
  573.         return;
  574.     }
  575.     while (dp = readdir(dirp)) {
  576.         if (dp->d_ino == 0)
  577.             continue;
  578.         if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
  579.             continue;
  580.         if (strlen(name) + 1 + strlen(dp->d_name) >= MAXPATHLEN - 1) {
  581.             error("%s/%s: name too long.\n", name, dp->d_name);
  582.             continue;
  583.         }
  584.         (void)snprintf(path, sizeof(path), "%s/%s", name, dp->d_name);
  585.         vect[0] = path;
  586.         source(1, vect);
  587.     }
  588.     closedir(dirp);
  589.     (void)write(rem, "E\n", 2);
  590.     (void)response();
  591. }
  592.  
  593. response()
  594. {
  595.     register char *cp;
  596.     char ch, resp, rbuf[BUFSIZ];
  597.  
  598.     if (read(rem, &resp, sizeof(resp)) != sizeof(resp))
  599.         lostconn();
  600.  
  601.     cp = rbuf;
  602.     switch(resp) {
  603.     case 0:                /* ok */
  604.         return(0);
  605.     default:
  606.         *cp++ = resp;
  607.         /* FALLTHROUGH */
  608.     case 1:                /* error, followed by err msg */
  609.     case 2:                /* fatal error, "" */
  610.         do {
  611.             if (read(rem, &ch, sizeof(ch)) != sizeof(ch))
  612.                 lostconn();
  613.             *cp++ = ch;
  614.         } while (cp < &rbuf[BUFSIZ] && ch != '\n');
  615.  
  616.         if (!iamremote)
  617.             (void)write(2, rbuf, cp - rbuf);
  618.         ++errs;
  619.         if (resp == 1)
  620.             return(-1);
  621.         exit(1);
  622.     }
  623.     /*NOTREACHED*/
  624. }
  625.  
  626. void
  627. lostconn()
  628. {
  629.     if (!iamremote)
  630.         (void)fprintf(stderr, "rcp: lost connection\n");
  631.     exit(1);
  632. }
  633.  
  634. sink(argc, argv)
  635.     int argc;
  636.     char **argv;
  637. {
  638.     register char *cp;
  639.     static BUF buffer;
  640.     struct stat stb;
  641.     struct timeval tv[2];
  642.     enum { YES, NO, DISPLAYED } wrerr;
  643.     BUF *bp, *allocbuf();
  644.     off_t i, j;
  645.     char ch, *targ, *why;
  646.     int amt, count, exists, first, mask, mode;
  647.     int ofd, setimes, size, targisdir;
  648.     char *np, *vect[1], buf[BUFSIZ];
  649.  
  650. #define    atime    tv[0]
  651. #define    mtime    tv[1]
  652. #define    SCREWUP(str)    { why = str; goto screwup; }
  653.  
  654.     setimes = targisdir = 0;
  655.     mask = umask(0);
  656.     if (!pflag)
  657.         (void)umask(mask);
  658.     if (argc != 1) {
  659.         error("rcp: ambiguous target\n");
  660.         exit(1);
  661.     }
  662.     targ = *argv;
  663.     if (targetshouldbedirectory)
  664.         verifydir(targ);
  665.     (void)write(rem, "", 1);
  666.     if (stat(targ, &stb) == 0 && (stb.st_mode & S_IFMT) == S_IFDIR)
  667.         targisdir = 1;
  668.     for (first = 1;; first = 0) {
  669.         cp = buf;
  670.         if (read(rem, cp, 1) <= 0)
  671.             return;
  672.         if (*cp++ == '\n')
  673.             SCREWUP("unexpected <newline>");
  674.         do {
  675.             if (read(rem, &ch, sizeof(ch)) != sizeof(ch))
  676.                 SCREWUP("lost connection");
  677.             *cp++ = ch;
  678.         } while (cp < &buf[BUFSIZ - 1] && ch != '\n');
  679.         *cp = 0;
  680.  
  681.         if (buf[0] == '\01' || buf[0] == '\02') {
  682.             if (iamremote == 0)
  683.                 (void)write(2, buf + 1, (int)strlen(buf + 1));
  684.             if (buf[0] == '\02')
  685.                 exit(1);
  686.             errs++;
  687.             continue;
  688.         }
  689.         if (buf[0] == 'E') {
  690.             (void)write(rem, "", 1);
  691.             return;
  692.         }
  693.  
  694.         if (ch == '\n')
  695.             *--cp = 0;
  696.  
  697. #define getnum(t) (t) = 0; while (isdigit(*cp)) (t) = (t) * 10 + (*cp++ - '0');
  698.         cp = buf;
  699.         if (*cp == 'T') {
  700.             setimes++;
  701.             cp++;
  702.             getnum(mtime.tv_sec);
  703.             if (*cp++ != ' ')
  704.                 SCREWUP("mtime.sec not delimited");
  705.             getnum(mtime.tv_usec);
  706.             if (*cp++ != ' ')
  707.                 SCREWUP("mtime.usec not delimited");
  708.             getnum(atime.tv_sec);
  709.             if (*cp++ != ' ')
  710.                 SCREWUP("atime.sec not delimited");
  711.             getnum(atime.tv_usec);
  712.             if (*cp++ != '\0')
  713.                 SCREWUP("atime.usec not delimited");
  714.             (void)write(rem, "", 1);
  715.             continue;
  716.         }
  717.         if (*cp != 'C' && *cp != 'D') {
  718.             /*
  719.              * Check for the case "rcp remote:foo\* local:bar".
  720.              * In this case, the line "No match." can be returned
  721.              * by the shell before the rcp command on the remote is
  722.              * executed so the ^Aerror_message convention isn't
  723.              * followed.
  724.              */
  725.             if (first) {
  726.                 error("%s\n", cp);
  727.                 exit(1);
  728.             }
  729.             SCREWUP("expected control record");
  730.         }
  731.         mode = 0;
  732.         for (++cp; cp < buf + 5; cp++) {
  733.             if (*cp < '0' || *cp > '7')
  734.                 SCREWUP("bad mode");
  735.             mode = (mode << 3) | (*cp - '0');
  736.         }
  737.         if (*cp++ != ' ')
  738.             SCREWUP("mode not delimited");
  739.         size = 0;
  740.         while (isdigit(*cp))
  741.             size = size * 10 + (*cp++ - '0');
  742.         if (*cp++ != ' ')
  743.             SCREWUP("size not delimited");
  744.         if (targisdir) {
  745.             static char *namebuf;
  746.             static int cursize;
  747.             size_t need;
  748.  
  749.             need = strlen(targ) + strlen(cp) + 250;
  750.             if (need > cursize) {
  751.                 if (!(namebuf = malloc(need)))
  752.                     error("out of memory\n");
  753.             }
  754.             (void)snprintf(namebuf, need, "%s%s%s", targ,
  755.                 *targ ? "/" : "", cp);
  756.             np = namebuf;
  757.         }
  758.         else
  759.             np = targ;
  760.         exists = stat(np, &stb) == 0;
  761.         if (buf[0] == 'D') {
  762.             if (exists) {
  763.                 if ((stb.st_mode&S_IFMT) != S_IFDIR) {
  764.                     errno = ENOTDIR;
  765.                     goto bad;
  766.                 }
  767.                 if (pflag)
  768.                     (void)chmod(np, mode);
  769.             } else if (mkdir(np, mode) < 0)
  770.                 goto bad;
  771.             vect[0] = np;
  772.             sink(1, vect);
  773.             if (setimes) {
  774.                 setimes = 0;
  775.                 if (utimes(np, tv) < 0)
  776.                     error("rcp: can't set times on %s: %s\n",
  777.                     np, strerror(errno));
  778.             }
  779.             continue;
  780.         }
  781.         if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
  782. bad:            error("rcp: %s: %s\n", np, strerror(errno));
  783.             continue;
  784.         }
  785.         if (exists && pflag)
  786.             (void)fchmod(ofd, mode);
  787.         (void)write(rem, "", 1);
  788.         if ((bp = allocbuf(&buffer, ofd, BUFSIZ)) == 0) {
  789.             (void)close(ofd);
  790.             continue;
  791.         }
  792.         cp = bp->buf;
  793.         count = 0;
  794.         wrerr = NO;
  795.         for (i = 0; i < size; i += BUFSIZ) {
  796.             amt = BUFSIZ;
  797.             if (i + amt > size)
  798.                 amt = size - i;
  799.             count += amt;
  800.             do {
  801.                 j = read(rem, cp, amt);
  802.                 if (j <= 0) {
  803.                     error("rcp: %s\n",
  804.                         j ? strerror(errno) :
  805.                         "dropped connection");
  806.                     exit(1);
  807.                 }
  808.                 amt -= j;
  809.                 cp += j;
  810.             } while (amt > 0);
  811.             if (count == bp->cnt) {
  812.                 if (wrerr == NO &&
  813.                     write(ofd, bp->buf, count) != count)
  814.                     wrerr = YES;
  815.                 count = 0;
  816.                 cp = bp->buf;
  817.             }
  818.         }
  819.         if (count != 0 && wrerr == NO &&
  820.             write(ofd, bp->buf, count) != count)
  821.             wrerr = YES;
  822.         if (ftruncate(ofd, size)) {
  823.             error("rcp: can't truncate %s: %s\n", np,
  824.                 strerror(errno));
  825.             wrerr = DISPLAYED;
  826.         }
  827.         (void)close(ofd);
  828.         (void)response();
  829.         if (setimes && wrerr == NO) {
  830.             setimes = 0;
  831.             if (utimes(np, tv) < 0) {
  832.                 error("rcp: can't set times on %s: %s\n",
  833.                     np, strerror(errno));
  834.                 wrerr = DISPLAYED;
  835.             }
  836.         }
  837.         switch(wrerr) {
  838.         case YES:
  839.             error("rcp: %s: %s\n", np, strerror(errno));
  840.             break;
  841.         case NO:
  842.             (void)write(rem, "", 1);
  843.             break;
  844.         case DISPLAYED:
  845.             break;
  846.         }
  847.     }
  848. screwup:
  849.     error("rcp: protocol screwup: %s\n", why);
  850.     exit(1);
  851. }
  852.  
  853. BUF *
  854. allocbuf(bp, fd, blksize)
  855.     BUF *bp;
  856.     int fd, blksize;
  857. {
  858.     struct stat stb;
  859.     size_t size;
  860.  
  861.     if (fstat(fd, &stb) < 0) {
  862.         error("rcp: fstat: %s\n", strerror(errno));
  863.         return(0);
  864.     }
  865.     size = roundup(stb.st_blksize, blksize);
  866.     if (size == 0)
  867.         size = blksize;
  868.     if (bp->cnt < size) {
  869.         if (bp->buf != 0)
  870.             free(bp->buf);
  871.         bp->buf = malloc(size);
  872.         if (!bp->buf) {
  873.             error("rcp: malloc: out of memory\n");
  874.             return(0);
  875.         }
  876.     }
  877.     bp->cnt = size;
  878.     return(bp);
  879. }
  880.  
  881. /* VARARGS1 */
  882. error(fmt, a1, a2, a3)
  883.     char *fmt;
  884.     int a1, a2, a3;
  885. {
  886.     static FILE *fp;
  887.  
  888.     ++errs;
  889.     if (!fp && !(fp = fdopen(rem, "w")))
  890.         return;
  891.     (void)fprintf(fp, "%c", 0x01);
  892.     (void)fprintf(fp, fmt, a1, a2, a3);
  893.     (void)fflush(fp);
  894.     if (!iamremote)
  895.         (void)fprintf(stderr, fmt, a1, a2, a3);
  896. }
  897.  
  898. nospace()
  899. {
  900.     (void)fprintf(stderr, "rcp: out of memory.\n");
  901.     exit(1);
  902. }
  903.  
  904.  
  905. usage()
  906. {
  907. #ifdef KERBEROS
  908. #ifdef CRYPT
  909.     (void)fprintf(stderr, "%s\n\t%s\n",
  910.         "usage: rcp [-k realm] [-px] f1 f2",
  911.         "or: rcp [-k realm] [-rpx] f1 ... fn directory");
  912. #else
  913.     (void)fprintf(stderr, "%s\n\t%s\n",
  914.         "usage: rcp [-k realm] [-p] f1 f2",
  915.         "or: rcp [-k realm] [-rp] f1 ... fn directory");
  916. #endif
  917. #else
  918.     (void)fprintf(stderr,
  919.         "usage: rcp [-p] f1 f2; or: rcp [-rp] f1 ... fn directory\n");
  920. #endif
  921.     exit(1);
  922. }
  923.  
  924. #ifdef KERBEROS
  925. old_warning(str)
  926.     char *str;
  927. {
  928.     (void)fprintf(stderr, "rcp: warning: %s, using standard rcp\n", str);
  929. }
  930.  
  931. int
  932. kerberos(host, bp, locuser, user)
  933.  
  934.     char **host, *bp, *locuser, *user;
  935. {
  936.     struct servent *sp;
  937.  
  938. again:
  939.     if (use_kerberos) {
  940.         rem = KSUCCESS;
  941.         errno = 0;
  942.         if (dest_realm == NULL)
  943.             dest_realm = krb_realmofhost(*host);
  944.  
  945. #ifdef CRYPT
  946.         if (doencrypt)
  947.             rem = krcmd_mutual(
  948.                 host, port,
  949.                 user, bp, 0,
  950.                     dest_realm,
  951.                 &cred, schedule);
  952.         else
  953. #endif
  954.             rem = krcmd(
  955.                 host, port,
  956.                 user, bp, 0, dest_realm);
  957.  
  958.         if (rem < 0) {
  959.             use_kerberos = 0;
  960.             sp = getservbyname("shell", "tcp");
  961.             if (sp == NULL) {
  962.                 (void)fprintf(stderr,
  963.                         "rcp: unknown service shell/tcp\n");
  964.                 exit(1);
  965.             }
  966.             if (errno == ECONNREFUSED)
  967.                 old_warning(
  968.                     "remote host doesn't support Kerberos");
  969.  
  970.             if (errno == ENOENT)
  971.                 old_warning(
  972.                     "Can't provide Kerberos auth data");
  973.             port = sp->s_port;
  974.             goto again;
  975.         }
  976.     } else {
  977. #ifdef CRYPT
  978.         if (doencrypt) {
  979.             fprintf(stderr,
  980.                 "The -x option requires Kerberos authentication\n");
  981.             exit(1);
  982.         }
  983. #endif
  984.         rem = rcmd(host, sp->s_port, locuser, user, bp, 0);
  985.     }
  986.     return(rem);
  987. }
  988. #endif /* KERBEROS */
  989.