home *** CD-ROM | disk | FTP | other *** search
/ Columbia Kermit / kermit.zip / archives / ckl197.zip / ckcfn2.c < prev    next >
C/C++ Source or Header  |  1999-12-30  |  98KB  |  3,192 lines

  1. /*  C K C F N 2  --  System-independent Kermit protocol support functions... */
  2.  
  3. /*  ...Part 2 (continued from ckcfns.c)  */
  4.  
  5. /*
  6.   Author: Frank da Cruz <fdc@columbia.edu>,
  7.   Columbia University Academic Information Systems, New York City.
  8.  
  9.   Copyright (C) 1985, 2000,
  10.     Trustees of Columbia University in the City of New York.
  11.     All rights reserved.  See the C-Kermit COPYING.TXT file or the
  12.     copyright text in the ckcmai.c module for disclaimer and permissions.
  13. */
  14. /*
  15.  Note -- if you change this file, please amend the version number and date at
  16.  the top of ckcfns.c accordingly.
  17. */
  18.  
  19. #include "ckcsym.h"            /* Compilation options */
  20. #include "ckcdeb.h"            /* Debugging and other symbols */
  21. #include "ckcasc.h"            /* ASCII symbols */
  22. #include "ckcker.h"            /* Kermit symbols */
  23. #include "ckcxla.h"            /* Translation */
  24. #include "ckcnet.h"            /* IKS and VMS #define TCPSOCKET */
  25.  
  26. #ifdef TCPSOCKET            /* For TELNET business in spack() */
  27. extern int tn_nlm, ttnproto, tn_b_nlm;
  28. #endif /* TCPSOCKET */
  29.  
  30. extern int parity, network, local, interrupted, fatalio, wasclosed;
  31.  
  32. int kstartactive = 0;            /* Flag for kstart() in a packet */
  33.  
  34. static CHAR p_tbl[] = {            /* Even parity table for dopar(). */
  35.     (CHAR) '\000',            /* ANSI C casts '\ooo' constants  */
  36.     (CHAR) '\201',            /* to signed char, so we have to  */
  37.     (CHAR) '\202',            /* cast back to unsigned char...  */
  38.     (CHAR) '\003',
  39.     (CHAR) '\204',
  40.     (CHAR) '\005',
  41.     (CHAR) '\006',
  42.     (CHAR) '\207',
  43.     (CHAR) '\210',
  44.     (CHAR) '\011',
  45.     (CHAR) '\012',
  46.     (CHAR) '\213',
  47.     (CHAR) '\014',
  48.     (CHAR) '\215',
  49.     (CHAR) '\216',
  50.     (CHAR) '\017',
  51.     (CHAR) '\220',
  52.     (CHAR) '\021',
  53.     (CHAR) '\022',
  54.     (CHAR) '\223',
  55.     (CHAR) '\024',
  56.     (CHAR) '\225',
  57.     (CHAR) '\226',
  58.     (CHAR) '\027',
  59.     (CHAR) '\030',
  60.     (CHAR) '\231',
  61.     (CHAR) '\232',
  62.     (CHAR) '\033',
  63.     (CHAR) '\234',
  64.     (CHAR) '\035',
  65.     (CHAR) '\036',
  66.     (CHAR) '\237',
  67.     (CHAR) '\240',
  68.     (CHAR) '\041',
  69.     (CHAR) '\042',
  70.     (CHAR) '\243',
  71.     (CHAR) '\044',
  72.     (CHAR) '\245',
  73.     (CHAR) '\246',
  74.     (CHAR) '\047',
  75.     (CHAR) '\050',
  76.     (CHAR) '\251',
  77.     (CHAR) '\252',
  78.     (CHAR) '\053',
  79.     (CHAR) '\254',
  80.     (CHAR) '\055',
  81.     (CHAR) '\056',
  82.     (CHAR) '\257',
  83.     (CHAR) '\060',
  84.     (CHAR) '\261',
  85.     (CHAR) '\262',
  86.     (CHAR) '\063',
  87.     (CHAR) '\264',
  88.     (CHAR) '\065',
  89.     (CHAR) '\066',
  90.     (CHAR) '\267',
  91.     (CHAR) '\270',
  92.     (CHAR) '\071',
  93.     (CHAR) '\072',
  94.     (CHAR) '\273',
  95.     (CHAR) '\074',
  96.     (CHAR) '\275',
  97.     (CHAR) '\276',
  98.     (CHAR) '\077',
  99.     (CHAR) '\300',
  100.     (CHAR) '\101',
  101.     (CHAR) '\102',
  102.     (CHAR) '\303',
  103.     (CHAR) '\104',
  104.     (CHAR) '\305',
  105.     (CHAR) '\306',
  106.     (CHAR) '\107',
  107.     (CHAR) '\110',
  108.     (CHAR) '\311',
  109.     (CHAR) '\312',
  110.     (CHAR) '\113',
  111.     (CHAR) '\314',
  112.     (CHAR) '\115',
  113.     (CHAR) '\116',
  114.     (CHAR) '\317',
  115.     (CHAR) '\120',
  116.     (CHAR) '\321',
  117.     (CHAR) '\322',
  118.     (CHAR) '\123',
  119.     (CHAR) '\324',
  120.     (CHAR) '\125',
  121.     (CHAR) '\126',
  122.     (CHAR) '\327',
  123.     (CHAR) '\330',
  124.     (CHAR) '\131',
  125.     (CHAR) '\132',
  126.     (CHAR) '\333',
  127.     (CHAR) '\134',
  128.     (CHAR) '\335',
  129.     (CHAR) '\336',
  130.     (CHAR) '\137',
  131.     (CHAR) '\140',
  132.     (CHAR) '\341',
  133.     (CHAR) '\342',
  134.     (CHAR) '\143',
  135.     (CHAR) '\344',
  136.     (CHAR) '\145',
  137.     (CHAR) '\146',
  138.     (CHAR) '\347',
  139.     (CHAR) '\350',
  140.     (CHAR) '\151',
  141.     (CHAR) '\152',
  142.     (CHAR) '\353',
  143.     (CHAR) '\154',
  144.     (CHAR) '\355',
  145.     (CHAR) '\356',
  146.     (CHAR) '\157',
  147.     (CHAR) '\360',
  148.     (CHAR) '\161',
  149.     (CHAR) '\162',
  150.     (CHAR) '\363',
  151.     (CHAR) '\164',
  152.     (CHAR) '\365',
  153.     (CHAR) '\366',
  154.     (CHAR) '\167',
  155.     (CHAR) '\170',
  156.     (CHAR) '\371',
  157.     (CHAR) '\372',
  158.     (CHAR) '\173',
  159.     (CHAR) '\374',
  160.     (CHAR) '\175',
  161.     (CHAR) '\176',
  162.     (CHAR) '\377'
  163. };
  164.  
  165. /*  D O P A R  --  Add an appropriate parity bit to a character  */
  166.  
  167. CHAR
  168. #ifdef CK_ANSIC
  169. dopar(register CHAR ch)
  170. #else
  171. dopar(ch) register CHAR ch;
  172. #endif /* CK_ANSIC */
  173.     {
  174.     register unsigned int a;
  175.     if (!parity
  176. #ifdef TCPSOCKET
  177.         || (network && (ttnproto == NP_TELNET) && (TELOPT_ME(TELOPT_BINARY)))
  178. #ifndef NOXFER
  179.     || (!local && sstelnet)        /* TELNET BINARY MODE */
  180. #endif /* NOXFER */
  181. #endif /* TCPSOCKET */
  182.         ) return((CHAR) (ch & 255)); else a = ch & 127;
  183.     switch (parity) {
  184.     case 'e':  return(p_tbl[a]);                 /* Even */
  185.     case 'm':  return((CHAR) (a | 128));         /* Mark */
  186.     case 'o':  return((CHAR) (p_tbl[a] ^ 128));  /* Odd */
  187.     case 's':  return((CHAR) a);                 /* Space */
  188.     default:   return((CHAR) a);                 /* Something illegal */
  189.     }
  190. }
  191.  
  192. #ifndef NOXFER                /* Rest of this file... */
  193.  
  194. #define NEWDPL                /* New dynamic packet length method */
  195.  
  196. #ifdef VMS
  197. extern int batch;
  198. #else
  199. extern int backgrd;
  200. #endif /* VMS */
  201.  
  202. #ifdef DYNAMIC
  203. extern struct pktinfo *s_pkt;        /* array of pktinfo structures */
  204. extern struct pktinfo *r_pkt;        /* array of pktinfo structures */
  205. #else
  206. extern struct pktinfo s_pkt[];        /* array of pktinfo structures */
  207. extern struct pktinfo r_pkt[];        /* array of pktinfo structures */
  208. #endif /* DYNAMIC */
  209.  
  210. extern int sseqtbl[], rseqtbl[], sbufuse[], sacktbl[], wslots, winlo,
  211.   sbufnum, rbufnum, pktpaus, reliable;
  212.  
  213. #ifdef STREAMING
  214. static int dontsend = 0;
  215. extern int streaming;
  216. #endif /* STREAMING */
  217.  
  218. extern int ttprty;            /* from ck*tio.c */
  219. extern int autopar;
  220.  
  221. extern int spsiz, spmax, rpsiz, timint, timef, npad, bestlen, maxsend;
  222. extern int rpt, rptq, rptflg, capas, spsizf, en_fin, tsecs, flow;
  223. extern int pktnum, sndtyp, rcvtyp, bctr, bctu, bctl, rsn, rln, maxtry, size;
  224. extern int osize, maxsize, spktl, rpktl, nfils, stdouf, fsecs;
  225. extern int turn, turnch, displa, pktlog, seslog, xflg, mypadn;
  226. extern int hcflg, server, cxseen, czseen, discard, slostart;
  227. extern int nakstate, quiet, success, xitsta, what, filestatus;
  228. extern int spackets, rpackets, timeouts, retrans, crunched, urpsiz;
  229. extern int carrier, fdispla, srvidl;
  230.  
  231. #ifdef GFTIMER
  232. extern CKFLOAT fptsecs, fpfsecs, fpxfsecs;
  233. #endif /* GFTIMER */
  234.  
  235. extern long filcnt, filrej, ffc, flci, flco, tlci, tlco, tfc, speed;
  236. extern long filcps, tfcps;
  237.  
  238. extern char *cmarg, filnam[];
  239.  
  240. extern CHAR padch, mypadc, eol, seol, ctlq, sstate;
  241. extern CHAR *recpkt, *data, myinit[];
  242. extern CHAR *srvptr, stchr, mystch, *rdatap;
  243. extern CHAR padbuf[];
  244. extern CHAR * epktmsg;
  245. extern int epktrcvd, epktsent;
  246.  
  247. #ifdef OS2                /* AUTODOWNLOAD parameters */
  248. extern int adl_kmode, adl_zmode;    /* Match Packet to signal download */
  249. extern char * adl_kstr;            /* KERMIT Download String */
  250. extern char * adl_zstr;            /* ZMODEM Download String */
  251. #endif /* OS2 */
  252.  
  253. #ifdef CK_AUTODL
  254. CHAR ksbuf[96] = { NUL, NUL };        /* Autodownload "Kermit Start" buf */
  255. #endif /* CK_AUTODL */
  256.  
  257. int numerrs = 0;            /* Number of packet errors so far */
  258. int rcvtimo = 0;            /* Timeout for receiving a packet */
  259. int idletmo = 0;            /* Flag for idle timeout */
  260.  
  261. long filcps = 0L;            /* CPS most recent file transferred */
  262. long tfcps  = 0L;            /* CPS most recent transaction */
  263. long xfsecs = 0L;            /* Elapsed time for most recent file */
  264. #ifdef GFTIMER
  265. CKFLOAT fpxfsecs = 0.0;            /* Ditto, but floating point */
  266. #endif /* GFTIMER */
  267.  
  268. #ifdef CK_TIMERS
  269. int rrttbl[64], srttbl[64];        /* Packet timestamp tables */
  270. extern int rttflg;
  271. #define RTT_SCALE 1000
  272. long
  273.   rttsamples,                /* Round trip time samples */
  274.   rttdelay,                /* RTT delay */
  275.   pktintvl,                /* Interpacket arrival time */
  276.   rttvariance,                /* RTT variance */
  277.   rttstddev;                /* RTT standard deviation */
  278. #endif /* CK_TIMERS */
  279.  
  280. /* CRC generation tables */
  281.  
  282. long crcta[16] = { 0L, 010201L, 020402L, 030603L, 041004L,
  283.   051205L, 061406L, 071607L, 0102010L, 0112211L, 0122412L, 0132613L, 0143014L,
  284.   0153215L, 0163416L, 0173617L
  285. };
  286.  
  287. long crctb[16] = { 0L, 010611L, 021422L, 031233L, 043044L,
  288.   053655L, 062466L, 072277L, 0106110L, 0116701L, 0127532L, 0137323L, 0145154L,
  289.   0155745L, 0164576L, 0174367L
  290. };
  291.  
  292. #ifdef CK_TIMERS
  293. /*
  294.   Round-trip timer calculations adapted from Tim Kientzle's article,
  295.   "Improving Kermit Performance", Dr Dobb's Journal, February 1996.
  296. */
  297.  
  298.  
  299. /*  R T T I N I T  --  Initialize timers at start of transaction  */
  300.  
  301. VOID
  302. rttinit() {                /* Initialize round-trip timing */
  303.     int i;
  304.  
  305.     if (timint == 0)
  306.       return;
  307.  
  308.     rttsamples  = 0L;            /* Samples (packets) */
  309.     rttvariance = 0L;            /* Variance in delay */
  310.     rttdelay    = (long) timint * RTT_SCALE; /* Delay */
  311.     pktintvl    = (long) timint * RTT_SCALE; /* Delay */
  312.     rttstddev   = (long) timint * RTT_SCALE; /* Standard deviation of delay */
  313.  
  314.     /* Tables of timestamps indexed by packet sequence number */
  315.  
  316.     for (i = 0; i < 64; i++) {
  317.     rrttbl[i] = -1;            /* Time each packet was received */
  318.     srttbl[i] = -1;            /* Time each packet was sent */
  319.     }
  320.     rcvtimo = timint;            /* Initial timeout is what user said */
  321. }
  322.  
  323. /*  G E T R T T  --  Get packet round trip time  */
  324. /*
  325.   Call with nakstate == 0 if file sender, nonzero if receiver,
  326.   and n == packet sequence number of the packet we just received.
  327.  
  328.   Returns:
  329.   -1 on failure with rcvtimo set to timint (what the user said), or:
  330.    0 on success with rcvtimo set to dynamically calculated value:
  331.      1 <= rcvtimo <= timint * 3.
  332. */
  333. int
  334. getrtt(nakstate, n) int nakstate, n; {
  335.     long rttdiff;
  336.     extern int mintime, maxtime;
  337.  
  338.     int x, y, yy, z = 0, zz = 0;    /* How long did it take to get here? */
  339.  
  340.     rcvtimo = timint;            /* Default timeout is what user said */
  341.  
  342.     if (timint == 0)            /* We're not timing out. */
  343.       return(0);
  344.  
  345.     if (!rttflg)            /* Not supposed to be doing this? */
  346.       return(-1);            /*  So don't */
  347.  
  348.     if (!RTT_SCALE)            /* Paranoia... */
  349.       return(-1);
  350.  
  351.     /* rtimer() (reset timer) is not called until 1st data packet */
  352. #ifdef GFTIMER
  353.     /* rftimer(); */
  354. #endif /* GFTIMER */
  355.     /* S (F [ A ] D* Z)* B */
  356.  
  357.     /* NOTE: we calculate both the round-trip time AND the packet */
  358.     /* arrival rate.  We don't use the RTT for anything, we just display it. */
  359.     /* Timeouts are based on the packet arrival rate. */
  360.  
  361.     if (spackets > 3) {            /* Don't start till 4th packet */
  362.     if (nakstate) {            /* File receiver */
  363.         x = rrttbl[n];             /* Time when I got packet n */
  364.         y = rrttbl[n > 0 ? n - 1 : 63];  /* Time when I got packet n-1 */
  365.         yy = srttbl[n > 0 ? n - 1 : 63]; /* Time when I sent ACK(n-1) */
  366.         if (x > -1 && y > -1) {    /* Be careful */
  367.         z = x - y;        /* Packet rate */
  368.         zz = x - yy;        /* Round trip time */
  369.         debug(F101,"RTT RECV","",z);
  370.         } else {            /* This shouldn't happen */
  371.         debug(F101,"RTT RECV ERROR spackets","",spackets);
  372.         debug(F101,"RTT RECV ERROR sequence","",n);
  373.         return(-1);
  374.         }
  375.     } else {            /* File sender */
  376.         x = rrttbl[n];        /* Time when I got ACK(n) */
  377.         y = rrttbl[n > 0 ? n - 1 : 63]; /* Time when I got packet n-1 */
  378.         yy = srttbl[n];        /* Time when I sent n */
  379.         if (x > -1 && y > -1) {
  380.         z = x - y;        /* Packet rate */
  381.         zz = x - yy;        /* Round trip time */
  382.         debug(F101,"RTT SEND","",z);
  383.         } else {
  384.         debug(F100,"RTT SEND ERROR","",0);
  385.         return(-1);
  386.         }
  387.     }
  388.     if (z < 1)            /* For fast connections */
  389.       z = RTT_SCALE / 2;        /* Convert to scale... */
  390.     else
  391.       z *= RTT_SCALE;
  392.  
  393.     if (zz < 1)            /* For fast connections */
  394.       zz = RTT_SCALE / 2;        /* Convert to scale... */
  395.     else
  396.       zz *= RTT_SCALE;
  397.  
  398.     rttdelay = zz;            /* Round trip time of this packet */
  399.     if (rttsamples++ == 0L) {    /* First sample */
  400.         pktintvl = z;
  401.         rttdiff = 0;
  402.     } else {            /* Subsequent samples */
  403.         long oldavg = pktintvl;
  404.         long rttdiffsq;
  405.  
  406.         if (rttsamples > 30)    /* Use real average for first 30 */
  407.           rttsamples = 30;        /*  then decaying average. */
  408.  
  409.         /* Average delay, difference squared, variance, std deviation */
  410.  
  411.         pktintvl += (z - pktintvl) / rttsamples;
  412.         rttdiffsq = (z - oldavg) * (z - oldavg);
  413.         rttvariance += (rttdiffsq - rttvariance) / rttsamples;
  414.         debug(F101,"RTT stddev1","",rttstddev);
  415.         if (rttstddev < 1L)        /* It can be zero, in which case */
  416.           rttstddev = RTT_SCALE / 3; /* set it to something small... */
  417.         rttstddev = (rttstddev + rttvariance / rttstddev) / 2;
  418.     }
  419.     debug(F101,"RTT stddev2","",rttstddev);
  420.     debug(F101,"RTT delay  ","",pktintvl);
  421.     rcvtimo = (pktintvl + (3L * rttstddev)) / RTT_SCALE + 1;
  422.     if (rpackets < 32)        /* Allow for slow start */
  423.       rcvtimo += rcvtimo + 2;
  424.     else if (rpackets < 64)
  425.       rcvtimo += rcvtimo / 2 + 1;
  426.         /* On a reliable link, don't try too hard to time out. */
  427.     /* Especially on fast local network connections. */
  428.         if (server && what == W_NOTHING) /* Server command wait */
  429.       rcvtimo = rcvtimo;        /* == srvtim */
  430.         else if (reliable == SET_ON && rcvtimo > 0) /* Reliable */
  431.       rcvtimo = rcvtimo +15;    /* and not server command wait */
  432.         else                            /* Not reliable or server cmd wait */
  433.       rcvtimo = rcvtimo;
  434.     if (rcvtimo < mintime)        /* Lower bound */
  435.       rcvtimo = mintime;
  436.     if (maxtime > 0) {        /* User specified an upper bound */
  437.         if (rcvtimo > maxtime)
  438.           rcvtimo = maxtime;
  439.     } else if (maxtime == 0) {    /* User didn't specify */
  440.         if (rcvtimo > timint * 6)
  441.           rcvtimo = timint * 6;
  442.     }
  443.     debug(F101,"RTT rcvtimo","",rcvtimo);
  444.     }
  445.     return(0);
  446. }
  447. #endif /* CK_TIMERS */
  448.  
  449. /*  I N P U T  --  Attempt to read packet number 'pktnum'.  */
  450.  
  451. /*
  452.  This is the function that feeds input to Kermit's finite state machine,
  453.  in the form of a character in the range 32-126, normally a packet type
  454.  (uppercase letter) or pseudo-packet-type (lowercase letter).
  455.  
  456.  If a special start state is in effect, that state is returned as if it were
  457.  the type of an incoming packet.
  458. */
  459. int
  460. input() {
  461.     int type = 0, acktype;        /* Received packet type */
  462.     int x, y, k;            /* Workers */
  463.     int z, pi, nf;            /* Worker, packet index, NAK flag */
  464.     int nak2ack = 0;
  465.  
  466.     debug(F000,"input sstate","",sstate);
  467.     debug(F101,"input nakstate","",nakstate);
  468.     debug(F000,"input sndtyp","",sndtyp);
  469.     debug(F101,"input xitsta","",xitsta);
  470.     debug(F101,"input what","",what);
  471.  
  472.     while (1) {                /* Big loop... */
  473. /*
  474.   It is ttchk()'s responsibility to tell us if the connection is broken,
  475.   and to do so instantly and nondestructively -- no blocking, etc, that would
  476.   slow down file transfer.
  477. */
  478.     if (ttchk() < 0) {
  479.         debug(F100,"input CONNECTION BROKEN","",0);
  480.         fatalio = 1;
  481.         return('q');
  482.     }
  483.     if (sstate != 0) {        /* If a start state is in effect, */
  484.         type = sstate;        /* return it like a packet type, */
  485.         sstate = 0;            /* and then nullify it. */
  486.         numerrs = 0;        /* (PWP) no errors so far */
  487.         return(type);
  488.     }
  489.     if (nakstate) {            /* This section for file receiver. */
  490.         if (wslots > 1) {        /* If we're doing windows, */
  491.         x = rseqtbl[winlo];    /* see if desired packet already in. */
  492.         debug(F101,"input winlo","",winlo);
  493.         debug(F101,"input rseqtbl[winlo]","",rseqtbl[winlo]);
  494.         if (x > -1) {        /* Already there? */
  495.             if (r_pkt[x].pk_seq == winlo) { /* (double check) */
  496.             rsn = winlo;                /* Yes, return its info */
  497.             debug(F101,"input return pre-stashed packet","",rsn);
  498.             dumprbuf();
  499.             rdatap = r_pkt[x].pk_adr;   /* like rpack would do. */
  500.             rln = (int)strlen((char *) rdatap);
  501.             type = r_pkt[x].pk_typ;
  502.             break;
  503.             }
  504.         }
  505.         }
  506.         type = rpack();            /* Try to read a packet. */
  507.         debug(F101,"input rpack","",type);
  508.  
  509.         while (type == 'e') {    /* Handle echoes */
  510.         debug(F101,"input echo discarded","",type);
  511.         type = rpack();
  512.         }
  513. #ifdef DEBUG
  514.         if (deblog) {
  515.         if (type == 'D')
  516.           debug(F011,"input type D=",(char *)rdatap,39);
  517.         else
  518.           debug(F000,"input type",(char *)rdatap,type);
  519.         }
  520. #endif /* DEBUG */
  521. #ifndef OLDCHKINT
  522.         if (type == 'z') {
  523.         epktrcvd = 1;
  524.         errpkt((CHAR *)"User cancelled.");
  525.         type = 'E';
  526.         break;
  527.         }
  528. #endif /* OLDCHKINT */
  529.         if (type < -1) {
  530.         char * s;
  531.         s = (type == -2) ?
  532.           "FAILED - Interrupted" :
  533.             "FAILED - Connection lost";
  534.  
  535.         xxscreen(SCR_PT,'q',0L,s);
  536.         debug(F111,"XXX wasclosed",s,wasclosed);
  537. #ifdef CKLOGDIAL
  538.         dologend();
  539. #endif /* CKLOGDIAL */
  540.         return('q');        /* Ctrl-C or connection lost */
  541.         }
  542.         if (type < 0) {        /* Receive window full */
  543.         /* Another thing to do here would be to delete */
  544.         /* the highest packet and NAK winlo.  But that */
  545.         /* shouldn't be necessary since the other Kermit */
  546.         /* should not have sent a packet outside the window. */
  547.         debug(F101,"rpack receive window full","",0);
  548.         dumprbuf();
  549.         errpkt((CHAR *)"Receive window full.");
  550.         type = 'E';
  551.         break;
  552.         }
  553.         dumprbuf();
  554.  
  555. #ifdef OLDCHKINT
  556.         if (chkint() < 0) {        /* Check for console interrupts. */
  557.         errpkt((CHAR *)"User cancelled."); /* (old way) */
  558.         type = 'E';
  559.         break;
  560.         }
  561. #endif /* OLDCHKINT */
  562.  
  563. #ifdef STREAMING
  564.         if (streaming) {        /* Streaming */
  565.         if (type == 'Q' || type == 'T') { /* Errors are fatal. */
  566.             crunched++;        /* For statistics */
  567.             errpkt((CHAR *)"Transmission error on reliable link.");
  568.             type = 'E';
  569.         }
  570.         }
  571. #endif /* STREAMING */
  572.         if (type == 'E') {
  573.         debug(F101,"input got E, nakstate","",nakstate);
  574.         break;            /* Error packet */
  575.         }
  576.         if (type == 'Q') {        /* Crunched packet. */
  577.         crunched++;
  578.         numerrs++;
  579. /*
  580.   Packet arrived damaged.  It was most likely the packet we were expecting
  581.   next, so we send a NAK for that packet.  Prior to 5A(189), we always
  582.   NAK'd winlo here, but that was bad because if two (or more) different
  583.   packets were damaged, we would keep NAKing the first one and never NAK the
  584.   other ones, which could result in a lengthy series of timeouts.  Now we
  585.   NAK the oldest as-yet-unNAK'd missing packet.
  586. */
  587. #ifdef CK_TIMERS
  588.         rcvtimo++;        /* Stretch the timeout a little */
  589. #endif /* CK_TIMERS */
  590.         z = (winlo + wslots) % 64;  /* Search from winlo to z */
  591.         debug(F101,"ZZZ crunched z","",z);
  592.         nf = 0;                /* NAK flag not set yet */
  593.         for (x = winlo; x != z; x = (x + 1) % 64) {
  594.             debug(F101,"ZZZ x","",x);
  595.             if (rseqtbl[x] > -1) /* Have I received packet x? */
  596.               continue;         /* Yes, go on. */
  597.             debug(F101,"ZZZ x not recd yet","",x);
  598.             pi = sseqtbl[x];     /* No, have I NAK'd it yet? */
  599.             if (pi < 0 || s_pkt[pi].pk_rtr == 0) {
  600.             debug(F101,"ZZZ x not NAK'd yet","",x);
  601.             nack(x);     /* No, NAK it now. */
  602.             nf = 1;         /* Flag that I did. */
  603.             break;
  604.             }
  605.         }
  606.         if (!nf) {        /* If we didn't NAK anything above, */
  607.             debug(F101,"ZZZ NAKing winlo","",winlo);
  608.             if (nack(winlo) < 0) { /* we have to NAK winlo (again) */
  609.             errpkt((CHAR *)"Too many retries."); /* Too many */
  610.             type = 'E';
  611.             break;
  612.             }
  613.         }
  614.         continue;
  615.         }
  616.  
  617.         if (type == 'T') {        /* Timeout */
  618. #ifndef OS2
  619.         /* K95 does this its own way */
  620.         if (server && srvidl) {
  621.             idletmo = 1;
  622.             debug(F101,"SERVER IDLE TIMEOUT","",srvidl);
  623.             return('q');
  624.         }
  625. #endif /* OS2 */
  626. #ifdef CK_TIMERS
  627.         rcvtimo++;        /* Stretch the timeout a little */
  628. #endif /* CK_TIMERS */
  629.         timeouts++;
  630.         debug(F101,"input receive-state timeout, winlo","",winlo);
  631.         /* NAK only the packet at window-low */
  632.         debug(F101,"input sending NAK for winlo","",winlo);
  633.         x = ttchk();
  634.         if (x > 0)        /* Don't give up if there is still */
  635.           continue;        /* something to read. */
  636.         else if (x < 0) {
  637. #ifdef CKLOGDIAL
  638.             dologend();
  639. #endif /* CKLOGDIAL */
  640.             fatalio = 1;
  641.             return('q');    /* Connection Lost */
  642.         }
  643.         if (nack(winlo) < 0) {
  644.             debug(F101,"input sent too many naks","",winlo);
  645.             errpkt((CHAR *)"Too many retries.");
  646.             type = 'E';
  647.             break;
  648.         } else continue;
  649.         }
  650.         if (rsn == winlo) {        /* Got the packet we want, done. */
  651. #ifdef CK_TIMERS
  652.         if (rttflg && timint)    /* Dynamic round trip timers? */
  653.           getrtt(nakstate, rsn); /* yes, do it. */
  654. #endif /* CK_TIMERS */
  655.         debug(F101,"input rsn=winlo","",rsn);
  656.         break;
  657.         }
  658.  
  659.         /* Got a packet out of order. */
  660.  
  661.         debug(F101,"input out of sequence, rsn","",rsn);
  662.         k = rseqtbl[rsn];        /* Get window slot of this packet. */
  663.         debug(F101,"input rseqtbl[rsn]","",k);
  664.         if (k < 0) {
  665.         debug(F101,"input recv can't find index for rcvd pkt","",rsn);
  666.         /* Was "Internal error 21" */
  667.         /* This should not happen  */
  668.         errpkt((CHAR *)"Sliding windows protocol error.");
  669.         type = 'E';
  670.         break;
  671.         }
  672.         y = chkwin(rsn,winlo,wslots); /* See what window it's in. */
  673.         debug(F101,"input recv chkwin","",y);
  674.         if (y == 1) {        /* From previous window. */
  675. #ifdef STREAMING
  676.         if (!streaming)        /* NO RESEND IF STREAMING! */
  677. #endif /* STREAMING */
  678.           resend(rsn);        /* Resend the ACK (might have data) */
  679.         freerpkt(rsn);        /* Get rid of received packet */
  680.         continue;        /* Back to wait for another packet */
  681.         } else {            /* In this window or out of range */
  682.         if (y < 0)        /* If out of range entirely, */
  683.           freerpkt(rsn);    /* release its buffer */
  684.  
  685. #ifdef STREAMING
  686.         if (streaming) {    /* Streaming (this shouldn't happen) */
  687.             errpkt((CHAR *)"Sequence error on reliable link.");
  688.             type = 'E';
  689.             break;
  690.         }
  691. #endif /* STREAMING */
  692.  
  693. /* If our receive window is full, NAK window-low */
  694.  
  695.         if (rbufnum < 1) {    /* Receive window full? */
  696.             if (nack(winlo) < 0) {    /* No choice, must NAK winlo. */
  697.             errpkt((CHAR *)"Too many retries."); /* Too many */
  698.             type = 'E';
  699.             break;
  700.             } else continue;
  701.         }
  702. /*
  703.   Receive window not full.  This is a packet in the current window but it is
  704.   not the desired packet at winlo.  So therefore there are gaps before this
  705.   packet.  So we find the "lowest" unNAK'd missing packet, if any, between
  706.   winlo and this one, and NAK it.  If there are no as-yet-unNAK'd missing
  707.   packets in the window, then we send nothing and go wait for another packet.
  708.   In theory, this could result in a timeout, but in practice it is likely that
  709.   the already-NAK'd missing packets are already on their way.  Note, we do not
  710.   NAK ahead of ourselves, as that only creates unnecessary retransmissions.
  711. */
  712.         for (x = winlo; x != rsn; x = (x + 1) % 64) {
  713.             if (rseqtbl[x] > -1) /* Have I received packet x? */
  714.               continue;         /* Yes, check next sequence number. */
  715.             pi = sseqtbl[x];     /* No, have I NAK'd it yet? */
  716.             if (pi < 0 || s_pkt[pi].pk_rtr == 0) {
  717.             nack(x);     /* No, NAK it now. */
  718.             break;
  719.             }
  720.         }
  721.         }
  722. /*!!!*/
  723.     } else {            /* Otherwise file sender... */
  724.  
  725. #ifdef STREAMING
  726.         if (streaming && sndtyp == 'D') {
  727.         debug(F101,"STREAMING input streaming","",streaming);
  728.         debug(F000,"STREAMING input sndtyp","",sndtyp);
  729.         rsn = winlo;
  730.         type = 'Y';        /* Pretend we got an ACK */
  731.         }
  732. #endif /* STREAMING */
  733.         if (!nak2ack) {        /* NAK(n+1) = ACK(n) */
  734.         if (wslots > 1) {    /* Packet at winlo already ACK'd? */
  735.             if (sacktbl[winlo]) { /* If so,  */
  736.             sacktbl[winlo] = 0; /* Turn off the ACK'd flag */
  737.             winlo = (winlo + 1) % 64; /* Rotate the window */
  738.             type = 'Y';    /* And return ACK */
  739.             debug(F101,
  740.                   "input send returning pre-stashed ACK","",
  741.                   winlo-1);
  742.             break;
  743.             }
  744.         }
  745. #ifdef STREAMING
  746.         if (!(streaming && sndtyp == 'D')) { /* Not streaming | data */
  747.             type = rpack();    /* Try to read an acknowledgement */
  748.         } else {        /* Streaming and in Data phase */
  749.             type = 'Y';        /* Assume all is normal */
  750.             if (chkint() < 0)    /* Check for console interrupts. */
  751.               type = 'z';
  752.             else if (ttchk() > 4 + bctu) /* Check for return traffic */
  753.               type = rpack();
  754.             debug(F000,"input streaming type","",type);
  755.         }
  756. #endif /* STREAMING */
  757.         debug(F111,"input send",(char *) rdatap,(int) type);
  758.         while (type == 'e') {    /* Handle echoes */
  759.             debug(F000,"echo discarded","",type);
  760.             type = rpack();
  761.         }
  762. #ifndef OLDCHKINT
  763.         if (type == 'z') {
  764.             epktrcvd = 1;
  765.             errpkt((CHAR *)"User cancelled.");
  766.             type = 'E';
  767.             break;
  768.         }
  769. #endif /* OLDCHKINT */
  770.         if (type < -1) {
  771.             xxscreen(SCR_PT,'q',0L,
  772.                ((char *)((type == -2) ?
  773.                "Interrupted" :
  774.                "Connection lost"))
  775.                );
  776. #ifdef CKLOGDIAL
  777.             if (type != -2)
  778.               dologend();
  779. #endif /* CKLOGDIAL */
  780.             return('q');    /* Ctrl-C or connection lost */
  781.         }
  782.         if (type == -1) {
  783.             errpkt((CHAR *)"Receive window full"); /* was "internal */
  784.             debug(F101," wslots","",wslots); /* error 18" */
  785.             debug(F101," winlo","",winlo);
  786.             debug(F101," pktnum","",pktnum);
  787.             dumprbuf();
  788.             type = 'E';
  789.             break;
  790.         }
  791.         dumprbuf();        /* Debugging */
  792.  
  793. #ifdef OLDCHKINT
  794.         if (chkint() < 0) {    /* Check for console interrupts. */
  795.             errpkt((CHAR *)"User cancelled.");
  796.             return(type = 'E');
  797.         }
  798. #endif /* OLDCHKINT */
  799.  
  800.         /* Got a packet */
  801.  
  802. #ifdef STREAMING
  803.         if (streaming) {        /* Streaming */
  804.             if (type == 'Q' || type == 'T') { /* Errors are fatal. */
  805.             crunched++;    /* For statistics */
  806.             errpkt((CHAR *)"Transmission error on reliable link.");
  807.             type = 'E';
  808.             }
  809.         }
  810. #endif /* STREAMING */
  811.         if (type == 'E') {
  812.             debug(F101,"input send got E, nakstate","",nakstate);
  813.             break;        /* Error packet */
  814.         }
  815.         if (type == 'Q') {    /* Crunched packet */
  816.             crunched++;        /* For statistics */
  817.             numerrs++;        /* For packet resizing */
  818.             x = resend(winlo);    /* Resend window-low */
  819.             if (x < 0) {
  820.             type = 'E';
  821.             errpkt((CHAR *)"Too many retries");
  822.             break;
  823.             }
  824.             continue;
  825.         }
  826.         if (type == 'T') {    /* Timeout waiting for ACKs. */
  827.             timeouts++;        /* Count it */
  828.             numerrs++;        /* Count an error too */
  829.             debug(F101,"input send state timeout, winlo","",winlo);
  830.  
  831.             /* Retransmit the oldest un-ACK'd packet. */
  832.  
  833.             debug(F101,"input send resending winlo","",winlo);
  834.             if (resend(winlo) < 0) { /* Check retries */
  835.             debug(F101,"input send too many resends","",maxtry);
  836.             errpkt((CHAR *)"Too many retries");
  837.             return(type = 'E');
  838.             }
  839. #ifdef NEWDPL
  840.             /* Reduce prevailing packet length */
  841.             x = sseqtbl[winlo];    /* Get length of packet we want ACKd */
  842.             if (x > -1) {    /* Only if we have a valid index */
  843.             if (s_pkt[x].pk_typ == 'D') { /* only for D packets */
  844.                 spsiz = (s_pkt[x].pk_len + 8) >> 1; /* halve it */
  845.                 if (spsiz < 20) spsiz = 20; /* within reason */
  846.                 debug(F101,"input T cut packet length","",spsiz);
  847.             }
  848.             }
  849. #endif /* NEWDPL */
  850.             continue;
  851.         }
  852.         }
  853.         /* Got an actual normal packet */
  854.  
  855.         nak2ack = 0;        /* Unset this flag. */
  856.         y = chkwin(rsn,winlo,wslots); /* Is it in the window? */
  857.         debug(F101,"input send rsn","",rsn);
  858.         debug(F101,"input send winlo","",winlo);
  859.         debug(F101,"input send chkwin","",y);
  860.  
  861.         if (type == 'Y') {        /* Got an ACK */
  862.         if (y == 0) {        /* In current window */
  863.             if (spackets < 4)    /* Error counter doesn't count */
  864.               numerrs = 0;    /* until data phase. */
  865.             sacktbl[rsn]++;    /* Mark the packet as ACK'd */
  866.             x = sseqtbl[rsn];    /* Get ACK'd packet's buffer index */
  867.             debug(F101,"bestlen ack x","",x);
  868. #ifdef NEWDPL
  869.             if (x > -1) {
  870.             acktype = s_pkt[x].pk_typ; /* Get type */
  871.             debug(F000,"bestlen ack type","",acktype);
  872.  
  873.             if (acktype == 'D') { /* Adjust data packet length */
  874.                 if (spsiz > bestlen) {
  875.                 bestlen = spsiz;
  876.                 debug(F101,"bestlen B","",bestlen);
  877.                 }
  878. #ifdef DEBUG
  879.                 if (deblog) {
  880.                 debug(F101,"bestlen retry","",s_pkt[x].pk_rtr);
  881.                 debug(F101,"bestlen len","",s_pkt[x].pk_len);
  882.                 debug(F101,"bestlen spackets","",spackets);
  883.                 }
  884. #endif /* DEBUG */
  885.                 /* Set new best length */
  886.                 if (s_pkt[x].pk_rtr == 0 &&
  887.                 s_pkt[x].pk_len + 8 > bestlen) {
  888.                 bestlen = s_pkt[x].pk_len + 8;
  889.                 if (bestlen > spmax)
  890.                   bestlen = spmax;
  891.                 debug(F101,"bestlen A","",bestlen);
  892.                 }
  893. #ifdef DEBUG
  894.                 if (deblog) {
  895.                 debug(F101,"bestlen wslots","",wslots);
  896.                 debug(F101,"bestlen maxsend","",maxsend);
  897.                 }
  898. #endif /* DEBUG */
  899.                 /* Slow start */
  900.                 if (slostart &&
  901.                 (maxsend <= spmax) &&
  902.                 (rpackets < 11) &&
  903.                 (numerrs == 0)) {
  904.                 spsiz = spsiz << 1;
  905.                 debug(F101,"bestlen spsiz A","",spsiz);
  906.  
  907.                 /* Creep up to best length */
  908.                 } else if ((spackets > 5) &&
  909.                        (spsiz < bestlen - 8)) {
  910.                 spsiz += (bestlen - spsiz) / 3;
  911.                 debug(F101,"bestlen spsiz B","",spsiz);
  912.  
  913.                 /* Push the envelope */
  914.                 } else if ((spackets % (wslots + 1) == 0) &&
  915.                        (spackets > 6) &&
  916.                        (bestlen < spmax - 8) &&
  917.                        (spsiz < spmax)) {
  918.                 spsiz += (spmax - bestlen) / 3;
  919.                 debug(F101,"bestlen spsiz C","",spsiz);
  920.                 }
  921.                 /* But not too far */
  922.                 if (spsiz > spmax) {
  923.                 spsiz = spmax;
  924.                 debug(F101,"bestlen spsiz D","",spsiz);
  925.                 }
  926.             }
  927.             }
  928. #endif /* NEWDPL */
  929.  
  930. #ifdef CK_TIMERS
  931.             if (rttflg && timint) /* If doing dynamic timers */
  932.               getrtt(nakstate, rsn); /* call routine to set it. */
  933. #endif /* CK_TIMERS */
  934. /*
  935.   NOTE: The following statement frees the buffer of the ACK we just got.
  936.   But the upper layers still need the data, like if it's the ACK to an I,
  937.   S, F, D, Z, or just about any kind of packet.  So for now, freerbuf()
  938.   deallocates the buffer, but does not erase the data or destroy the pointer
  939.   to it.  There's no other single place where these receive buffers can be
  940.   correctly freed (?) ...
  941. */
  942.             freerpkt(rsn);    /* Free the ACK's buffer */
  943.             freesbuf(rsn);    /* *** Free the sent packet's buffer */
  944.             if (rsn == winlo) {    /* Got the one we want */
  945.             sacktbl[winlo] = 0;
  946.             winlo = (winlo + 1) % 64;
  947.             debug(F101,"input send rotated send window","",winlo);
  948.             break;        /* Return the ACK */
  949.             } else {
  950.             debug(F101,"input send mark pkt","",rsn);
  951.             continue;    /* Otherwise go read another packet */
  952.             }
  953.         } else if (y == 1 && wslots < 2) { /* (190) ACK for previous */
  954.             numerrs++;        /* == NAK for current, count error */
  955.             debug(F101,"input send ACK for previous","",rsn);
  956.             freerpkt(rsn);    /* Free NAK's buffer */
  957.             x = resend(winlo);    /* Resend current packet */
  958.             if (x < 0) {
  959.             type = 'E';
  960.             errpkt((CHAR *)"Too many retries");
  961.             break;
  962.             } else continue;    /* Resend ok, go read another packet */
  963.         } else {        /* Other cases, just ignore */
  964.             debug(F101,"input send ACK out of window","",rsn);
  965.             freerpkt(rsn);
  966.             continue;
  967.         }
  968.         }
  969.         if (type == 'N') {        /* NAK */
  970.         numerrs++;        /* Count an error */
  971. #ifdef STREAMING
  972.         if (streaming) {        /* Streaming */
  973.             errpkt((CHAR *)"NAK received on reliable link.");
  974.             type = 'E';
  975.             break;
  976.         }
  977. #endif /* STREAMING */
  978.  
  979.         debug(F101,"input send NAK","",rsn);
  980. #ifdef NEWDPL
  981.         /* Reduce prevailing packet length */
  982.         x = sseqtbl[rsn];    /* Length of packet that was NAK'd */
  983.         if (x > -1) {        /* If it's a Data packet we've sent */
  984.             if (s_pkt[x].pk_typ == 'D') {
  985.             spsiz = (s_pkt[x].pk_len + 8) >> 1; /* Halve length */
  986. #ifdef COMMENT
  987.             /* This might be a good idea -- haven't tried it ... */
  988.             if (bestlen > 0 && spsiz > bestlen)
  989.               spsiz = bestlen;
  990. #endif /* COMMENT */
  991.             if (spsiz < 20) spsiz = 20;
  992.             debug(F101,"input N cut packet length","",spsiz);
  993.             }
  994.         }
  995. #endif /* NEWDPL */
  996.         freerpkt(rsn);        /* Free buffer where NAK lies. */
  997.         if (y == 0) {        /* In current window */
  998.             debug(F100," in window","",0);
  999.             k = sseqtbl[rsn];    /* Get pointer to NAK'd packet. */
  1000.             if (k < 0 || (k > -1 && s_pkt[k].pk_typ == ' ')) {
  1001.             x = resend(winlo); /* Packet we haven't sent yet. */
  1002.             } else {
  1003.             x = resend(rsn); /* Resend requested packet. */
  1004.             }
  1005.             if (x < 0) {    /* Resend error is fatal.  */
  1006.             type = 'E';
  1007.             errpkt((CHAR *)"Too many retries");
  1008.             break;
  1009.             } else continue;    /* Resend ok, go read another packet */
  1010.         } else if ((rsn == (pktnum + 1) % 64)) { /* NAK for next pkt */
  1011.             if (wslots > 1) {
  1012.             debug( F101,"NAK for next packet, windowing","",rsn);
  1013.             x = resend(winlo); /* Resend window-low */
  1014.             if (x < 0) {
  1015.                 type = 'E';
  1016.                 errpkt((CHAR *)"Too many retries");
  1017.                 break;
  1018.             }
  1019.             continue;    /* Go back and read another pkt */
  1020.             }
  1021.             debug(F101,"NAK for next packet, no windowing","",rsn);
  1022.             x = (rsn == 0) ? 63 : rsn - 1;
  1023.             if (x == 0 && (sndtyp == 'S' || sndtyp == 'I')) {
  1024.             resend(0);    /* ACK for S or I packet missing */
  1025.             continue;    /* so resend the S or I */
  1026.             }
  1027.             rsn = x;        /* Else, treat NAK(n+1) as ACK(n) */
  1028.             nak2ack = 1;    /* Go back and process the ACK */
  1029.             continue;
  1030.         } else if (y > 0) {    /* NAK for pkt we can't resend */
  1031.             debug(F101," NAK out of window","",rsn); /* bad... */
  1032.             type = 'E';
  1033.             errpkt((CHAR *)"NAK out of window");
  1034.             break;
  1035.         } else continue;    /* Ignore other NAKs */
  1036.         }                /* End of file-sender NAK handler */
  1037.  
  1038.             if (rsn == winlo) {        /* Not ACK, NAK, timeout, etc. */
  1039.         debug(F000,"input send unexpected type","",type);
  1040.         break;
  1041.         }
  1042.     }                /* End of file-sender section */
  1043.     }                    /* End of input() while() loop */
  1044. /*
  1045.   When the window size is 1 and we have the packet we want, there can not
  1046.   possibly be anything waiting for us on the connection that is useful to us.
  1047.   However, there might be redundant copies of a packet we already got, which
  1048.   would cause needless cycles of repeated packets.  Therefore we flush the
  1049.   communications input buffer now to try to get rid of undesired and unneeded
  1050.   packets that we have not read yet.
  1051. */
  1052.     if (wslots == 1
  1053. #ifdef STREAMING
  1054.     && !streaming            /* But not when streaming */
  1055. #endif /* STREAMING */
  1056.     ) {
  1057.     debug(F100,"input about to flush","",0);
  1058.     ttflui();        /* Got what we want, clear input buffer. */
  1059.     }
  1060. #ifndef NEWDPL
  1061.     if (!nakstate)            /* When sending */
  1062.       rcalcpsz();            /* recalculate size every packet */
  1063. #endif /* NEWDPL */
  1064.     if (type == 'E')
  1065.       xitsta |= (what ? what : 1);    /* Remember what failed. */
  1066.     debug(F101,"input winlo","",winlo);
  1067.     debug(F101,"input rsn","",rsn);
  1068.     debug(F000,"input returning type","",type);
  1069.     return(rcvtyp = type);        /* Success, return packet type. */
  1070. }
  1071.  
  1072. #ifdef PARSENSE
  1073. /*  P A R C H K  --  Check if Kermit packet has parity  */
  1074.  
  1075. /*
  1076.   Call with s = pointer to packet, start = packet start character, n = length.
  1077.   Returns 0 if packet has no parity, -1 on error, or, if packet has parity:
  1078.     'e' for even, 'o' for odd, 'm' for mark.  Space parity cannot be sensed.
  1079.   So a return value of 0 really means either space or none.
  1080.   Returns -2 if parity has already been checked during this protocol operation.
  1081. */
  1082. int
  1083. #ifdef CK_ANSIC
  1084. parchk(CHAR *s, CHAR start, int n)
  1085. #else
  1086. parchk(s,start,n) CHAR *s, start; int n;
  1087. #endif /* CK_ANSIC */
  1088. /* parchk */ {
  1089.     CHAR s0, s1, s2, s3;
  1090.  
  1091.     debug(F101,"parchk n","",n);
  1092.     debug(F101,"parchk start","",start);
  1093.  
  1094.     s0 = s[0] & 0x7f;            /* Mark field (usually Ctrl-A) */
  1095.  
  1096.     if (s0 != start || n < 5) return(-1); /* Not a valid packet */
  1097.  
  1098. /* Look at packet control fields, which never have 8th bit set */
  1099. /* First check for no parity, most common case. */
  1100.  
  1101.     if (((s[0] | s[1] | s[2] | s[3]) & 0x80) == 0)
  1102.       return(0);            /* No parity or space parity */
  1103.  
  1104. /* Check for mark parity */
  1105.  
  1106.     if (((s[0] & s[1] & s[2] & s[3]) & 0x80) == 0x80)
  1107.       return('m');            /* Mark parity */
  1108.  
  1109. /* Packet has some kind of parity */
  1110. /* Make 7-bit copies of control fields */
  1111.  
  1112.     s1 = s[1] & 0x7f;            /* LEN */
  1113.     s2 = s[2] & 0x7f;            /* SEQ */
  1114.     s3 = s[3] & 0x7f;            /* TYPE */
  1115.  
  1116. /* Check for even parity */
  1117.  
  1118.     if ((s[0] == p_tbl[s0]) &&
  1119.         (s[1] == p_tbl[s1]) &&
  1120.         (s[2] == p_tbl[s2]) &&
  1121.     (s[3] == p_tbl[s3]))
  1122.       return('e');
  1123.  
  1124. /* Check for odd parity */
  1125.  
  1126.     if ((s[0] != p_tbl[s0]) &&
  1127.         (s[1] != p_tbl[s1]) &&
  1128.         (s[2] != p_tbl[s2]) &&
  1129.     (s[3] != p_tbl[s3]))
  1130.       return('o');
  1131.  
  1132. /* Otherwise it's probably line noise.  Let checksum calculation catch it. */
  1133.  
  1134.     return(-1);
  1135. }
  1136. #endif /* PARSENSE */
  1137.  
  1138. /*
  1139.   Check to make sure timeout intervals are long enough to allow maximum
  1140.   length packets to get through before the timer goes off.  If not, the
  1141.   timeout interval is adjusted upwards.
  1142.  
  1143.   This routine is called at the beginning of a transaction, before we
  1144.   know anything about the delay characteristics of the line.  It works
  1145.   only for serial communication devices; it trusts the speed reported by
  1146.   the operating system.
  1147.  
  1148.   Call with a timout interval.  Returns it, adjusted if necessary.
  1149. */
  1150. int
  1151. chktimo(timo,flag) int timo, flag; {
  1152.     long cps, z; int x, y;
  1153. #ifdef STREAMING
  1154.     debug(F101,"chktimo streaming","",streaming);
  1155.     if (streaming)
  1156.       return(0);
  1157. #endif /* STREAMING */
  1158.  
  1159.     debug(F101,"chktimo timo","",timo); /* Timeout before adjustment */
  1160.     debug(F101,"chktimo flag","",flag);
  1161.  
  1162.     if (flag)                /* Don't change timeout if user */
  1163.       return(timo);            /* gave SET SEND TIMEOUT command. */
  1164.     debug(F101,"chktimo spmax","",spmax);
  1165.     debug(F101,"chktimo urpsiz","",urpsiz);
  1166.  
  1167.     speed = ttgspd();            /* Get current speed. */
  1168.     if (speed > 0L && !network) {
  1169.     cps = speed / 10L;        /* Convert to chars per second */
  1170.     if (cps > 0L) {
  1171.         long plen;            /* Maximum of send and rcv pkt size */
  1172.         z = cps * (long) timo;    /* Chars per timeout interval */
  1173.         z -= z / 10L;        /* Less 10 percent */
  1174.         plen = spmax;
  1175.         if (urpsiz > spmax) plen = urpsiz;
  1176.         debug(F101,"chktimo plen","",plen);
  1177.         if (z < plen) {        /* Compare with packet size */
  1178.         x = (int) ((long) plen / cps); /* Adjust if necessary */
  1179.         y = x / 10;        /* Add 10 percent for safety */
  1180.         if (y < 2) y = 2;    /* Or 2 seconds, whichever is more */
  1181.         x += y;
  1182.         if (x > timo)        /* If this is greater than current */
  1183.           timo = x;        /* timeout, change the timeout */
  1184.         debug(F101,"chktimo new timo","",timo);
  1185.         }
  1186.     }
  1187.     }
  1188.     return(timo);
  1189. }
  1190.  
  1191. /*  S P A C K  --  Construct and send a packet  */
  1192.  
  1193. /*
  1194.   spack() sends a packet of the given type, sequence number n, with len data
  1195.   characters pointed to by d, in either a regular or extended- length packet,
  1196.   depending on len.  Returns the number of bytes actually sent, or else -1
  1197.   upon failure.  Uses global npad, padch, mystch, bctu, data.  Leaves packet
  1198.   fully built and null-terminated for later retransmission by resend().
  1199.   Updates global sndpktl (send-packet length).
  1200.  
  1201.   NOTE: The global pointer "data" is assumed to point into the 7th position
  1202.   of a character array (presumably in packet buffer for the current packet).
  1203.   It was used by getpkt() to build the packet data field.  spack() fills in
  1204.   the header to the left of the data pointer (the data pointer is defined
  1205.   in getsbuf() in ckcfn3.c).  If the address "d" is the same as "data", then
  1206.   the packet's data field has been built "in place" and need not be copied.
  1207. */
  1208. int
  1209. #ifdef CK_ANSIC
  1210. spack(char pkttyp, int n, int len, CHAR *d)
  1211. #else
  1212. spack(pkttyp,n,len,d) char pkttyp; int n, len; CHAR *d;
  1213. #endif /* CK_ANSIC */
  1214. /* spack */ {
  1215.     register int i;
  1216.     int j, k, x, lp, longpkt, copy, loglen;
  1217.  
  1218. #ifdef GFTIMER
  1219.     CKFLOAT t1 = 0.0, t2 = 0.0;
  1220. #endif /* GFTIMER */
  1221.  
  1222.     register CHAR *cp, *mydata;
  1223.     unsigned crc;
  1224.  
  1225.     copy = (d != data);            /* Flag whether data must be copied  */
  1226.  
  1227. #ifdef DEBUG
  1228.     if (deblog) {            /* Save lots of function calls! */
  1229.     debug(F101,"spack n","",n);
  1230.     if (pkttyp != 'D') {        /* Data packets would be too long */
  1231.         debug(F111,"spack data",data,data);
  1232.         debug(F111,"spack d",d,d);
  1233.     }
  1234.     debug(F101,"spack len","",len);
  1235.     debug(F101,"spack copy","",copy);
  1236.     }
  1237. #endif /* DEBUG */
  1238.  
  1239.     longpkt = (len + bctl + 2) > 94;    /* Decide whether it's a long packet */
  1240.     mydata = data - 7 + (longpkt ? 0 : 3); /* Starting position of header */
  1241.     k = sseqtbl[n];            /* Packet structure info for pkt n */
  1242. #ifdef DEBUG
  1243.     if (deblog) {            /* Save 2 more function calls... */
  1244.     debug(F101,"spack mydata","",mydata);
  1245.     debug(F101,"spack sseqtbl[n]","",k);
  1246.     if (k < 0) {
  1247. #ifdef STREAMING
  1248.         if (!streaming)
  1249. #endif /* STREAMING */
  1250.           debug(F101,"spack sending packet out of window","",n);
  1251.     }
  1252.     }
  1253. #endif /* DEBUG */
  1254.     if (k > -1) {
  1255.     s_pkt[k].pk_adr = mydata;    /* Remember address of packet. */
  1256.     s_pkt[k].pk_seq = n;        /* Record sequence number */
  1257.     s_pkt[k].pk_typ = pkttyp;    /* Record packet type */
  1258.     }
  1259.     spktl = 0;                /* Initialize length of this packet */
  1260.     i = 0;                /* and position in packet. */
  1261.  
  1262. /* Now fill the packet */
  1263.  
  1264.     mydata[i++] = mystch;        /* MARK */
  1265.     lp = i++;                /* Position of LEN, fill in later */
  1266.  
  1267.     mydata[i++] = tochar(n);        /* SEQ field */
  1268.     mydata[i++] = pkttyp;        /* TYPE field */
  1269.     j = len + bctl;            /* Length of data + block check */
  1270.     if (longpkt) {            /* Long packet? */
  1271.     int x;                /* Yes, work around SCO Xenix/286 */
  1272. #ifdef CKTUNING
  1273.     unsigned int chk;
  1274. #endif /* CKTUNING */
  1275.     x = j / 95;            /* compiler bug... */
  1276.         mydata[lp] = tochar(0);        /* Set LEN to zero */
  1277.         mydata[i++] = tochar(x);    /* Extended length, high byte */
  1278.         mydata[i++] = tochar(j % 95);    /* Extended length, low byte */
  1279. #ifdef CKTUNING
  1280.         /* Header checksum - skip the function calls and loops */
  1281.       chk = (unsigned) mydata[lp]   +
  1282.             (unsigned) mydata[lp+1] +
  1283.             (unsigned) mydata[lp+2] +
  1284.         (unsigned) mydata[lp+3] +
  1285.         (unsigned) mydata[lp+4] ;
  1286.     mydata[i++] = tochar((CHAR) ((((chk & 0300) >> 6) + chk) & 077));
  1287. #else
  1288.         mydata[i] = '\0';        /* Terminate for header checksum */
  1289.         mydata[i++] = tochar(chk1(mydata+lp,5));
  1290. #endif /* CKTUNING */
  1291.     } else mydata[lp] = tochar(j+2);    /* Normal LEN */
  1292. /*
  1293.   When sending a file, the data is already in the right place.  If it weren't,
  1294.   it might make sense to optimize this section by using memcpy or bcopy
  1295.   (neither of which are portable), but only if our packets were rather long.
  1296.   When receiving, we're only sending ACKs so it doesn't matter.  So count the
  1297.   following loop as a sleeping dog.
  1298. */
  1299.     if (copy)                /* Data field built in place? */
  1300.       for ( ; len--; i++) mydata[i] = *d++; /* No, must copy. */
  1301.     else                /* Otherwise, */
  1302.       i += len;                /* Just skip past data field. */
  1303.     mydata[i] = '\0';            /* Null-terminate for checksum calc. */
  1304.  
  1305.     switch (bctu) {            /* Block check */
  1306.     case 1:                /* 1 = 6-bit chksum */
  1307.         mydata[i++] = tochar(chk1(mydata+lp,i-lp));
  1308.         break;
  1309.     case 2:                /* 2 = 12-bit chksum */
  1310.         j = chk2(mydata+lp,i-lp);
  1311.         mydata[i++] = (unsigned)tochar((j >> 6) & 077);
  1312.            mydata[i++] = (unsigned)tochar(j & 077);
  1313.         break;
  1314.         case 3:                /* 3 = 16-bit CRC */
  1315.         crc = chk3(mydata+lp,i-lp);
  1316.         mydata[i++] = (unsigned)tochar(((crc & 0170000)) >> 12);
  1317.         mydata[i++] = (unsigned)tochar((crc >> 6) & 077);
  1318.         mydata[i++] = (unsigned)tochar(crc & 077);
  1319.         break;
  1320.     case 4:                /* 2 = 12-bit chksum, blank-free */
  1321.         j = chk2(mydata+lp,i-lp);
  1322.         mydata[i++] =
  1323.           (unsigned)(tochar((unsigned)(((j >> 6) & 077) + 1)));
  1324.            mydata[i++] = (unsigned)(tochar((unsigned)((j & 077) + 1)));
  1325.         break;
  1326.     }
  1327.     loglen = i;
  1328.     mydata[i++] = seol;            /* End of line (packet terminator) */
  1329. #ifdef TCPSOCKET
  1330. /*
  1331.   If TELNET connection and packet terminator is carriage return,
  1332.   we must stuff either LF or NUL, according to SET TELNET NEWLINE-MODE
  1333.   (tn_nlm), to meet the TELNET NVT specification, unless user said RAW.
  1334.  
  1335.   If NEWLINE-MODE is set to LF instead of CR, we still send CR-NUL
  1336.   on a NVT connection and CR on a binary connection.
  1337. */
  1338.     if (
  1339. #ifdef STREAMING
  1340.     !dontsend &&
  1341. #endif /* STREAMING */
  1342.     ((network && ttnproto == NP_TELNET) || (!local && sstelnet))
  1343.     && seol == CR) {
  1344.         switch (TELOPT_ME(TELOPT_BINARY) ? tn_b_nlm : tn_nlm) {
  1345.       case TNL_CR:            /* NVT or BINARY */
  1346.         break;
  1347.       case TNL_CRNUL:
  1348.         mydata[i++] = NUL;
  1349.         break;
  1350.       case TNL_CRLF:
  1351.         mydata[i++] = LF;
  1352.         break;
  1353.     }
  1354.     }
  1355. #endif /* TCPSOCKET */
  1356.     mydata[i] = '\0';            /* Terminate string */
  1357.     if (
  1358. #ifdef STREAMING
  1359.     !dontsend &&
  1360. #endif /* STREAMING */
  1361.     pktlog
  1362.     )                /* Save a function call! */
  1363.       logpkt('s',n,mydata,loglen);    /* Log the packet */
  1364.  
  1365.     /* (PWP) add the parity quickly at the end */
  1366.     if (parity) {
  1367.     switch (parity) {
  1368.       case 'e':            /* Even */
  1369.         for (cp = &mydata[i-1]; cp >= mydata; cp--)
  1370.           *cp = p_tbl[*cp];
  1371.         break;
  1372.       case 'm':            /* Mark */
  1373.         for (cp = &mydata[i-1]; cp >= mydata; cp--)
  1374.           *cp |= 128;
  1375.         break;
  1376.       case 'o':            /* Odd */
  1377.         for (cp = &mydata[i-1]; cp >= mydata; cp--)
  1378.           *cp = p_tbl[*cp] ^ 128;
  1379.         break;
  1380.       case 's':            /* Space */
  1381.         for (cp = &mydata[i-1]; cp >= mydata; cp--)
  1382.           *cp &= 127;
  1383.         break;
  1384.     }
  1385.     }
  1386.     if (pktpaus) msleep(pktpaus);    /* Pause if requested */
  1387.     x = 0;
  1388.  
  1389.     if (npad) {
  1390. #ifdef STREAMING
  1391.     if (dontsend)
  1392.       x = 0;
  1393.     else
  1394. #endif /* STREAMING */
  1395.       x = ttol(padbuf,npad);    /* Send any padding */
  1396.     }
  1397.     if (x > -1) {
  1398. #ifdef CK_TIMERS
  1399.     if (timint > 0) {
  1400.         if (pkttyp == 'N')
  1401.           srttbl[n > 0 ? n-1 : 63] = gtimer();
  1402.         else
  1403.           srttbl[n] = gtimer();
  1404.     }
  1405. #endif /* CK_TIMERS */
  1406.     spktl = i;            /* Remember packet length */
  1407.     if (k > -1)
  1408.       s_pkt[k].pk_len = spktl;    /* also in packet info structure */
  1409.  
  1410. #ifdef DEBUG
  1411. #ifdef GFTIMER
  1412. /*
  1413.   This code shows (in the debug log) how long it takes write() to execute.
  1414.   Sometimes on a congested TCP connection, it can surprise you -- 90 seconds
  1415.   or more...
  1416. */
  1417.     if (
  1418. #ifdef STREAMING
  1419.         !dontsend &&
  1420. #endif /* STREAMING */
  1421.         deblog
  1422.         )
  1423.       t1 = gftimer();
  1424. #endif /* GFTIMER */
  1425. #endif /* DEBUG */
  1426.  
  1427. #ifdef STREAMING
  1428.     if (dontsend) {
  1429.         debug(F000,"STREAMING spack skipping","",pkttyp);
  1430.         x = 0;
  1431.     } else
  1432. #endif /* STREAMING */
  1433.     x = ttol(mydata,spktl);        /* Send the packet */
  1434.     }
  1435. #ifdef STREAMING
  1436.     if (!dontsend) {
  1437. #endif /* STREAMING */
  1438.     debug(F101,"spack spktl","",spktl);
  1439.     debug(F101,"spack ttol returns","",x);
  1440.     if (x < 0) {            /* Failed. */
  1441.         if (local && x < -1) {
  1442.         xxscreen(SCR_ST,ST_ERR,0L,"FAILED: Connection lost");
  1443.         /* We can't send an E packet because the connection is lost. */
  1444.         epktsent = 1;        /* So pretend we sent one. */
  1445.         fatalio = 1;        /* Remember we got a fatal i/o error */
  1446. #ifdef CKLOGDIAL
  1447.         dologend();
  1448. #endif /* CKLOGDIAL */
  1449.         ckstrncpy((char *)epktmsg,"Connection lost",PKTMSGLEN);
  1450.         }
  1451.         return(x);
  1452.     }
  1453.     if (spktl > maxsend)        /* Keep track of longest packet sent */
  1454.       maxsend = spktl;
  1455. #ifdef DEBUG
  1456. #ifdef GFTIMER
  1457.     if (deblog)  {            /* Log elapsed time for write() */
  1458.         t2 = gftimer();
  1459.         debug(F101,"spack ttol msec","",(long)((t2-t1)*1000.0));
  1460.     }
  1461. #endif /* GFTIMER */
  1462. #endif /* DEBUG */
  1463. #ifdef STREAMING
  1464.     }
  1465. #endif /* STREAMING */
  1466.  
  1467.     sndtyp = pkttyp;            /* Remember packet type for echos */
  1468.     if (!dontsend) {            /* If really sent, */
  1469.     spackets++;            /* count it. */
  1470.     flco += spktl;            /* Count the characters */
  1471.     tlco += spktl;            /* for statistics... */
  1472. #ifdef DEBUG
  1473.     if (deblog) {            /* Save two function calls! */
  1474.         dumpsbuf();            /* Dump send buffers to debug log */
  1475.         debug(F111,"spack calling screen, mydata=",mydata,n);
  1476.     }
  1477. #endif /* DEBUG */
  1478.     }
  1479.     if (local) {
  1480.     int x = 0;
  1481.     if (fdispla != XYFD_N) x = 1;
  1482.     if ((fdispla == XYFD_B) && (pkttyp == 'D' || pkttyp == 'Y')) x = 0;
  1483.     if (x)
  1484.       xxscreen(SCR_PT,pkttyp,(long)n,(char *)mydata); /* Update screen */
  1485.     }
  1486.     return(spktl);            /* Return length */
  1487. }
  1488.  
  1489. /*  C H K 1  --  Compute a type-1 Kermit 6-bit checksum.  */
  1490.  
  1491. int
  1492. chk1(pkt,len) register CHAR *pkt; register int len; {
  1493.     register unsigned int chk;
  1494. #ifdef CKTUNING
  1495. #ifdef COMMENT
  1496.     register unsigned int m;        /* Avoid function call */
  1497.     m = (parity) ? 0177 : 0377;
  1498.     for (chk = 0; len-- > 0; pkt++)
  1499.       chk += *pkt & m;
  1500. #else
  1501.     chk = 0;
  1502.     while (len-- > 0) chk += (unsigned) *pkt++;
  1503. #endif /* COMMENT */
  1504. #else
  1505.     chk = chk2(pkt,len);
  1506. #endif /* CKTUNING */
  1507.     chk = (((chk & 0300) >> 6) + chk) & 077;
  1508.     debug(F101,"chk1","",chk);
  1509.     return((int) chk);
  1510. }
  1511.  
  1512. /*  C H K 2  --  Compute the numeric sum of all the bytes in the packet.  */
  1513.  
  1514. unsigned int
  1515. chk2(pkt,len) register CHAR *pkt; register int len; {
  1516.     register long chk;
  1517. #ifdef COMMENT
  1518.     register unsigned int m;
  1519.     m = (parity) ? 0177 : 0377;
  1520.     for (chk = 0; len-- > 0; pkt++)
  1521.       chk += *pkt & m;
  1522. #else
  1523.     /* Parity has already been stripped */
  1524.     chk = 0L;
  1525.     while (len-- > 0) chk += (unsigned) *pkt++;
  1526. #endif /* COMMENT */
  1527.     debug(F101,"chk2","",(unsigned int) (chk & 07777));
  1528.     return((unsigned int) (chk & 07777));
  1529. }
  1530.  
  1531. /*  C H K 3  --  Compute a type-3 Kermit block check.  */
  1532. /*
  1533.  Calculate the 16-bit CRC-CCITT of a null-terminated string using a lookup
  1534.  table.  Assumes the argument string contains no embedded nulls.
  1535. */
  1536. #ifdef COMMENT
  1537. unsigned int
  1538. chk3(pkt,parity,len) register CHAR *pkt; int parity; register int len; {
  1539.     register long c, crc;
  1540.     register unsigned int m;
  1541.     m = (parity) ? 0177 : 0377;
  1542.     for (crc = 0; len-- > 0; pkt++) {
  1543.     c = crc ^ (long)(*pkt & m);
  1544.     crc = (crc >> 8) ^ (crcta[(c & 0xF0) >> 4] ^ crctb[c & 0x0F]);
  1545.     }
  1546.     return((unsigned int) (crc & 0xFFFF));
  1547. }
  1548. #else
  1549. unsigned int
  1550. chk3(pkt,len) register CHAR *pkt; register int len; {
  1551.     register long c, crc;
  1552.     for (crc = 0; len-- > 0; pkt++) {
  1553.     c = crc ^ (long)(*pkt);
  1554.     crc = (crc >> 8) ^ (crcta[(c & 0xF0) >> 4] ^ crctb[c & 0x0F]);
  1555.     }
  1556.     debug(F101,"chk3","",(unsigned int) (crc & 0xFFFF));
  1557.     return((unsigned int) (crc & 0xFFFF));
  1558. }
  1559. #endif /* COMMENT */
  1560.  
  1561. /*  N X T P K T  --  Next Packet  */
  1562. /*
  1563.   Get packet number of next packet to send and allocate a buffer for it.
  1564.   Returns:
  1565.     0 on success, with global pktnum set to the packet number;
  1566.    -1 on failure to allocate buffer (fatal);
  1567.    -2 if resulting packet number is outside the current window.
  1568. */
  1569. int
  1570. nxtpkt() {                /* Called by file sender */
  1571.     int j, n, x;
  1572.  
  1573.     debug(F101,"nxtpkt pktnum","",pktnum);
  1574.     debug(F101,"nxtpkt winlo ","",winlo);
  1575.     n = (pktnum + 1) % 64;        /* Increment packet number mod 64 */
  1576.     debug(F101,"nxtpkt n","",n);
  1577. #ifdef STREAMING
  1578.     if (!streaming) {
  1579.     x = chkwin(n,winlo,wslots);    /* Don't exceed window boundary */
  1580.     debug(F101,"nxtpkt chkwin","",x);
  1581.     if (x)
  1582.       return(-2);
  1583.     j = getsbuf(n);            /* Get a buffer for packet n */
  1584.     if (j < 0) {
  1585.         debug(F101,"nxtpkt getsbuf failure","",j);
  1586.         return(-1);
  1587.     }
  1588.     }
  1589. #endif /* STREAMING */
  1590.     pktnum = n;
  1591.     return(0);
  1592. }
  1593.  
  1594. /* Functions for sending ACKs and NAKs */
  1595.  
  1596. /* Note, we should only ACK the packet at window-low (winlo) */
  1597. /* However, if an old packet arrives again (e.g. because the ACK we sent */
  1598. /* earlier was lost), we ACK it again. */
  1599.  
  1600. int
  1601. ack() {                    /* Acknowledge the current packet. */
  1602.     return(ackns(winlo,(CHAR *)""));
  1603. }
  1604.  
  1605. #ifdef STREAMING
  1606. int
  1607. fastack() {                /* Acknowledge packet n */
  1608.     int j, k, n, x;
  1609.     n = winlo;
  1610.  
  1611.     k = rseqtbl[n];            /* First find received packet n. */
  1612.     debug(F101,"STREAMING fastack k","",k);
  1613.     freesbuf(n);            /* Free current send-buffer, if any */
  1614.     if ((j = getsbuf(n)) < 0) {
  1615.     /* This can happen if we have to re-ACK an old packet that has */
  1616.         /* already left the window.  It does no harm. */
  1617.     debug(F101,"STREAMING fastack can't getsbuf","",n);
  1618.     }
  1619.     dontsend = 1;
  1620.     x = spack('Y',n,0,(CHAR *)"");    /* Now send it (but not really) */
  1621.     dontsend = 0;
  1622.     if (x < 0) return(x);
  1623.     debug(F101,"STREAMING fastack x","",x);
  1624.     if (k > -1)
  1625.       freerbuf(k);            /* don't need it any more */
  1626.     if (j > -1)
  1627.       freesbuf(j);            /* and don't need to keep ACK either */
  1628.     winlo = (winlo + 1) % 64;
  1629.     return(0);
  1630. }
  1631. #endif /* STREAMING */
  1632.  
  1633. int
  1634. ackns(n,s) int n; CHAR *s; {        /* Acknowledge packet n */
  1635.     int j, k, x;
  1636.     debug(F111,"ackns",s,n);
  1637.  
  1638.     k = rseqtbl[n];            /* First find received packet n. */
  1639.     debug(F101,"ackns k","",k);
  1640.     freesbuf(n);            /* Free current send-buffer, if any */
  1641.     if ((j = getsbuf(n)) < 0) {
  1642.     /* This can happen if we have to re-ACK an old packet that has */
  1643.         /* already left the window.  It does no harm. */
  1644.     debug(F101,"ackns can't getsbuf","",n);
  1645.     }
  1646.     x = spack('Y',n,(int)strlen((char *)s),s); /* Now send it. */
  1647.     if (x < 0) return(x);
  1648.     debug(F101,"ackns winlo","",winlo);
  1649.     debug(F101,"ackns n","",n);
  1650.     if (n == winlo) {            /* If we're acking winlo */
  1651.     if (k > -1)
  1652.       freerbuf(k);            /* don't need it any more */
  1653.     if (j > -1)
  1654.       freesbuf(j);            /* and don't need to keep ACK either */
  1655.     winlo = (winlo + 1) % 64;
  1656.     }
  1657.     return(0);
  1658. }
  1659.  
  1660. int
  1661. ackn(n) int n; {            /* Send ACK for packet number n */
  1662.     return(ackns(n,(CHAR *)""));
  1663. }
  1664.  
  1665. int
  1666. ack1(s) CHAR *s; {            /* Send an ACK with data. */
  1667.     if (!s) s = (CHAR *)"";
  1668.     debug(F110,"ack1",(char *)s,0);
  1669.     return(ackns(winlo,s));
  1670. }
  1671.  
  1672. /* N A C K  --   Send a Negative ACKnowledgment. */
  1673. /*
  1674.  Call with the packet number, n, to be NAK'd.
  1675.  Returns -1 if that packet has been NAK'd too many times, otherwise 0.
  1676.  Btw, it is not right to return 0 under error conditions.  This is
  1677.  done because the -1 code is used for cancelling the file transfer.
  1678.  More work is needed here.
  1679. */
  1680. int
  1681. nack(n) int n; {
  1682.     int i, x;
  1683.  
  1684.     if (n < 0 || n > 63) {
  1685.     debug(F101,"nack bad pkt num","",n);
  1686.     return(0);
  1687.     } else debug(F101,"nack","",n);
  1688.     if ((i = sseqtbl[n]) < 0) {        /* If necessary */
  1689.     if (getsbuf(n) < 0) {        /* get a buffer for this NAK */
  1690.         debug(F101,"nack can't getsbuf","",n);
  1691.         return(0);
  1692.     } else i = sseqtbl[n];        /* New slot number */
  1693.     }
  1694.     if (s_pkt[i].pk_rtr++ > maxtry)    /* How many times have we done this? */
  1695.       return(-1);            /* Too many... */
  1696.  
  1697. /* Note, don't free this buffer.  Eventually an ACK will come, and that */
  1698. /* will set it free.  If not, well, it's back to ground zero anyway...  */
  1699.  
  1700.     x = spack('N',n,0,(CHAR *) "");    /* NAKs never have data. */
  1701.     return(x);
  1702. }
  1703.  
  1704. #ifndef NEWDPL                /* This routine no longer used */
  1705. /*
  1706.  * (PWP) recalculate the optimal packet length in the face of errors.
  1707.  * This is a modified version of the algorithm by John Chandler in Kermit/370,
  1708.  * see "Dynamic Packet Size Control", Kermit News, V2 #1, June 1988.
  1709.  *
  1710.  * This implementation minimizes the total overhead equation, which is
  1711.  *
  1712.  *   Total chars = file_chars + (header_len * num_packs)
  1713.  *                            + (errors * (header_len + packet_len))
  1714.  *
  1715.  * Differentiate with respect to number of chars, solve for packet_len, get:
  1716.  *
  1717.  *   packet_len = sqrt (file_chars * header_len / errors)
  1718.  */
  1719.  
  1720. /*
  1721.  (FDC) New super-simple algorithm.  If there was an error in the most recent
  1722.  packet exchange, cut the send-packet size in half, down to a minimum of 20.
  1723.  If there was no error, increase the size by 5/4, up to the maximum negotiated
  1724.  length.  Seems to be much more responsive than previous algorithm, which took
  1725.  forever to recover the original packet length, and it also went crazy under
  1726.  certain conditions.
  1727.  
  1728.  Here's another idea for packet length resizing that keeps a history of the
  1729.  last n packets.  Push a 1 into the left end of an n-bit shift register if the
  1730.  current packet is good, otherwise push a zero.  The current n-bit value, w, of
  1731.  this register is a weighted sum of the noise hits for the last n packets, with
  1732.  the most recent weighing the most.  The current packet length is some function
  1733.  of w and the negotiated packet length, like:
  1734.  
  1735.    (2^n - w) / (2^n) * (negotiated length)
  1736.  
  1737.  If the present resizing method causes problems, think about this one a little
  1738.  more.
  1739. */
  1740. VOID
  1741. rcalcpsz() {
  1742.  
  1743. #ifdef COMMENT
  1744. /* Old way */
  1745.     register long x, q;
  1746.     if (numerrs == 0) return;        /* bounds check just in case */
  1747.  
  1748.     /* overhead on a data packet is npad+5+bctr, plus 3 if extended packet */
  1749.     /* an ACK is 5+bctr */
  1750.  
  1751.     /* first set x = per packet overhead */
  1752.     if (wslots > 1)            /* Sliding windows */
  1753.       x = (long) (npad+5+bctr);        /* packet only, don't count ack */
  1754.     else                /* Stop-n-wait */
  1755.       x = (long) (npad+5+3+bctr+5+bctr); /* count packet and ack. */
  1756.  
  1757.     /* then set x = packet length ** 2 */
  1758.     x = x * ( ffc / (long) numerrs);    /* careful of overflow */
  1759.  
  1760.     /* calculate the long integer sqrt(x) quickly */
  1761.     q = 500;
  1762.     q = (q + x/q) >> 1;
  1763.     q = (q + x/q) >> 1;
  1764.     q = (q + x/q) >> 1;
  1765.     q = (q + x/q) >> 1;        /* should converge in about 4 steps */
  1766.     if ((q > 94) && (q < 130))    /* break-even point for long packets */
  1767.       q = 94;
  1768.     if (q > spmax) q = spmax;    /* maximum bounds */
  1769.     if (q < 10) q = 10;        /* minimum bounds */
  1770.     spsiz = q;            /* set new send packet size */
  1771.     debug(F101,"rcalcpsiz","",q);
  1772. #else
  1773. /* New way */
  1774.     debug(F101,"rcalcpsiz numerrs","",numerrs);
  1775.     debug(F101,"rcalcpsiz spsiz","",spsiz);
  1776.     if (spackets < 3) {
  1777.     numerrs = 0;
  1778.     return;
  1779.     }
  1780.     if (numerrs)
  1781.       spsiz = spsiz / 2;
  1782.     else
  1783.       spsiz = (spsiz / 4) * 5;
  1784.     if (spsiz < 20) spsiz = 20;
  1785.     if (spsiz > spmax) spsiz = spmax;
  1786.     debug(F101,"rcalcpsiz new spsiz","",spsiz);
  1787.     numerrs = 0;
  1788. #endif /* COMMENT */
  1789. }
  1790. #endif /* NEWDPL */
  1791.  
  1792. /*  R E S E N D  --  Retransmit packet n.  */
  1793.  
  1794. /*
  1795.   Returns 0 or positive on success (the number of retries for packet n).
  1796.   On failure, returns a negative number, and an error message is placed
  1797.   in recpkt.
  1798. */
  1799. int
  1800. resend(n) int n; {            /* Send packet n again. */
  1801.     int j, k, x;
  1802. #ifdef GFTIMER
  1803.     CKFLOAT t1 = 0.0, t2 = 0.0;
  1804. #endif /* GFTIMER */
  1805.  
  1806.     debug(F101,"resend seq","",n);
  1807.  
  1808.     k = chkwin(n,winlo,wslots);        /* See if packet in current window */
  1809.     j = -1;                /* Assume it's lost */
  1810.     if (k == 0) j = sseqtbl[n];        /* See if we still have a copy of it */
  1811.     if (k != 0 || j < 0) {        /* If not.... */
  1812.     if (nakstate && k == 1) {
  1813. /*
  1814.   Packet n is in the previous window and we are the file receiver.
  1815.   We already sent the ACK and deallocated its buffer so we can't just
  1816.   retransmit the ACK.  Rather than give up, we try some tricks...
  1817. */
  1818.         if (n == 0 && spackets < 63 && myinit[0]) { /* ACK to Send-Init */
  1819. /*
  1820.   If the packet number is 0, and we're at the beginning of a protocol
  1821.   operation (spackets < 63), then we have to resend the ACK to an I or S
  1822.   packet, complete with parameters in the data field.  So we take a chance and
  1823.   send a copy of the parameters in an ACK packet with block check type 1.
  1824. */
  1825.         int bctlsav;        /* Temporary storage */
  1826.         int bctusav;
  1827.         bctlsav = bctl;        /* Save current block check length */
  1828.         bctusav = bctu;        /* and type */
  1829.         bctu = bctl = 1;    /* Set block check to 1 */
  1830.         x = spack('Y',0,(int)strlen((char *)myinit),(CHAR *)myinit);
  1831.         if (x < 0) return(x);
  1832.         logpkt('#',n,(CHAR *)"<reconstructed>",0); /* Log it */
  1833.         bctu = bctusav;        /* Restore block check type */
  1834.         bctl = bctlsav;        /* and length */
  1835.  
  1836.         } else {            /* Not the first packet */
  1837. /*
  1838.   It's not the first packet of the protocol operation.  It's some other packet
  1839.   that we have already ACK'd and forgotten about.  So we take a chance and
  1840.   send an empty ACK using the current block-check type.  Usually this will
  1841.   work out OK (like when acking Data packets), and no great harm will be done
  1842.   if it was some other kind of packet (F, etc).  If we are requesting an
  1843.   interruption of the file transfer, the flags are still set, so we'll catch
  1844.   up on the next packet.
  1845. */
  1846.         x = spack('Y',n,0,(CHAR *) "");
  1847.         if (x < 0) return(x);
  1848.         }
  1849.         retrans++;
  1850.         xxscreen(SCR_PT,'%',(long)pktnum,"Retransmission");
  1851.         return(0);
  1852.     } else {
  1853. /*
  1854.   Packet number is not in current or previous window.  We seem to hit this
  1855.   code occasionally at the beginning of a transaction, for apparently no good
  1856.   reason.  Let's just log it for debugging, send nothing, and try to proceed
  1857.   with the protocol rather than killing it.
  1858. */
  1859.         debug(F101,"RESEND PKT NOT IN WINDOW","",n);
  1860.         debug(F101,"RESEND k","",k);
  1861.         return(0);
  1862.     }
  1863.     }
  1864.  
  1865. /* OK, it's in the window and it's not lost. */
  1866.  
  1867.     debug(F101,"resend pktinfo index","",k);
  1868.  
  1869.     if (s_pkt[j].pk_rtr++ > maxtry) {    /* Found it but over retry limit */
  1870.     xitsta |= what;
  1871.     return(-1);
  1872.     }
  1873.     debug(F101," retry","",s_pkt[j].pk_rtr); /* OK so far */
  1874.     dumpsbuf();                /* (debugging) */
  1875.     if (s_pkt[j].pk_typ == ' ') {    /* Incompletely formed packet */
  1876.     if (nakstate) {            /* (This shouldn't happen any more) */
  1877.         nack(n);
  1878.         retrans++;
  1879.         xxscreen(SCR_PT,'%',(long)pktnum,"(resend)");
  1880.         return(s_pkt[j].pk_rtr);
  1881.     } else {            /* No packet to resend! */
  1882. #ifdef COMMENT
  1883. /*
  1884.   This happened (once) while sending a file with 2 window slots and typing
  1885.   X to the sender to cancel the file.  But since we're cancelling anyway,
  1886.   there's no need to give a scary message.
  1887. */
  1888.         sprintf((char *)epktmsg,
  1889.             "resend logic error: NPS, n=%d, j=%d.",n,j);
  1890.         return(-2);
  1891. #else
  1892. /* Just ignore it. */
  1893.         return(0);
  1894. #endif /* COMMENT */
  1895.     }
  1896.     }
  1897. #ifdef DEBUG
  1898. #ifdef GFTIMER
  1899.     if (deblog) t1 = gftimer();
  1900. #endif /* GFTIMER */
  1901. #endif /* DEBUG */
  1902.  
  1903.     /* Everything ok, send the packet */
  1904. #ifdef CK_TIMERS
  1905.     if (timint > 0)
  1906.       srttbl[n] = gtimer();        /* Update the timer */
  1907. #endif /* CK_TIMERS */
  1908.     x = ttol(s_pkt[j].pk_adr,s_pkt[j].pk_len);
  1909.  
  1910. #ifdef DEBUG
  1911. #ifdef GFTIMER
  1912.     if (deblog)  {
  1913.     t2 = gftimer();
  1914.     debug(F101,"resend ttol msec","",(long)((t2-t1)*1000.0));
  1915.     }
  1916. #endif /* GFTIMER */
  1917. #endif /* DEBUG */
  1918.     debug(F101,"resend ttol returns","",x);
  1919.  
  1920.     retrans++;                /* Count a retransmission */
  1921.     xxscreen(SCR_PT,'%',(long)pktnum,"(resend)"); /* Tell user about resend */
  1922.     logpkt('S',n,s_pkt[j].pk_adr, s_pkt[j].pk_len); /* Log the resent packet */
  1923.     return(s_pkt[j].pk_rtr);        /* Return the number of retries. */
  1924. }
  1925.  
  1926. /*  E R R P K T  --  Send an Error Packet  */
  1927.  
  1928. int
  1929. errpkt(reason) CHAR *reason; {        /* ...containing the reason given */
  1930.     extern int rtimo, state, justone;
  1931.     int x, y;
  1932.     czseen = 1;                /* Also cancels batch */
  1933.     state = 0;                /* Reset protocol state */
  1934.     debug(F110,"errpkt",reason,0);
  1935.     tlog(F110,"Protocol Error:",(char *)reason,0L);
  1936.     xxscreen(SCR_EM,0,0L,reason);
  1937.     encstr(reason);
  1938.     x = spack('E',pktnum,size,data);
  1939.     ckstrncpy((char *)epktmsg,(char *)reason,PKTMSGLEN);
  1940.     y = quiet; quiet = 1; epktsent = 1;    /* Close files silently. */
  1941.     clsif(); clsof(discard);
  1942.     quiet = y;
  1943. /*
  1944.   I just sent an E-packet.  I'm in local mode, I was receiving a file,
  1945.   I'm not a server, and sliding windows are in use.  Therefore, there are
  1946.   likely to be a bunch of packets already "in the pipe" on their way to me
  1947.   by the time the remote sender gets the E-packet.  So the next time I
  1948.   CONNECT or try to start another protocol operation, I am likely to become
  1949.   terribly confused by torrents of incoming material.  To prevent this,
  1950.   the following code soaks up packets from the connection until there is an
  1951.   error or timeout, without wasting too much time waiting.
  1952.  
  1953.   Exactly the same problem occurs when I am in remote mode or if I am
  1954.   in server mode with the justone flag set.  In remote mode not only
  1955.   does the packet data potentially get echo'd back to the sender which
  1956.   is confusing to the user in CONNECT mode, but it also may result in the
  1957.   host performing bizarre actions such as suspending the process if ^Z is
  1958.   unprefixed, etc.
  1959.  
  1960.   Furthermore, thousands of packets bytes in the data stream prevent the
  1961.   client from being able to process Telnet Kermit Option negotiations
  1962.   properly.
  1963. */
  1964. #ifdef STREAMING
  1965.     /* Because streaming sets the timeout to 0... */
  1966.     if (streaming) {
  1967.     timint = rcvtimo = rtimo;
  1968.     streaming = 0;
  1969.     }
  1970. #endif /* STREAMING */
  1971.     if (what == W_RECV &&
  1972.         (!server || server && justone) &&
  1973.         (wslots > 1 || streaming)) {
  1974. #ifdef GFTIMER
  1975.     CKFLOAT oldsec, sec = (CKFLOAT) 0.0;
  1976. #else
  1977.     int oldsec, sec = 0;
  1978. #endif /* GFTIMER */
  1979.     debug(F101,"errpkt draining","",wslots);
  1980.     xxscreen(SCR_ST,ST_MSG,0l,"Draining incoming packets, wait...");
  1981.     while (x > -1) {        /* Don't bother if no connection */
  1982.         oldsec = sec;
  1983. #ifdef GFTIMER
  1984.         sec = gftimer();
  1985.         if (oldsec != (CKFLOAT) 0.0)
  1986.           timint = rcvtimo = (int) (sec - oldsec + 0.5);
  1987. #else
  1988.         sec = gtimer();
  1989.         if (oldsec != 0)
  1990.           timint = rcvtimo = sec - oldsec + 1;
  1991. #endif /* GFTIMER */
  1992.         if (timint < 1)
  1993.           timint = rcvtimo = 1;
  1994.         msleep(50);            /* Allow a bit of slop */
  1995.         x = rpack();        /* Read a packet */
  1996.         if (x == 'T' || x == 'z')    /* Timed out means we're done */
  1997.           break;
  1998.         xxscreen(SCR_PT,x,rsn,"");    /* Let user know */
  1999.     }
  2000.     xxscreen(SCR_ST,ST_MSG,0l,"Drain complete.");
  2001.     }
  2002.     if (what < W_CONNECT)
  2003.       xitsta |= what;            /* Remember what failed. */
  2004.     success = 0;
  2005.     return(y);
  2006. }
  2007.  
  2008. /* scmd()  --  Send a packet of the given type */
  2009.  
  2010. int
  2011. #ifdef CK_ANSIC
  2012. scmd(char t, CHAR *dat)
  2013. #else
  2014. scmd(t,dat) char t; CHAR *dat;
  2015. #endif /* CK_ANSIC */
  2016. /* scmd */ {
  2017.     int x;
  2018.     extern char * srimsg;
  2019.     debug(F000,"scmd",dat,t);
  2020.     if (encstr(dat) < 0) {        /* Encode the command string */
  2021.     srimsg = "String too long";
  2022.     return(-1);
  2023.     }
  2024.     x = spack(t,pktnum,size,data);
  2025.     debug(F101,"scmd spack","",x);
  2026.     return(x);
  2027. }
  2028.  
  2029. /* Compose and Send GET packet */
  2030.  
  2031. struct opktparm {            /* O-Packet item list */
  2032.     CHAR * opktitem;
  2033.     struct opktparm * opktnext;
  2034. };
  2035.  
  2036. struct opktparm * opkthead = NULL;    /* Linked list of O-packet fields */
  2037. int opktcnt = 0;            /* O-Packet counter */
  2038. char * srimsg = NULL;            /* GET-Packet error message */
  2039.  
  2040. /* S O P K T  --  Send O-Packet */
  2041. /*
  2042.   Sends one O-Packet each time called, using first-fit method of filling
  2043.   the packet from linked list of parameters pointed to by opkthead.
  2044.   To be called repeatedly until list is empty or there is an error.
  2045.   Returns:
  2046.    -1 on failure.
  2047.     0 on success and no more fields left to send.
  2048.     1 on success but with more fields left to be sent.
  2049. */
  2050.  
  2051. int
  2052. sopkt() {
  2053.     int n = 0;                /* Field number in this packet */
  2054.     int rc = 0;                /* Return code */
  2055.     int len = 0;            /* Data field length */
  2056.     char c = NUL;
  2057.     struct opktparm * o = NULL;
  2058.     struct opktparm * t = NULL;
  2059.     struct opktparm * prev = NULL;
  2060.     CHAR * dsave = data;
  2061.     int x, ssave = spsiz;
  2062.  
  2063.     srimsg = NULL;            /* Error message */
  2064.     o = opkthead;            /* Point to head of list */
  2065.     if (!o) {                /* Oops, no list... */
  2066.     srimsg = "GET Packet Internal Error 1";
  2067.     debug(F100,"sopkt NULL list","",0);
  2068.     return(-1);
  2069.     }
  2070.     while (o) {                /* Go thru linked list... */
  2071.     c = *(o->opktitem);        /* Parameter code */
  2072.     debug(F000,"sopkt",o->opktitem,c);
  2073.     x = encstr((CHAR *)o->opktitem);
  2074.     debug(F111,"sopkt encstr",dsave,x);
  2075.     if (x < 0) {            /* Encode this item */
  2076.         if (n == 0) {        /* Failure, first field in packet */
  2077.         debug(F100,"sopkt overflow","",0);
  2078.         spsiz = ssave;        /* Restore these */
  2079.         data = dsave;
  2080.         o = opkthead;        /* Free linked list */
  2081.         while (o) {
  2082.             if (o->opktitem) free(o->opktitem);
  2083.             t = o->opktnext;
  2084.             free(o);
  2085.             o = t;
  2086.         }
  2087.         opkthead = NULL;
  2088.         srimsg = "GET Packet Too Long for Server";
  2089.         return(-1);        /* Fail */
  2090.         } else {            /* Not first field in packet */
  2091.         debug(F110,"sopkt leftover",o->opktitem,0);
  2092.         prev = o;        /* Make this one the new previous */
  2093.         o = o->opktnext;    /* Get next */
  2094.         c = NUL;        /* So we know we're not done */
  2095.         *data = NUL;        /* Erase any partial encoding */
  2096.         continue;        /* We can try this one again later */
  2097.         }
  2098.     }
  2099.     n++;                /* Encoding was successful */
  2100.     debug(F111,"sopkt field",data,x);
  2101.     len += x;            /* Total data field length */
  2102.     data += x;            /* Set up for next field... */
  2103.     spsiz -= x;
  2104.     free(o->opktitem);        /* Free item just encoded */
  2105.     if (o == opkthead) {        /* If head */
  2106.         opkthead = o->opktnext;    /* Move head to next */
  2107.         free(o);            /* Free this list node */
  2108.         o = opkthead;
  2109.     } else {            /* If not head */
  2110.         o = o->opktnext;        /* Get next */
  2111.         prev->opktnext = o;        /* Link previous to next */
  2112.     }
  2113.     if (c == '@')            /* Loop exit */
  2114.       break;
  2115.     if (!o && !opkthead) {        /* Set up End Of Parameters Field */
  2116.         o = (struct opktparm *)malloc(sizeof(struct opktparm));
  2117.         if (o) {
  2118.         opkthead = o;
  2119.         if (!(o->opktitem = (CHAR *)malloc(3))) {
  2120.             free(o);
  2121.             srimsg = "GET Packet Internal Error 8";
  2122.             return(-1);
  2123.         }
  2124.         strcpy((char *)(o->opktitem), "@ ");
  2125.         debug(F111,"sopkt o->opktitem",o->opktitem,
  2126.               strlen((char *)(o->opktitem)));
  2127.         o->opktnext = NULL;
  2128.         }
  2129.     }
  2130.     }
  2131.     data = dsave;            /* Restore globals */
  2132.     spsiz = ssave;
  2133.     debug(F110,"sopkt data",data,0);
  2134.     debug(F101,"sopkt opktcnt","",opktcnt);
  2135.     if (opktcnt++ > 0) {
  2136.     if (nxtpkt() < 0) {        /* Get next packet number and buffer */
  2137.         srimsg = "GET Packet Internal Error 9";
  2138.         return(-1);
  2139.     }
  2140.     }
  2141.     debug(F101,"sopkt pktnum","",pktnum);
  2142.     rc = spack((char)'O',pktnum,len,data); /* Send O-Packet */
  2143.     debug(F101,"sopkt spack","",rc);
  2144.     if (rc < 0)                /* Failed */
  2145.       srimsg = "Send Packet Failure";    /* Set message */
  2146.     else                /* Succeeded */
  2147.       rc = (c == '@') ? 0 : 1;        /* 1 = come back for more, 0 = done */
  2148.     debug(F101,"sopkt rc","",rc);
  2149.     return(rc);
  2150. }
  2151.  
  2152. /* S R I N I T  --  Send GET packet  */
  2153. /*
  2154.   Sends the appropriate GET-Class packet.
  2155.   Returns:
  2156.   -1 on error
  2157.    0 if packet sent successfully and we can move on to the next state
  2158.    1 if an O-packet was sent OK but more O packets still need to be sent.
  2159. */
  2160. int
  2161. srinit(reget, retrieve, opkt) int reget, retrieve, opkt; {
  2162.     int x = 0;
  2163.     extern int oopts, omode;
  2164.     CHAR * p = NULL;
  2165. #ifdef RECURSIVE
  2166.     extern int recursive;
  2167.     debug(F101,"srinit recursive","",recursive);
  2168. #endif /* RECURSIVE */
  2169.     debug(F101,"srinit reget","",reget);
  2170.     debug(F101,"srinit retrieve","",retrieve);
  2171.     debug(F101,"srinit opkt","",opkt);
  2172.     debug(F101,"srinit oopts","",oopts);
  2173.     debug(F101,"srinit omode","",omode);
  2174.     debug(F110,"srinit cmarg",cmarg,0);
  2175.     srimsg = NULL;
  2176.  
  2177.     opktcnt = 0;
  2178.     if (!cmarg) cmarg = "";
  2179.     if (!*cmarg) {
  2180.     srimsg = "GET with no filename";
  2181.     debug(F100,"srinit null cmarg","",0);
  2182.     return(-1);
  2183.     }
  2184.     if (opkt) {                /* Extended GET is totally different */
  2185.     char buf[8];
  2186.     struct opktparm * o = NULL;
  2187.     struct opktparm * prev = NULL;
  2188.  
  2189.         buf[0] = NUL;
  2190.  
  2191.     /* Build O-Packet fields and send (perhaps first) O-Packet */
  2192.  
  2193.     if (oopts > -1) {        /* Write Option flags */
  2194.         o = (struct opktparm *)malloc(sizeof(struct opktparm));
  2195.         if (!o) {
  2196.         srimsg = "GET Packet Internal Error 2";
  2197.         debug(F100,"srinit malloc fail O1","",0);
  2198.         return(-1);
  2199.         }
  2200.         sprintf(buf,"Ox%d",oopts);
  2201.         x = (int) strlen(buf+2);
  2202.         buf[1] = tochar(x);
  2203.         o->opktitem = (CHAR *)malloc(x + 3);
  2204.         if (!o->opktitem) {
  2205.         srimsg = "GET Packet Internal Error 3";
  2206.         debug(F100,"srinit malloc fail O2","",0);
  2207.         return(-1);
  2208.         }
  2209.         strcpy((char *)(o->opktitem),buf);
  2210.         o->opktnext = NULL;
  2211.         if (!opkthead)
  2212.           opkthead = o;
  2213.         prev = o;
  2214.     }
  2215.     if (omode > -1) {        /* If Xfer Mode specified, write it */
  2216.         o = (struct opktparm *)malloc(sizeof(struct opktparm));
  2217.         if (!o) {
  2218.         srimsg = "GET Packet Internal Error 4";
  2219.         debug(F100,"srinit malloc fail M1","",0);
  2220.         return(-1);
  2221.         }
  2222.         sprintf(buf,"Mx%d",omode);
  2223.         x = (int) strlen(buf+2);
  2224.         buf[1] = tochar(x);
  2225.         o->opktitem = (CHAR *)malloc(x + 3);
  2226.         if (!o->opktitem) {
  2227.         srimsg = "GET Packet Internal Error 5";
  2228.         debug(F100,"srinit malloc fail O2","",0);
  2229.         return(-1);
  2230.         }
  2231.         strcpy((char *)(o->opktitem),buf);
  2232.         o->opktnext = NULL;
  2233.         if (!opkthead)
  2234.           opkthead = o;
  2235.         else
  2236.           prev->opktnext = o;
  2237.         prev = o;
  2238.     }
  2239.  
  2240.     /* Same deal for oname and opath eventually but not needed now... */
  2241.  
  2242.     x = strlen(cmarg);        /* Now do filename */
  2243.     if (x > spsiz - 4) {
  2244.         srimsg = "GET Packet Too Long for Server";
  2245.         return(-1);
  2246.     }
  2247.     o = (struct opktparm *)malloc(sizeof(struct opktparm));
  2248.     if (!o) {
  2249.         srimsg = "GET Packet Internal Error 6";
  2250.         debug(F100,"srinit malloc fail F1","",0);
  2251.         return(-1);
  2252.     }
  2253.     o->opktitem = (CHAR *)malloc(x + 3);
  2254.     if (!o->opktitem) {
  2255.         srimsg = "GET Packet Internal Error 7";
  2256.         debug(F100,"srinit malloc fail F2","",0);
  2257.         return(-1);
  2258.     }
  2259.     p = o->opktitem;
  2260.     *p++ = 'F';
  2261.     if (x > 94) {            /* Too long for normal length */
  2262.         *p++ = SYN;            /* Escape length with Ctrl-V */
  2263.         *p++ = tochar(x / 95);
  2264.         *p++ = tochar(x % 95);
  2265.     } else {            /* Normal encoding for 94 or less */
  2266.         *p++ = tochar(x);
  2267.     }
  2268.     strcpy((char *)p,cmarg);    /* Copy the filename */
  2269.     o->opktnext = NULL;
  2270.     if (!opkthead)
  2271.       opkthead = o;
  2272.     else
  2273.       prev->opktnext = o;
  2274.     prev = o;
  2275.  
  2276.     /* End of Parameters */
  2277.  
  2278.     prev->opktnext = NULL;        /* End of list. */
  2279.     return(sopkt());
  2280.     }
  2281.  
  2282.     /* Not Extended GET */
  2283.  
  2284.     if (encstr((CHAR *)cmarg) < 0) {    /* Encode the filename. */
  2285.     srimsg = "GET Packet Too Long for Server";
  2286.     return(-1);
  2287.     }
  2288.     if (retrieve) {            /* Send the packet. */
  2289. #ifdef RECURSIVE
  2290.     if (recursive)
  2291.       x = spack((char)'W',pktnum,size,data); /* GET /DELETE /RECURSIVE */
  2292.     else
  2293. #endif /* RECURSIVE */
  2294.       x = spack((char)'H',pktnum,size,data); /* GET /DELETE */
  2295.     }
  2296. #ifdef RECURSIVE
  2297.     else if (recursive)
  2298.       x = spack((char)'V',pktnum,size,data); /* GET /RECURSIVE */
  2299. #endif /* RECURSIVE */
  2300.     else
  2301.       x = spack((char)(reget ? 'J' : 'R'),pktnum,size,data); /* GET */
  2302.     if (x < 0)
  2303.       srimsg = "Send Packet Failure";
  2304.     return(x < 0 ? x : 0);
  2305. }
  2306.  
  2307.  
  2308. /*  K S T A R T  --  Checks for a Kermit packet while in terminal mode.  */
  2309.  
  2310. /*  (or command mode...)  */
  2311.  
  2312. #ifdef CK_AUTODL
  2313. int
  2314. #ifdef CK_ANSIC
  2315. kstart(CHAR ch)
  2316. #else
  2317. kstart(ch) CHAR ch;
  2318. #endif /* CK_ANSIC */
  2319. /* kstart */ {
  2320.     static CHAR * p = NULL;
  2321.  
  2322. #ifdef OS2
  2323.     static CHAR * pk = NULL;
  2324. #endif /* OS2 */
  2325.     ch &= 0177;                /* Strip 8th bit */
  2326.  
  2327.     /* Because we're in cooked mode at the command prompt... */
  2328.  
  2329.     if (ch == LF) {
  2330.     debug(F110,"kstart","ch == LF",0);
  2331.     if ((what == W_COMMAND || what == W_INIT || what == W_NOTHING)) {
  2332.         if (eol == CR) {
  2333.         ch = eol;
  2334.         debug(F110,"kstart","ch = CR",0);
  2335.         }
  2336.     }
  2337.     }
  2338.  
  2339. #ifdef OS2
  2340.     if (adl_kmode == ADL_STR) {
  2341.     if (!ch)
  2342.       return(0);
  2343.     if (!pk)
  2344.       pk = adl_kstr;
  2345.  
  2346.     if (ch == *pk) {
  2347.         pk++;
  2348.         if (*pk == '\0') {
  2349.         pk = adl_kstr;
  2350.         debug(F100, "kstart Kermit Start String","",0);
  2351.         return(PROTO_K + 1);
  2352.         }
  2353.     } else
  2354.       pk = adl_kstr;
  2355.     }
  2356. #endif /* OS2 */
  2357.  
  2358.     if (ch == stchr) {            /* Start of packet */
  2359.         if (what == W_COMMAND)
  2360.       kstartactive = 1;
  2361.     p = ksbuf;
  2362.     *p = ch;
  2363.     debug(F101,"kstart SOP","",ch);
  2364.     } else if (ch == eol) {        /* End of packet */
  2365.     kstartactive = 0;
  2366.     if (p) {
  2367.         debug(F101,"kstart EOL","",ch);
  2368.         p++;
  2369.         if (p - ksbuf < 94 ) {
  2370.         int rc = 0;
  2371.         *p++ = ch;
  2372.         *p = NUL;
  2373.         rc = chkspkt((char *)ksbuf);
  2374.         debug(F111,"kstart EOP chkspkt", ksbuf, rc);
  2375.         p = NULL;
  2376.         if (!rc) return(0);
  2377.         if (rc == 2) rc = -1;
  2378.         debug(F111,"kstart ksbuf",ksbuf,rc);
  2379.         return(rc);
  2380.         } else {
  2381.         debug(F110,"kstart","p - ksbuf >= 94",0);
  2382.         p = NULL;
  2383.         }
  2384.     }
  2385.     } else if (p) {
  2386.     if (ch < SP)
  2387.       kstartactive = 0;
  2388.     p++;
  2389.     if (p - ksbuf < 94) {
  2390.         *p = ch;
  2391.     } else {
  2392.         p = NULL;
  2393.         debug(F110,"kstart","p - ksbuf >= 94",0);
  2394.     }
  2395.     }
  2396.     return(0);
  2397. }
  2398.  
  2399. #ifdef CK_XYZ
  2400.  
  2401. /*  Z S T A R T  --  Checks for a ZMODEM packet while in terminal mode.  */
  2402.  
  2403. int
  2404. #ifdef CK_ANSIC
  2405. zstart(CHAR ch)
  2406. #else
  2407. zstart(ch) CHAR ch;
  2408. #endif /* CK_ANSIC */
  2409. /* zstart */ {
  2410.     static CHAR * matchstr = (CHAR *) "\030B00";
  2411.     /* "rz\r**\030B00000000000000\r\033J\021"; */
  2412.     static CHAR * p = NULL;
  2413.     extern int inserver;
  2414.  
  2415.     if (inserver)
  2416.       return(0);
  2417.  
  2418.     if (!ch)
  2419.       return(0);
  2420.     if (!p) {
  2421. #ifdef OS2
  2422.     p = adl_zmode == ADL_PACK ? matchstr : adl_zstr;
  2423. #else
  2424.     p = matchstr;
  2425. #endif /* OS2 */
  2426.     }
  2427.     if (ch == *p) {
  2428.     p++;
  2429.     if (*p == '\0') {
  2430. #ifdef OS2
  2431.         if (adl_zmode == ADL_PACK) {
  2432.         p = matchstr;
  2433.         debug(F100, "zstart Zmodem SOP","",0);
  2434.         } else {
  2435.         p = adl_zstr;
  2436.         debug(F100, "zstart Zmodem Start String","",0);
  2437.         }
  2438. #else
  2439.         p = matchstr;
  2440.         debug(F100, "zstart Zmodem SOP","",0);
  2441. #endif /* OS2 */
  2442.         return(PROTO_Z + 1);
  2443.     }
  2444.     } else {
  2445. #ifdef OS2
  2446.     p = adl_zmode == ADL_PACK ? matchstr : adl_zstr;
  2447. #else
  2448.     p = matchstr;
  2449. #endif /* OS2 */
  2450.     }
  2451.     return(0);
  2452. }
  2453. #endif /* CK_XYZ */
  2454.  
  2455. #ifndef NOICP
  2456. #ifdef CK_APC
  2457. /*  A U T O D O W N  */
  2458.  
  2459. #ifdef CK_ANSIC
  2460. VOID
  2461. autodown(int ch)
  2462. #else
  2463. VOID
  2464. autodown(ch) int ch;
  2465. #endif /* CK_ANSIC */
  2466. /* autodown */ {
  2467.  
  2468. /* The Kermit and Zmodem Auto-download calls go here */
  2469.  
  2470.     extern int justone;            /* From protocol module */
  2471.     extern int debses, protocol, apcactive, autodl, inautodl;
  2472. #ifdef DCMDBUF
  2473.     extern char *apcbuf;
  2474. #else
  2475.     extern char apcbuf[];
  2476. #endif /* DCMDBUF */
  2477. #ifdef OS2
  2478.     extern int apclength, term_io;
  2479. #endif /* OS2 */
  2480.     int k = 0;
  2481.  
  2482.     if ((autodl || inautodl
  2483. #ifdef IKS_OPTION
  2484.      || TELOPT_SB(TELOPT_KERMIT).kermit.me_start
  2485. #endif /* IKS_OPTION */
  2486.      ) && !debses) {
  2487. #ifdef CK_XYZ
  2488. #ifdef XYZ_INTERNAL
  2489.     extern int p_avail;
  2490. #else
  2491.     int p_avail = 1;
  2492. #endif /* XYZ_INTERNAL */
  2493.     if (p_avail && zstart((CHAR) ch)) {
  2494.         debug(F100, "Zmodem download","",0);
  2495.             strcpy(apcbuf,"receive /protocol:zmodem");
  2496.         apcactive = APC_LOCAL;
  2497. #ifdef OS2
  2498.         apclength = strlen(apcbuf) ;
  2499.         term_io = FALSE;        /* Disable Emulator I/O */
  2500.         SetConnectMode(FALSE);
  2501. #endif /* OS2 */
  2502.         return;
  2503.     }
  2504. #endif /* CK_XYZ */
  2505.  
  2506.     /* First try... */
  2507.     k = kstart((CHAR) ch);
  2508.     if (
  2509. #ifdef NOSERVER
  2510.         k > 0
  2511. #else /* NOSERVER */
  2512.         k
  2513. #endif /* NOSERVER */
  2514.         ) {                /* We saw a valid S or I packet */
  2515.         if (k < 0) {        /* Stuff RECEIVE into APC buffer */
  2516.         justone = 1;
  2517.         switch (protocol) {
  2518. #ifdef CK_XYZ
  2519.           case PROTO_G:
  2520.             strcpy(apcbuf,"set proto kermit, server, set protocol g");
  2521.             break;
  2522.           case PROTO_X:
  2523.             strcpy(apcbuf,"set proto kermit,server,set proto xmodem");
  2524.             break;
  2525.                   case PROTO_XC:
  2526.             strcpy(apcbuf,
  2527.                "set proto kermit,server,set proto xmodem-crc");
  2528.                       break;
  2529.           case PROTO_Y:
  2530.             strcpy(apcbuf,"set proto kermit,server, set protocol y");
  2531.             break;
  2532.           case PROTO_Z:
  2533.             strcpy(apcbuf,"set proto kermit,server,set proto zmodem");
  2534.             break;
  2535. #endif /* CK_XYZ */
  2536.           case PROTO_K:
  2537.             strcpy(apcbuf,"server");
  2538.             break;
  2539.         }
  2540.         } else {
  2541.         justone = 0;
  2542.                 strcpy(apcbuf,"receive /protocol:kermit");
  2543.         }
  2544.         apcactive = APC_LOCAL;
  2545. #ifdef OS2
  2546.         apclength = strlen(apcbuf);
  2547.         term_io = FALSE;        /* Stop handling I/O */
  2548.         SetConnectMode(FALSE);    /* Waiting for a timeout to occur */
  2549. #endif /* OS2 */
  2550.         return;
  2551.     }
  2552.     }
  2553. }
  2554. #endif /* CK_APC */
  2555. #endif /* NOICP */
  2556.  
  2557. /*  C H K S P K T  --  Check if buf contains a valid S or I packet  */
  2558.  
  2559. int
  2560. chkspkt(buf) char *buf; {
  2561.     int buflen;
  2562.     int len = -1;
  2563.     CHAR chk;
  2564.     char type = 0;
  2565.     char *s = buf;
  2566.  
  2567.     if (!buf) return(0);
  2568.     buflen = strlen(buf);
  2569.     if (buflen < 5) return(0);        /* Too short */
  2570.     if (*s++ != stchr) return(0);    /* SOH */
  2571.     len = xunchar(*s++);        /* Length */
  2572.     if (len < 0) return(0);
  2573.     if (*s++ != SP) return(0);        /* Sequence number */
  2574.     type = *s++;            /* Type */
  2575.     if (type != 'S' && type != 'I')
  2576.       return(0);
  2577.     if (buflen < len + 2) return(0);
  2578.     s += (len - 3);            /* Position of checksum */
  2579.     chk = (CHAR) (*s);            /* Checksum */
  2580.     *s = NUL;
  2581.     if (xunchar(chk) != chk1((CHAR *)(buf+1),buflen-2)) /* Check it */
  2582.       return(0);
  2583.     *s = chk;
  2584.     return(type == 'S' ? 1 : 2);
  2585. }
  2586. #endif /* CK_AUTODL */
  2587.  
  2588. /* R P A C K  --  Read a Packet */
  2589.  
  2590. /*
  2591.   rpack reads a packet and returns the packet type, or else Q if the
  2592.   packet was invalid, or T if a timeout occurred.  Upon successful return,
  2593.   sets the values of global rsn (received sequence number),  rln (received
  2594.   data length), and rdatap (pointer to null-terminated data field), and
  2595.   returns the packet type.  NOTE: This is an inner-loop function so must be
  2596.   efficient.  Protect function calls by if-tests where possible, e.g.
  2597.   "if (pktlog) logpkt(...);".
  2598. */
  2599. int
  2600. rpack() {
  2601.     register int i, j, x, lp;        /* Local variables */
  2602. #ifdef CKTUNING
  2603.     unsigned int chk;
  2604. #endif /* CKTUNING */
  2605.     int k, type, chklen;
  2606.     unsigned crc;
  2607.     CHAR pbc[5];            /* Packet block check */
  2608.     CHAR *sohp;                /* Pointer to SOH */
  2609.     CHAR e;                /* Packet end character */
  2610.  
  2611. #ifdef GFTIMER
  2612.     CKFLOAT t1 = 0.0, t2 = 0.0;
  2613. #endif /* GFTIMER */
  2614.  
  2615.     debug(F101,"rpack pktnum","",pktnum);
  2616.  
  2617. #ifndef OLDCHKINT
  2618.     if (chkint() < 0)            /* Check for console interrupts. */
  2619.       return('z');
  2620. #endif /* OLDCHKINT */
  2621.  
  2622.     k = getrbuf();            /* Get a new packet input buffer. */
  2623.     /* debug(F101,"rpack getrbuf","",k); */
  2624.     if (k < 0) {            /* Return like this if none free. */
  2625.     return(-1);
  2626.     }
  2627.     recpkt = r_pkt[k].bf_adr;
  2628.     *recpkt = '\0';            /* Clear receive buffer. */
  2629.     sohp = recpkt;            /* Initialize pointers to it. */
  2630.     rdatap = recpkt;
  2631.     rsn = rln = -1;            /* In case of failure. */
  2632.     e = (turn) ? turnch : eol;        /* Use any handshake char for eol */
  2633.  
  2634. /* Try to get a "line". */
  2635.  
  2636. #ifdef CK_AUTODL
  2637.     debug(F110,"rpack ksbuf",ksbuf,0);
  2638.     if (ksbuf[0]) {            /* Kermit packet already */
  2639.     int x;                /* collected for us in CONNECT mode */
  2640.     CHAR *s1 = recpkt, *s2 = ksbuf;
  2641.     j = 0;
  2642.     while (*s2) {            /* Copy and get length */
  2643.         *s1++ = *s2++;        /* No point optimizing this since */
  2644.         j++;            /* it's never more than ~20 chars */
  2645.     }
  2646.     *s1 = NUL;
  2647. #ifdef PARSENSE
  2648.     x = parchk(recpkt, stchr, j);    /* Check parity */
  2649.     debug(F000,"autodownload parity","",parity);
  2650.     debug(F000,"autodownload parchk","",x);
  2651.     if (x > -1 && parity != x) {
  2652.         autopar = 1;
  2653.         parity = x;
  2654.     }
  2655. #endif /* PARSENSE */
  2656.     ksbuf[0] = NUL;            /* Don't do this next time! */
  2657.  
  2658.     } else {                /* Normally go read a packet */
  2659. #endif /* CK_AUTODL */
  2660.  
  2661. #ifdef DEBUG
  2662.     if (deblog) {
  2663.         debug(F101,"rpack timint","",timint);
  2664.         debug(F101,"rpack rcvtimo","",rcvtimo);
  2665.         debug(F101,"rpack streaming","",streaming);
  2666. #ifdef GFTIMER
  2667.         /* Measure how long it takes to read a packet */
  2668.         t1 = gftimer();
  2669. #endif /* GFTIMER */
  2670.     }
  2671. #endif /* DEBUG */
  2672.  
  2673. /* JUST IN CASE (otherwise this could clobber streaming) */
  2674.  
  2675.     if ((timint == 0 || streaming) && rcvtimo != 0) {
  2676.         debug(F101,"rpack timint 0 || streaming but rcvtimo","",rcvtimo);
  2677.         rcvtimo = 0;
  2678.     }
  2679.  
  2680. #ifdef PARSENSE
  2681. #ifdef UNIX
  2682. /*
  2683.   So far the final turn argument is only for ck[uvdl]tio.c.  Should be added
  2684.   to the others too.  (turn == handshake character.)
  2685. */
  2686.     j = ttinl(recpkt,r_pkt[k].bf_len - 1,rcvtimo,e,stchr,turn);
  2687. #else
  2688. #ifdef VMS
  2689.     j = ttinl(recpkt,r_pkt[k].bf_len - 1,rcvtimo,e,stchr,turn);
  2690. #else
  2691. #ifdef datageneral
  2692.     j = ttinl(recpkt,r_pkt[k].bf_len - 1,rcvtimo,e,stchr,turn);
  2693. #else
  2694. #ifdef STRATUS
  2695.     j = ttinl(recpkt,r_pkt[k].bf_len - 1,rcvtimo,e,stchr,turn);
  2696. #else
  2697. #ifdef OS2
  2698.     j = ttinl(recpkt,r_pkt[k].bf_len - 1,rcvtimo,e,stchr,turn);
  2699. #else
  2700. #ifdef OSK
  2701.     j = ttinl(recpkt,r_pkt[k].bf_len - 1,rcvtimo,e,stchr,turn);
  2702. #else
  2703.     j = ttinl(recpkt,r_pkt[k].bf_len - 1,rcvtimo,e,stchr);
  2704. #endif /* OSK */
  2705. #endif /* OS2 */
  2706. #endif /* STRATUS */
  2707. #endif /* datageneral */
  2708. #endif /* VMS */
  2709. #endif /* UNIX */
  2710.     if (parity != 0 && parity != 's' && ttprty != 0) {
  2711.         if (parity != ttprty) autopar = 1;
  2712.         parity = ttprty;
  2713.     }
  2714. #else /* !PARSENSE */
  2715.     j = ttinl(recpkt,r_pkt[k].bf_len - 1,rcvtimo,e);
  2716. #endif /* PARSENSE */
  2717.  
  2718. #ifdef DEBUG
  2719.     if (deblog)  {
  2720.         debug(F101,"rpack ttinl len","",j);
  2721. #ifdef GFTIMER
  2722.         t2 = gftimer();
  2723.         debug(F101,"rpack ttinl msec","",(long)((t2-t1)*1000.0));
  2724. #endif /* GFTIMER */
  2725.     }
  2726. #endif /* DEBUG */
  2727.  
  2728.     if (j < 0) {
  2729.         /* -1 == timeout, -2 == ^C, -3 == connection lost or fatal i/o */
  2730.         debug(F101,"rpack: ttinl fails","",j); /* Otherwise, */
  2731.         freerbuf(k);        /* Free this buffer */
  2732.         if (j < -1) {        /* Bail out if ^C^C typed. */
  2733.         if (j == -2) {
  2734.             interrupted = 1;
  2735.             debug(F101,"rpack ^C server","",server);
  2736.             debug(F101,"rpack ^C en_fin","",en_fin);
  2737.         } else if (j == -3) {
  2738.             fatalio = 1;
  2739.             debug(F101,"rpack fatalio","",en_fin);
  2740.         }
  2741.         return(j);
  2742.         }
  2743.         if (nakstate)        /* j == -1 is a read timeout */
  2744.           xxscreen(SCR_PT,'T',(long)winlo,"");
  2745.         else
  2746.           xxscreen(SCR_PT,'T',(long)pktnum,"");
  2747.         logpkt('r',-1,(CHAR *)"<timeout>",0);
  2748.         if (flow == 1) ttoc(XON);    /* In case of Xoff blockage. */
  2749.         return('T');
  2750.     }
  2751. #ifdef CK_AUTODL
  2752.     }
  2753. #endif /* CK_AUTODL */
  2754.  
  2755.     rpktl = j;
  2756.     tlci += j;                /* All OK, Count the characters. */
  2757.     flci += j;
  2758.  
  2759. /* Find start of packet */
  2760.  
  2761. #ifndef PARSENSE
  2762.     for (i = 0; (recpkt[i] != stchr) && (i < j); i++)
  2763.       sohp++;                /* Find mark */
  2764.     if (i++ >= j) {            /* Didn't find it. */
  2765.     logpkt('r',-1,"<timeout>",0);
  2766.     freerbuf(k);
  2767.     return('T');
  2768.     }
  2769. #else
  2770.     i = 1;                /* ttinl does this for us */
  2771. #endif /* PARSENSE */
  2772.  
  2773.     rpackets++;                /* Count received packet. */
  2774.     lp = i;                /* Remember LEN position. */
  2775.     if ((j = xunchar(recpkt[i++])) == 0) { /* Get packet length.  */
  2776.         if ((j = lp+5) > MAXRP) {    /* Long packet */
  2777.         return('Q');        /* Too long */
  2778.     }
  2779.  
  2780. #ifdef CKTUNING
  2781.     /* Save some function-call and loop overhead... */
  2782. #ifdef COMMENT
  2783.     /* ttinl() already removed parity */
  2784.     if (parity)
  2785. #endif /* COMMENT */
  2786.       chk = (unsigned) ((unsigned) recpkt[i-1] +
  2787.                 (unsigned) recpkt[i]   +
  2788.                 (unsigned) recpkt[i+1] +
  2789.                 (unsigned) recpkt[i+2] +
  2790.                 (unsigned) recpkt[i+3]
  2791.                 );
  2792. #ifdef COMMENT
  2793.     else
  2794.       chk = (unsigned) ((unsigned) (recpkt[i-1] & 077) +
  2795.                 (unsigned) (recpkt[i]   & 077) +
  2796.                 (unsigned) (recpkt[i+1] & 077) +
  2797.                 (unsigned) (recpkt[i+2] & 077) +
  2798.                 (unsigned) (recpkt[i+3] & 077)
  2799.                 );
  2800. #endif /* COMMENT */
  2801.     if (xunchar(recpkt[j]) != ((((chk & 0300) >> 6) + chk) & 077))
  2802. #else
  2803.     x = recpkt[j];            /* Header checksum. */
  2804.     recpkt[j] = '\0';        /* Calculate & compare. */
  2805.     if (xunchar(x) != chk1(recpkt+lp,5))
  2806. #endif /* CKTUNING */
  2807.       {
  2808.           freerbuf(k);
  2809.           logpkt('r',-1,(CHAR *)"<crunched:hdr>",0);
  2810.           xxscreen(SCR_PT,'%',(long)pktnum,"Bad packet header");
  2811.           return('Q');
  2812.       }
  2813. #ifndef CKTUNING
  2814.     recpkt[j] = x;            /* Checksum ok, put it back. */
  2815. #endif /* CKTUNING */
  2816.     rln = xunchar(recpkt[j-2]) * 95 + xunchar(recpkt[j-1]) - bctl;
  2817.     j = 3;                /* Data offset. */
  2818.     } else if (j < 3) {
  2819.     debug(F101,"rpack packet length less than 3","",j);
  2820.     freerbuf(k);
  2821.     logpkt('r',-1,(CHAR *)"<crunched:len>",0);
  2822.     xxscreen(SCR_PT,'%',(long)pktnum,"Bad packet length");
  2823.     return('Q');
  2824.     } else {
  2825.     rln = j - bctl - 2;        /* Regular packet */
  2826.     j = 0;                /* No extended header */
  2827.     }
  2828.     rsn = xunchar(recpkt[i++]);        /* Sequence number */
  2829.     if (pktlog)                /* Save a function call! */
  2830.       logpkt('r',rsn,sohp,rln+bctl+j+4);
  2831.     if (rsn < 0 || rsn > 63) {
  2832.     debug(F101,"rpack bad sequence number","",rsn);
  2833.     freerbuf(k);
  2834.     if (pktlog)
  2835.       logpkt('r',rsn,(CHAR *)"<crunched:seq>",0);
  2836.     xxscreen(SCR_PT,'%',(long)pktnum,"Bad sequence number");
  2837.     return('Q');
  2838.     }
  2839. /*
  2840.   If this packet has the same type as the packet just sent, assume it is
  2841.   an echo and ignore it.  Don't even bother with the block check calculation:
  2842.   even if the packet is corrupted, we don't want to NAK an echoed packet.
  2843.   Nor must we NAK an ACK or NAK.
  2844. */
  2845.     type = recpkt[i++];            /* Get packet's TYPE field */
  2846.     if (type == sndtyp || (nakstate && (type == 'N' /* || type == 'Y' */ ))) {
  2847.     debug(F000,"rpack echo","",type); /* If it's an echo */
  2848.     freerbuf(k);            /* Free this buffer */
  2849.     logpkt('#',rsn,(CHAR *)"<echo:ignored>",0);
  2850.     return('e');            /* Return special (lowercase) code */
  2851.     }
  2852. /*
  2853.   Separate the data from the block check, accounting for the case where
  2854.   a packet was retransmitted after the block check switched.
  2855. */
  2856.     if (type == 'I' || type == 'S') {    /* I & S packets always have type 1 */
  2857.     chklen = 1;
  2858.     rln = rln + bctl - 1;
  2859.     } else if (type == 'N') {        /* A NAK packet never has data */
  2860.     chklen = xunchar(recpkt[lp]) - 2;
  2861.     rln = rln + bctl - chklen;
  2862.     } else chklen = bctl;
  2863. #ifdef DEBUG
  2864.     if (deblog) {            /* Save 2 function calls */
  2865.     debug(F101,"rpack bctl","",bctl);
  2866.     debug(F101,"rpack chklen","",chklen);
  2867.     }
  2868. #endif /* DEBUG */
  2869.     i += j;                /* Buffer index of DATA field */
  2870.     rdatap = recpkt+i;            /* Pointer to DATA field */
  2871.     if ((j = rln + i) > r_pkt[k].bf_len) { /* Make sure it fits */
  2872.     debug(F101,"packet too long","",j);
  2873.     freerbuf(k);
  2874.     logpkt('r',rsn,(CHAR *)"<overflow>",0);
  2875.     return('Q');
  2876.     }
  2877.     for (x = 0; x < chklen; x++)    /* Copy the block check */
  2878.       pbc[x] = recpkt[j+x];        /* 3 bytes at most. */
  2879.     pbc[x] = '\0';            /* Null-terminate block check string */
  2880.     recpkt[j] = '\0';            /* and the packet Data field. */
  2881.  
  2882.     if (chklen == 2 && bctu == 4) {    /* Adjust for Blank-Free-2 */
  2883.     chklen = 4;            /* (chklen is now a misnomer...) */
  2884.     debug(F100,"rpack block check B","",0);
  2885.     }
  2886.     switch (chklen) {            /* Check the block check */
  2887.       case 1:                /* Type 1, 6-bit checksum */
  2888.     if (xunchar(*pbc) != chk1(recpkt+lp,j-lp)) {
  2889. #ifdef DEBUG
  2890.         if (deblog) {
  2891.         debug(F110,"checked chars",recpkt+lp,0);
  2892.         debug(F101,"block check (1)","",(int) xunchar(*pbc));
  2893.         debug(F101,"should be (1)","",chk1(recpkt+lp,j-lp));
  2894.         }
  2895. #endif /* DEBUG */
  2896.         freerbuf(k);
  2897.         logpkt('r',-1,(CHAR *)"<crunched:chk1>",0);
  2898.         xxscreen(SCR_PT,'%',(long)pktnum,"Checksum error");
  2899.         return('Q');
  2900.     }
  2901.     break;
  2902.       case 2:                /* Type 2, 12-bit checksum */
  2903.     x = xunchar(*pbc) << 6 | xunchar(pbc[1]);
  2904.     if (x != chk2(recpkt+lp,j-lp)) { /* No match */
  2905.         if (type == 'E') {        /* Allow E packets to have type 1 */
  2906.         recpkt[j++] = pbc[0];
  2907.         recpkt[j] = '\0';
  2908.         if (xunchar(pbc[1]) == chk1(recpkt+lp,j-lp))
  2909.           break;
  2910.         else
  2911.           recpkt[--j] = '\0';
  2912.         }
  2913. #ifdef DEBUG
  2914.         if (deblog) {
  2915.         debug(F110,"checked chars",recpkt+lp,0);
  2916.         debug(F101,"block check (2)","", x);
  2917.         debug(F101,"should be (2)","", (int) chk2(recpkt+lp,j-lp));
  2918.         }
  2919. #endif /* DEBUG */
  2920.         freerbuf(k);
  2921.         logpkt('r',-1,(CHAR *)"<crunched:chk2>",0);
  2922.         xxscreen(SCR_PT,'%',(long)pktnum,"Checksum error");
  2923.         return('Q');
  2924.     }
  2925.     break;
  2926.       case 3:                /* Type 3, 16-bit CRC */
  2927.     crc = (xunchar(pbc[0]) << 12)
  2928.         | (xunchar(pbc[1]) << 6)
  2929.         | (xunchar(pbc[2]));
  2930.     if (crc != chk3(recpkt+lp,j-lp)) {
  2931.         if (type == 'E') {        /* Allow E packets to have type 1 */
  2932.         recpkt[j++] = pbc[0];
  2933.         recpkt[j++] = pbc[1];
  2934.         recpkt[j] = '\0';
  2935.         if (xunchar(pbc[2]) == chk1(recpkt+lp,j-lp))
  2936.           break;
  2937.         else { j -=2; recpkt[j] = '\0'; }
  2938.         }
  2939. #ifdef DEBUG
  2940.         if (deblog) {
  2941.         debug(F110,"checked chars",recpkt+lp,0);
  2942.         debug(F101,"block check (3)","",xunchar(*pbc));
  2943.         debug(F101,"should be (3)","",(int) chk3(recpkt+lp,j-lp));
  2944.         }
  2945. #endif /* DEBUG */
  2946.         freerbuf(k);
  2947.         logpkt('r',-1,(CHAR *)"<crunched:chk3>",0);
  2948.         xxscreen(SCR_PT,'%',(long)pktnum,"CRC error");
  2949.         return('Q');
  2950.     }
  2951.     break;
  2952.       case 4:                /* Type 4 = Type 2, no blanks. */
  2953.     x = (unsigned)((xunchar(*pbc) - 1) << 6) |
  2954.       (unsigned)(xunchar(pbc[1]) - 1);
  2955.     if (x != chk2(recpkt+lp,j-lp)) {
  2956.         if (type == 'E') {    /* Allow E packets to have type 1 */
  2957.         recpkt[j++] = pbc[0];
  2958.         recpkt[j] = '\0';
  2959.         if (xunchar(pbc[1]) == chk1(recpkt+lp,j-lp))
  2960.           break;
  2961.         else
  2962.           recpkt[--j] = '\0';
  2963.         }
  2964.         debug(F101,"bad type B block check","",x);
  2965.         freerbuf(k);
  2966.         logpkt('r',-1,(CHAR *)"<crunched:chkb>",0);
  2967.         xxscreen(SCR_PT,'%',(long)pktnum,"Checksum error");
  2968.         return('Q');
  2969.     }
  2970.     break;
  2971.       default:            /* Shouldn't happen... */
  2972.     freerbuf(k);
  2973.     logpkt('r',-1,(CHAR *)"<crunched:chkx>",0);
  2974.     xxscreen(SCR_PT,'%',(long)pktnum,"(crunched)");
  2975.     return('Q');
  2976.     }
  2977.     debug(F101,"rpack block check OK","",rsn);
  2978.  
  2979. /* Now we can believe the sequence number, and other fields. */
  2980. /* Here we violate strict principles of layering, etc, and look at the  */
  2981. /* packet sequence number.  If there's already a packet with the same   */
  2982. /* number in the window, we remove this one so that the window will not */
  2983. /* fill up. */
  2984.  
  2985.     if ((x = rseqtbl[rsn]) != -1) {    /* Already a packet with this number */
  2986.     retrans++;            /* Count it for statistics */
  2987.     debug(F101,"rpack got dup","",rsn);
  2988.     logpkt('r',rsn,(CHAR *)"<duplicate>",0);
  2989.     freerbuf(x);            /* Free old buffer, keep new packet. */
  2990.     r_pkt[k].pk_rtr++;        /* Count this as a retransmission. */
  2991.     }
  2992.  
  2993. /* New packet, not seen before, enter it into the receive window. */
  2994.  
  2995. #ifdef CK_TIMERS
  2996.     if (timint > 0)
  2997.       rrttbl[rsn] = gtimer();        /* Timestamp */
  2998. #endif /* CK_TIMERS */
  2999.  
  3000.     rseqtbl[rsn] = k;            /* Make back pointer */
  3001.     r_pkt[k].pk_seq = rsn;        /* Record in packet info structure */
  3002.     r_pkt[k].pk_typ = type;        /* Sequence, type,... */
  3003.     r_pkt[k].pk_adr = rdatap;        /* pointer to data buffer */
  3004.     if (local) {            /* Save a function call! */
  3005.     int x = 0;
  3006.     if (fdispla != XYFD_N) x = 1;
  3007.     if (fdispla == XYFD_B && (type == 'D' || sndtyp == 'D')) x = 0;
  3008.     if (x)                /* Update screen */
  3009.       xxscreen(SCR_PT,(char)type,(long)rsn,(char *)sohp);
  3010.     }
  3011.     return(type);            /* Return packet type */
  3012. }
  3013.  
  3014. /*  L O G P K T  --  Log packet number n, pointed to by s.  */
  3015.  
  3016. /* c = 's' (send) or 'r' (receive) */
  3017.  
  3018. VOID
  3019. #ifdef CK_ANSIC
  3020. logpkt(char c,int n, CHAR *s, int len)
  3021. #else
  3022. logpkt(c,n,s,len) char c; int n; CHAR *s; int len;
  3023. #endif /* CK_ANSIC */
  3024. /* logpkt */ {
  3025. #ifdef UNPREFIXZERO
  3026.     extern FILE *fp[];
  3027. #endif /* UNPREFIXZERO */
  3028.     char plog[20];
  3029.     if (pktlog) if (chkfn(ZPFILE) > 0) {
  3030.     if (n < 0)            /* Construct entry header */
  3031.       sprintf(plog,"%c-xx-%02d-",c,(gtimer()%60));
  3032.     else
  3033.       sprintf(plog,"%c-%02d-%02d-",c,n,(gtimer()%60));
  3034.     if (zsoutx(ZPFILE,plog,(int)strlen(plog)) < 0) {
  3035.         pktlog = 0;
  3036.     } else {
  3037.         if (len == 0)
  3038.           len = strlen((char *)s);
  3039.         if (zsoutx(ZPFILE,(char *)s,len) < 0) {
  3040.         pktlog = 0;
  3041.         } else if (zsoutx(ZPFILE,
  3042. #ifdef UNIX
  3043.                   "\n", 1
  3044. #else
  3045. #ifdef datageneral
  3046.                   "\n", 1
  3047. #else
  3048. #ifdef OSK
  3049.                   "\r", 1
  3050. #else
  3051. #ifdef MAC
  3052.                   "\r", 1
  3053. #else
  3054.                   "\015\012", 2
  3055. #endif /* MAC */
  3056. #endif /* OSK */
  3057. #endif /* datageneral */
  3058. #endif /* UNIX */
  3059.                   ) < 0) {
  3060.         pktlog = 0;
  3061.         }
  3062.     }
  3063.     }
  3064. }
  3065.  
  3066. /*  T S T A T S  --  Record statistics in transaction log  */
  3067.  
  3068. VOID
  3069. tstats() {
  3070.     char *tp;
  3071. #ifdef GFTIMER
  3072.     CKFLOAT xx;                /* Elapsed time divisor */
  3073. #endif /* GFTIMER */
  3074.  
  3075.     debug(F101,"tstats xfsecs","",xfsecs);
  3076.     debug(F101,"tstats filcnt","",filcnt);
  3077.     if (filcnt == 1) {            /* Get timing for statistics */
  3078.     tsecs = xfsecs;            /* Single file, we already have it */
  3079. #ifdef GFTIMER
  3080.     debug(F101,"tstats fpxfsecs","",(int)fpxfsecs);
  3081.     fptsecs = fpxfsecs;
  3082. #endif /* GFTIMER */
  3083.     } else {                /* Multiple files */
  3084.     tsecs = gtimer();        /* Get current time */
  3085. #ifdef GFTIMER
  3086.     fptsecs = gftimer();
  3087. #endif /* GFTIMER */
  3088.     }
  3089. #ifdef GFTIMER
  3090.     if (fptsecs <= GFMINTIME)        /* Calculate CPS */
  3091.       fptsecs = (CKFLOAT) GFMINTIME;
  3092.     debug(F101,"tstats fptsecs","",(int)fptsecs);
  3093.     xx = (CKFLOAT) tfc / fptsecs;
  3094.     if (sizeof(long) <= 4) {        /* doesn't account for 16-bit longs */
  3095.     if (xx  > 2147483647.0)
  3096.       tfcps = 2147483647L;            /* 31 bits */
  3097.     else
  3098.       tfcps = (long) xx;
  3099.     } else
  3100.       tfcps = (long) xx;
  3101. #else
  3102.     if (tsecs < 2L)
  3103.       tsecs = 1L;
  3104.     debug(F101,"tstats tsecs","",tsecs);
  3105.     tfcps = tfc / tsecs;
  3106. #endif /* GFTIMER */
  3107.  
  3108.     ztime(&tp);                /* Get time stamp */
  3109.     tlog(F100,"","",0L);        /* Leave a blank line */
  3110.     tlog(F110,"Transaction complete",tp,0L);  /* Record it */
  3111.  
  3112.     if (filcnt < 1) return;        /* If no files, done. */
  3113.  
  3114. /* If multiple files, record character totals for all files */
  3115.  
  3116.     if (filcnt > 1) {
  3117.     tlog(F101," files transferred       ","",filcnt - filrej);
  3118.     tlog(F101," total file characters   ","",tfc);
  3119.     tlog(F101," communication line in   ","",tlci);
  3120.     tlog(F101," communication line out  ","",tlco);
  3121.     }
  3122.  
  3123. /* Record timing info for one or more files */
  3124.  
  3125. #ifdef GFTIMER
  3126.     if (filcnt - filrej == 1) {
  3127.     tlog(F101," elapsed time (seconds)  ","",(long) fpxfsecs);
  3128.     tlog(F101," effective data rate     ","",filcps);
  3129.     } else {
  3130.     tlog(F101," elapsed time (seconds)  ","",(long) fptsecs);
  3131.     tlog(F101," effective data rate     ","",(long) xx);
  3132.     }
  3133. #else
  3134.     tlog(F101," elapsed time (seconds)  ","",(long) tsecs);
  3135.     if (tsecs > 0) {
  3136.     long lx;
  3137.     lx = (tfc * 10L) / (long) tsecs;
  3138.     tlog(F101," effective data rate     ","",lx/10L);
  3139.     }
  3140. #endif /* GFTIMER */
  3141.     tlog(F100,"","",0L);        /* Leave a blank line */
  3142. }
  3143.  
  3144. /*  F S T A T S  --  Record file statistics in transaction log  */
  3145.  
  3146. VOID
  3147. fcps() {
  3148. #ifdef GFTIMER
  3149.     double xx;
  3150.     fpxfsecs = gftimer() - fpfsecs;
  3151.     if (fpxfsecs <= GFMINTIME)
  3152.       fpxfsecs = (CKFLOAT) GFMINTIME;
  3153.     xx = (CKFLOAT) ffc / fpxfsecs;
  3154.     if (sizeof(long) <= 4) {
  3155.     if (xx  > 2147483647.0)
  3156.       tfcps = 2147483647L;        /* 31 bits */
  3157.     else
  3158.       filcps = (long) xx;
  3159.     } else
  3160.       filcps = (long) xx;
  3161.     if (sizeof(int) >= 4)
  3162.       xfsecs = (int) fpxfsecs;
  3163.     else if (fpxfsecs < 32768.0)
  3164.       xfsecs = (int) fpxfsecs;
  3165.     else
  3166.       xfsecs = 32767;
  3167. #else /* GFTIMER */
  3168.     xfsecs = gtimer() - fsecs;
  3169.     if (xfsecs < 1L) xfsecs = 1L;
  3170.     filcps = ffc / xfsecs;
  3171. #endif /* GFTIMER */
  3172. }
  3173.  
  3174. VOID
  3175. fstats() {
  3176.     extern long cps;
  3177.     tfc += ffc;
  3178. #ifdef DEBUG
  3179.     if (deblog) {
  3180.     debug(F101,"fstats tfc","",tfc);
  3181.     debug(F101,"fstats what","",what);
  3182.     debug(F110,"fstats epktmsg",epktmsg,0);
  3183.     }
  3184. #endif /* DEBUG */
  3185. #ifdef TLOG
  3186.     if (!discard && !cxseen && !czseen && what != W_NOTHING && !*epktmsg)
  3187.       tlog(F101," complete, size","",ffc);
  3188. #endif /* TLOG */
  3189. }
  3190.  
  3191. #endif /* NOXFER */
  3192.