1/* protg.c
2   The 'g' protocol.
3
4   Copyright (C) 1991, 1992, 1993, 1994, 1995, 2002 Ian Lance Taylor
5
6   This file is part of the Taylor UUCP package.
7
8   This program is free software; you can redistribute it and/or
9   modify it under the terms of the GNU General Public License as
10   published by the Free Software Foundation; either version 2 of the
11   License, or (at your option) any later version.
12
13   This program is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16   General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with this program; if not, write to the Free Software
20   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307, USA.
21
22   The author of the program may be contacted at ian@airs.com.
23   */
24
25#include "uucp.h"
26
27#if USE_RCS_ID
28const char protg_rcsid[] = "$Id: protg.c,v 1.71 2002/03/05 19:10:41 ian Rel $";
29#endif
30
31#include <ctype.h>
32#include <errno.h>
33
34#include "uudefs.h"
35#include "uuconf.h"
36#include "conn.h"
37#include "trans.h"
38#include "system.h"
39#include "prot.h"
40
41/* Each 'g' protocol packet begins with six bytes.  They are:
42
43   <DLE><k><c0><c1><C><x>
44
45   <DLE> is the ASCII DLE character (^P or '\020').
46   if 1 <= <k> <= 8, the packet is followed by 2 ** (k + 4) bytes of data;
47   if <k> == 9, these six bytes are a complete control packet;
48   other value of <k> are illegal.
49   <c0> is the low byte of a checksum.
50   <c1> is the high byte of a checksum.
51   <C> is a control byte (see below).
52   <x> is <k> ^ <c0> ^ <c1> ^ <C>.
53
54   The control byte <C> is divided into three bitfields:
55
56   t t x x x y y y
57
58   The two bit field tt is the packet type.
59   The three bit field xxx is the control type for a control packet, or
60   the sequence number for a data packet.
61   The three bit field yyy is a value for a control packet, or the
62   sequence number of the last packet received for a data packet.
63
64   For all successfully recieved packets, the control byte is stored
65   into iGpacket_control.  */
66
67/* Names for the bytes in the frame header.  */
68#define IFRAME_DLE (0)
69#define IFRAME_K (1)
70#define IFRAME_CHECKLOW (2)
71#define IFRAME_CHECKHIGH (3)
72#define IFRAME_CONTROL (4)
73#define IFRAME_XOR (5)
74
75/* Length of the frame header.  */
76#define CFRAMELEN (6)
77
78/* Macros to break apart the control bytes.  */
79#define CONTROL_TT(b) ((int)(((b) >> 6) & 03))
80#define CONTROL_XXX(b) ((int)(((b) >> 3) & 07))
81#define CONTROL_YYY(b) ((int)((b) & 07))
82
83/* DLE value.  */
84#define DLE ('\020')
85
86/* Get the length of a packet given a pointer to the header.  */
87#define CPACKLEN(z) ((size_t) (1 << ((z)[IFRAME_K] + 4)))
88
89/* <k> field value for a control message.  */
90#define KCONTROL (9)
91
92/* Get the next sequence number given a sequence number.  */
93#define INEXTSEQ(i) ((i + 1) & 07)
94
95/* Compute i1 - i2 modulo 8.  */
96#define CSEQDIFF(i1, i2) (((i1) + 8 - (i2)) & 07)
97
98/* Packet types.  These are from the tt field.
99   CONTROL -- control packet
100   ALTCHAN -- alternate channel; not used by UUCP
101   DATA -- full data segment
102   SHORTDATA -- less than full data segment (all the bytes specified by
103   the packet length <k> are always transferred).  Let <u> be the number
104   of bytes in the data segment not to be used.  If <u> <= 0x7f, the first
105   byte of the data segment is <u> and the data follows.  If <u> > 0x7f,
106   the first byte of the data segment is 0x80 | (<u> & 0x7f), the second
107   byte of the data segment is <u> >> 7, and the data follows.  The
108   maximum possible data segment size is 2**12, so this handles all
109   possible cases.  */
110#define CONTROL (0)
111#define ALTCHAN (1)
112#define DATA (2)
113#define SHORTDATA (3)
114
115/* Control types.  These are from the xxx field if the type (tt field)
116   is CONTROL.
117
118   CLOSE -- close the connection
119   RJ -- reject; packet yyy last to be received correctly
120   SRJ -- selective reject; reject only packet yyy (not used by UUCP)
121   RR -- receiver ready; packet yyy received correctly
122   INITC -- third step of initialization; yyy holds window size
123   INITB -- second step of initialization; yyy holds maximum <k> value - 1
124   INITA -- first step of initialization; yyy holds window size.
125
126   The yyy value for RR is the same as the yyy value for an ordinary
127   data packet.  */
128#define CLOSE (1)
129#define RJ (2)
130#define SRJ (3)
131#define RR (4)
132#define INITC (5)
133#define INITB (6)
134#define INITA (7)
135
136/* Maximum amount of data in a single packet.  This is set by the <k>
137   field in the header; the amount of data in a packet is
138   2 ** (<k> + 4).  <k> ranges from 1 to 8.  */
139
140#define CMAXDATAINDEX (8)
141
142#define CMAXDATA (1 << (CMAXDATAINDEX + 4))
143
144/* Maximum window size.  */
145#define CMAXWINDOW (7)
146
147/* Defaults for the protocol parameters.  These may all be changed by
148   using the ``protocol-parameter g'' command, so there is no
149   particular reason to change the values given here.  */
150
151/* The desired window size.  This is what we tell the other system to
152   use.  It must be between 1 and 7, and there's no reason to use less
153   than 7.  Protocol parameter ``window''.  */
154#define IWINDOW (7)
155
156/* The desired packet size.  Many implementations only support 64 byte
157   packets.  Protocol parameter ``packet-size''.  */
158#define IPACKSIZE (64)
159
160/* The number of times to retry the exchange of INIT packets when
161   starting the protocol.  Protocol parameter ``startup-retries''.  */
162#define CSTARTUP_RETRIES (8)
163
164/* The timeout to use when waiting for an INIT packet when starting up
165   the protocol.  Protocol parameter ``init-timeout''.  */
166#define CEXCHANGE_INIT_TIMEOUT (10)
167
168/* The number of times to retry sending and waiting for a single INIT
169   packet when starting the protocol.  This controls a single INIT
170   packet, while CSTARTUP_RETRIES controls how many times to try the
171   entire INIT sequence.  Protocol parameter ``init-retries''.  */
172#define CEXCHANGE_INIT_RETRIES (4)
173
174/* The timeout to use when waiting for a packet.  Protocol parameter
175   ``timeout''.  */
176#define CTIMEOUT (10)
177
178/* The number of times to retry waiting for a packet.  Each time the
179   timeout fails we send a copy of our last data packet or a reject
180   message for the packet we expect from the other side, depending on
181   whether we are waiting for an acknowledgement or a data packet.
182   This is the number of times we try doing that and then waiting
183   again.  Protocol parameter ``retries''.   */
184#define CRETRIES (6)
185
186/* If we see more than this much unrecognized data, we drop the
187   connection.  This must be larger than a single packet size, which
188   means it must be larger than 4096 (the largest possible packet
189   size).  Protocol parameter ``garbage''.  */
190#define CGARBAGE (10000)
191
192/* If we see more than this many protocol errors, we drop the
193   connection.  Protocol parameter ``errors''.  */
194#define CERRORS (100)
195
196/* Default decay rate.  Each time we send or receive this many packets
197   succesfully, we decrement the error level by one (protocol
198   parameter ``error-decay'').  */
199#define CERROR_DECAY (10)
200
201/* If this value is non-zero, it will be used as the remote window
202   size regardless of what the other side requested.  This can be
203   useful for dealing with some particularly flawed packages.  This
204   default value should always be 0, and protocol parameter
205   ``remote-window'' should be used for the affected systems.  */
206#define IREMOTE_WINDOW (0)
207
208/* If this value is non-zero, it will be used as the packet size to
209   send to the remote system regardless of what it requested.  It's
210   difficult to imagine any circumstances where you would want to set
211   this.  Protocol parameter ``remote-packet-size''.  */
212#define IREMOTE_PACKSIZE (0)
213
214/* Local variables.  */
215
216/* Next sequence number to send.  */
217static int iGsendseq;
218
219/* Last sequence number that has been acked.  */
220static int iGremote_ack;
221
222/* Last sequence number to be retransmitted.  */
223static int iGretransmit_seq;
224
225/* Last sequence number we have received.  */
226static int iGrecseq;
227
228/* Last sequence number we have acked.  */
229static int iGlocal_ack;
230
231/* Window size to request (protocol parameter ``window'').  */
232static int iGrequest_winsize = IWINDOW;
233
234/* Packet size to request (protocol parameter ``packet-size'').  */
235static int iGrequest_packsize = IPACKSIZE;
236
237/* Remote window size (set during handshake).  */
238static int iGremote_winsize;
239
240/* Forced remote window size (protocol parameter ``remote-window'').  */
241static int iGforced_remote_winsize = IREMOTE_WINDOW;
242
243/* Remote segment size (set during handshake).  This is one less than
244   the value in a packet header.  */
245static int iGremote_segsize;
246
247/* Remote packet size (set based on iGremote_segsize).  */
248static size_t iGremote_packsize;
249
250/* Forced remote packet size (protocol parameter
251   ``remote-packet-size'').  */
252static int iGforced_remote_packsize = IREMOTE_PACKSIZE;
253
254/* Recieved control byte.  */
255static int iGpacket_control;
256
257/* Number of times to retry the initial handshake.  Protocol parameter
258   ``startup-retries''.  */
259static int cGstartup_retries = CSTARTUP_RETRIES;
260
261/* Number of times to retry sending an initial control packet.
262   Protocol parameter ``init-retries''.  */
263static int cGexchange_init_retries = CEXCHANGE_INIT_RETRIES;
264
265/* Timeout (seconds) for receiving an initial control packet.
266   Protocol parameter ``init-timeout''.  */
267static int cGexchange_init_timeout = CEXCHANGE_INIT_TIMEOUT;
268
269/* Timeout (seconds) for receiving a data packet.  Protocol parameter
270   ``timeout''.  */
271static int cGtimeout = CTIMEOUT;
272
273/* Maximum number of timeouts when receiving a data packet or
274   acknowledgement.  Protocol parameter ``retries''.  */
275static int cGretries = CRETRIES;
276
277/* Amount of garbage data we are prepared to see before giving up.
278   Protocol parameter ``garbage''.  */
279static int cGgarbage_data = CGARBAGE;
280
281/* Maximum number of errors we are prepared to see before giving up.
282   Protocol parameter ``errors''.  */
283static int cGmax_errors = CERRORS;
284
285/* Each time we receive this many packets succesfully, we decrement
286   the error level by one (protocol parameter ``error-decay'').  */
287static int cGerror_decay = CERROR_DECAY;
288
289/* Whether to use shorter packets when possible.  Protocol parameter
290   ``short-packets''.  */
291static boolean fGshort_packets = TRUE;
292
293/* Protocol parameter commands.  */
294struct uuconf_cmdtab asGproto_params[] =
295{
296  { "window", UUCONF_CMDTABTYPE_INT, (pointer) &iGrequest_winsize, NULL },
297  { "packet-size", UUCONF_CMDTABTYPE_INT, (pointer) &iGrequest_packsize,
298      NULL },
299  { "startup-retries", UUCONF_CMDTABTYPE_INT, (pointer) &cGstartup_retries,
300      NULL },
301  { "init-timeout", UUCONF_CMDTABTYPE_INT, (pointer) &cGexchange_init_timeout,
302      NULL },
303  { "init-retries", UUCONF_CMDTABTYPE_INT, (pointer) &cGexchange_init_retries,
304      NULL },
305  { "timeout", UUCONF_CMDTABTYPE_INT, (pointer) &cGtimeout, NULL },
306  { "retries", UUCONF_CMDTABTYPE_INT, (pointer) &cGretries, NULL },
307  { "garbage", UUCONF_CMDTABTYPE_INT, (pointer) &cGgarbage_data, NULL },
308  { "errors", UUCONF_CMDTABTYPE_INT, (pointer) &cGmax_errors, NULL },
309  { "error-decay", UUCONF_CMDTABTYPE_INT, (pointer) &cGerror_decay, NULL },
310  { "remote-window", UUCONF_CMDTABTYPE_INT,
311      (pointer) &iGforced_remote_winsize, NULL },
312  { "remote-packet-size", UUCONF_CMDTABTYPE_INT,
313      (pointer) &iGforced_remote_packsize, NULL },
314  { "short-packets", UUCONF_CMDTABTYPE_BOOLEAN, (pointer) &fGshort_packets,
315      NULL },
316  { NULL, 0, NULL, NULL }
317};
318
319/* Statistics.  */
320
321/* Number of packets we have sent.  */
322static long cGsent_packets;
323
324/* Number of packets we have resent (these are not included in
325   cGsent_packets).  */
326static long cGresent_packets;
327
328/* Number of packets we have delayed sending (these should not be
329   counted in cGresent_packets).  */
330static long cGdelayed_packets;
331
332/* Number of packets we have received.  */
333static long cGrec_packets;
334
335/* Number of packets rejected because the header was bad.  */
336static long cGbad_hdr;
337
338/* Number of packets rejected because the checksum was bad.  */
339static long cGbad_checksum;
340
341/* Number of packets received out of order.  */
342static long cGbad_order;
343
344/* Number of packets rejected by receiver (number of RJ packets
345   received).  */
346static long cGremote_rejects;
347
348/* Number of duplicate RR packets treated as RJ packets.  Some UUCP
349   packages appear to never send RJ packets, but only RR packets.  If
350   no RJ has been seen, fgprocess_data treats a duplicate RR as an RJ
351   and increments this variable.  */
352static long cGremote_duprrs;
353
354/* The error level.  This is the total number of errors as adjusted by
355   cGerror_decay.  */
356static long cGerror_level;
357
358/* Each time we send an RJ, we can expect several out of order of
359   packets, because the other side will probably have sent a full
360   window by the time it sees the RJ.  This variable keeps track of
361   the number of out of order packets we expect to see.  We don't
362   count expected out of order packets against the error level.  This
363   is reset to 0 when an in order packet is received.  */
364static int cGexpect_bad_order;
365
366#if DEBUG > 1
367/* Control packet names used for debugging.  */
368static const char * const azGcontrol[] =
369{"?0?", "CLOSE", "RJ", "SRJ", "RR", "INITC", "INITB", "INITA"};
370#endif
371
372/* Local functions.  */
373static boolean fgexchange_init P((struct sdaemon *qdaemon, int ictl,
374				  int ival, int *piset));
375static boolean fgsend_control P((struct sdaemon *qdaemon, int ictl,
376				 int ival));
377static char *zgadjust_ack P((int iseq));
378static boolean fgwait_for_packet P((struct sdaemon *qdaemon,
379				    boolean freturncontrol, int ctimeout,
380				    int cretries));
381static boolean fgsend_acks P((struct sdaemon *qdaemon));
382static boolean fggot_ack P((struct sdaemon *qdaemon, int iack));
383static boolean fgprocess_data P((struct sdaemon *qdaemon, boolean fdoacks,
384				 boolean freturncontrol,
385				 boolean *pfexit, size_t *pcneed,
386				 boolean *pffound));
387static boolean fginit_sendbuffers P((boolean fallocate));
388static boolean fgcheck_errors P((struct sdaemon *qdaemon));
389static int igchecksum P((const char *zdata, size_t clen));
390static int igchecksum2 P((const char *zfirst, size_t cfirst,
391			  const char *zsecond, size_t csecond));
392
393/* Start the protocol.  This requires a three way handshake.  Both sides
394   must send and receive an INITA packet, an INITB packet, and an INITC
395   packet.  The INITA and INITC packets contain the window size, and the
396   INITB packet contains the packet size.  */
397
398boolean
399fgstart (qdaemon, pzlog)
400     struct sdaemon *qdaemon;
401     char **pzlog;
402{
403  int iseg;
404  int i;
405  boolean fgota, fgotb;
406
407  *pzlog = NULL;
408
409  /* The 'g' protocol requires a full eight bit interface.  */
410  if (! fconn_set (qdaemon->qconn, PARITYSETTING_NONE,
411		   STRIPSETTING_EIGHTBITS, XONXOFF_OFF))
412    return FALSE;
413
414  iGsendseq = 1;
415  iGremote_ack = 0;
416  iGretransmit_seq = -1;
417  iGrecseq = 0;
418  iGlocal_ack = 0;
419  cGsent_packets = 0;
420  cGresent_packets = 0;
421  cGdelayed_packets = 0;
422  cGrec_packets = 0;
423  cGbad_hdr = 0;
424  cGbad_checksum = 0;
425  cGbad_order = 0;
426  cGremote_rejects = 0;
427  cGremote_duprrs = 0;
428  cGerror_level = 0;
429  cGexpect_bad_order = 0;
430
431  /* We must determine the segment size based on the packet size
432     which may have been modified by a protocol parameter command.
433     A segment size of 2^n is passed as n - 5.  */
434  i = iGrequest_packsize;
435  iseg = -1;
436  while (i > 0)
437    {
438      ++iseg;
439      i >>= 1;
440    }
441  iseg -= 5;
442  if (iseg < 0 || iseg > 7)
443    {
444      ulog (LOG_ERROR, "Illegal packet size %d for '%c' protocol",
445	    iGrequest_packsize, qdaemon->qproto->bname);
446      iseg = 1;
447    }
448
449  if (iGrequest_winsize <= 0 || iGrequest_winsize > 7)
450    {
451      ulog (LOG_ERROR, "Illegal window size %d for '%c' protocol",
452	    iGrequest_winsize, qdaemon->qproto->bname);
453      iGrequest_winsize = IWINDOW;
454    }
455
456  fgota = FALSE;
457  fgotb = FALSE;
458  for (i = 0; i < cGstartup_retries; i++)
459    {
460      if (fgota)
461	{
462	  if (! fgsend_control (qdaemon, INITA, iGrequest_winsize))
463	    return FALSE;
464	}
465      else
466	{
467	  if (! fgexchange_init (qdaemon, INITA, iGrequest_winsize,
468				 &iGremote_winsize))
469	    continue;
470	}
471      fgota = TRUE;
472
473      if (fgotb)
474	{
475	  if (! fgsend_control (qdaemon, INITB, iseg))
476	    return FALSE;
477	}
478      else
479	{
480	  if (! fgexchange_init (qdaemon, INITB, iseg, &iGremote_segsize))
481	    continue;
482	}
483      fgotb = TRUE;
484
485      if (! fgexchange_init (qdaemon, INITC, iGrequest_winsize,
486			     &iGremote_winsize))
487	continue;
488
489      /* We have succesfully connected.  Determine the remote packet
490	 size.  */
491      iGremote_packsize = 1 << (iGremote_segsize + 5);
492
493      /* If the user requested us to force specific remote window and
494	 packet sizes, do so now.  */
495      if (iGforced_remote_winsize > 0
496	  && iGforced_remote_winsize <= CMAXWINDOW)
497	iGremote_winsize = iGforced_remote_winsize;
498
499      if (iGforced_remote_packsize >= 32
500	  && iGforced_remote_packsize <= 4096)
501	{
502	  /* Force the value to a power of two.  */
503	  i = iGforced_remote_packsize;
504	  iseg = -1;
505	  while (i > 0)
506	    {
507	      ++iseg;
508	      i >>= 1;
509	    }
510	  iGremote_packsize = 1 << iseg;
511	  iGremote_segsize = iseg - 5;
512	}
513
514      /* Set up packet buffers to use.  We don't do this until we know
515	 the maximum packet size we are going to send.  */
516      if (! fginit_sendbuffers (TRUE))
517	return FALSE;
518
519      *pzlog =
520	zbufalc (sizeof "protocol '' sending packet/window / receiving /"
521		 + 64);
522      sprintf (*pzlog,
523	       "protocol '%c' sending packet/window %d/%d receiving %d/%d",
524	       qdaemon->qproto->bname, (int) iGremote_packsize,
525	       (int) iGremote_winsize, (int) iGrequest_packsize,
526	       (int) iGrequest_winsize);
527
528      return TRUE;
529    }
530
531  DEBUG_MESSAGE0 (DEBUG_PROTO | DEBUG_ABNORMAL,
532		  "fgstart: Protocol startup failed");
533
534  return FALSE;
535}
536
537/* The 'G' protocol is identical to the 'g' protocol, except that
538   short packets are never supported.  */
539
540boolean
541fbiggstart (qdaemon, pzlog)
542     struct sdaemon *qdaemon;
543     char **pzlog;
544{
545  fGshort_packets = FALSE;
546  return fgstart (qdaemon, pzlog);
547}
548
549/* The 'v' protocol is identical to the 'g' protocol, except that the
550   packet size defaults to 512 bytes.  Rather than really get it
551   right, we automatically switch from the usual default of 64 to 512.
552   This won't work correctly if somebody does protocol-parameter v
553   packet-size 64.  */
554
555boolean
556fvstart (qdaemon, pzlog)
557     struct sdaemon *qdaemon;
558     char **pzlog;
559{
560  if (iGrequest_packsize == IPACKSIZE)
561    iGrequest_packsize = 1024;
562  return fgstart (qdaemon, pzlog);
563}
564
565/* Exchange initialization messages with the other system.
566
567   A problem:
568
569   We send INITA; it gets received
570   We receive INITA
571   We send INITB; it gets garbled
572   We receive INITB
573
574   We have seen and sent INITB, so we start to send INITC.  The other
575   side as sent INITB but not seen it, so it times out and resends
576   INITB.  We will continue sending INITC and the other side will
577   continue sending INITB until both sides give up and start again
578   with INITA.
579
580   It might seem as though if we are sending INITC and receive INITB,
581   we should resend our INITB, but this could cause infinite echoing
582   of INITB on a long-latency line.  Rather than risk that, I have
583   implemented a fast drop-back procedure.  If we are sending INITB and
584   receive INITC, the other side has gotten ahead of us.  We immediately
585   fail and begin again with INITA.  For the other side, if we are
586   sending INITC and see INITA, we also immediately fail back to INITA.
587
588   Unfortunately, this doesn't work for the other case, in which we
589   are sending INITB but the other side has not yet seen INITA.  As
590   far as I can see, if this happens we just have to wait until we
591   time out and resend INITA.  */
592
593static boolean
594fgexchange_init (qdaemon, ictl, ival, piset)
595     struct sdaemon *qdaemon;
596     int ictl;
597     int ival;
598     int *piset;
599{
600  int i;
601
602  /* The three-way handshake should be independent of who initializes
603     it, but it seems that some versions of uucico assume that the
604     caller sends first and the callee responds.  This only matters if
605     we are the callee and the first packet is garbled.  If we send a
606     packet, the other side will assume that we must have seen the
607     packet they sent and will never time out and send it again.
608     Therefore, if we are the callee we don't send a packet the first
609     time through the loop.  This can still fail, but should usually
610     work, and, after all, if the initialization packets are received
611     correctly there will be no problem no matter what we do.  */
612  for (i = 0; i < cGexchange_init_retries; i++)
613    {
614      long itime;
615      int ctimeout;
616
617      if (qdaemon->fcaller || i > 0)
618	{
619	  if (! fgsend_control (qdaemon, ictl, ival))
620	    return FALSE;
621	}
622
623      itime = ixsysdep_time ((long *) NULL);
624      ctimeout = cGexchange_init_timeout;
625
626      do
627	{
628	  long inewtime;
629
630	  /* We pass 0 as the retry count to fgwait_for_packet because
631	     we want to handle retries here and because if it retried
632	     it would send a packet, which would be bad.  */
633	  if (! fgwait_for_packet (qdaemon, TRUE, ctimeout, 0))
634	    break;
635
636	  if (CONTROL_TT (iGpacket_control) == CONTROL)
637	    {
638	      if (CONTROL_XXX (iGpacket_control) == ictl)
639		{
640		  *piset = CONTROL_YYY (iGpacket_control);
641
642		  /* If we didn't already send our initialization
643		     packet, send it now.  */
644		  if (! qdaemon->fcaller && i == 0)
645		    {
646		      if (! fgsend_control (qdaemon, ictl, ival))
647			return FALSE;
648		    }
649
650		  return TRUE;
651		}
652
653	      /* If the other side is farther along than we are,
654		 we have lost a packet.  Fail immediately back to
655		 INITA (but don't fail if we are already doing INITA,
656		 since that would count against cStart_retries more
657		 than it should).  */
658	      if (CONTROL_XXX (iGpacket_control) < ictl && ictl != INITA)
659		return FALSE;
660
661	      /* If we are sending INITC and we receive an INITA, the other
662		 side has failed back (we know this because we have
663		 seen an INITB from them).  Fail back ourselves to
664		 start the whole handshake over again.  */
665	      if (CONTROL_XXX (iGpacket_control) == INITA && ictl == INITC)
666		return FALSE;
667
668	      /* As a special hack, if we are sending INITC and we
669		 receive INITB, we update the segment size from the
670		 packet.  This permits a second INITB to override the
671		 first one.  It would be nice to do this in a cleaner
672		 way.  */
673	      if (CONTROL_XXX (iGpacket_control) == INITB && ictl == INITC)
674		iGremote_segsize = CONTROL_YYY (iGpacket_control);
675	    }
676
677	  inewtime = ixsysdep_time ((long *) NULL);
678	  ctimeout -= inewtime - itime;
679	}
680      while (ctimeout > 0);
681    }
682
683  return FALSE;
684}
685
686/* Shut down the protocol.  */
687
688boolean
689fgshutdown (qdaemon)
690     struct sdaemon *qdaemon;
691{
692  (void) fgsend_control (qdaemon, CLOSE, 0);
693  (void) fgsend_control (qdaemon, CLOSE, 0);
694  (void) fginit_sendbuffers (FALSE);
695
696  /* The count of sent packets may not be accurate, because some of
697     them may have not been sent yet if the connection failed in the
698     middle (the ones that counted for cGdelayed_packets).  I don't
699     think it's worth being precise.  */
700  ulog (LOG_NORMAL,
701	"Protocol '%c' packets: sent %ld, resent %ld, received %ld",
702	qdaemon->qproto->bname, cGsent_packets,
703	cGresent_packets - cGdelayed_packets, cGrec_packets);
704  if (cGbad_hdr != 0
705      || cGbad_checksum != 0
706      || cGbad_order != 0
707      || cGremote_rejects != 0
708      || cGremote_duprrs != 0)
709    ulog (LOG_NORMAL,
710	  "Errors: header %ld, checksum %ld, order %ld, remote rejects %ld",
711	  cGbad_hdr, cGbad_checksum, cGbad_order,
712	  cGremote_duprrs + cGremote_rejects);
713
714  /* Reset all the parameters to their default values, so that the
715     protocol parameters used for this connection do not affect the
716     next one.  */
717  iGrequest_winsize = IWINDOW;
718  iGrequest_packsize = IPACKSIZE;
719  cGstartup_retries = CSTARTUP_RETRIES;
720  cGexchange_init_timeout = CEXCHANGE_INIT_TIMEOUT;
721  cGexchange_init_retries = CEXCHANGE_INIT_RETRIES;
722  cGtimeout = CTIMEOUT;
723  cGretries = CRETRIES;
724  cGgarbage_data = CGARBAGE;
725  cGmax_errors = CERRORS;
726  cGerror_decay = CERROR_DECAY;
727  iGforced_remote_winsize = IREMOTE_WINDOW;
728  iGforced_remote_packsize = IREMOTE_PACKSIZE;
729  fGshort_packets = TRUE;
730
731  return TRUE;
732}
733
734/* Send a command string.  We send packets containing the string until
735   the entire string has been sent.  Each packet is full.  */
736
737/*ARGSUSED*/
738boolean
739fgsendcmd (qdaemon, z, ilocal, iremote)
740     struct sdaemon *qdaemon;
741     const char *z;
742     int ilocal ATTRIBUTE_UNUSED;
743     int iremote ATTRIBUTE_UNUSED;
744{
745  size_t clen;
746  boolean fagain;
747
748  DEBUG_MESSAGE1 (DEBUG_UUCP_PROTO, "fgsendcmd: Sending command \"%s\"", z);
749
750  clen = strlen (z);
751
752  do
753    {
754      char *zpacket;
755      size_t cdummy;
756
757      zpacket = zggetspace (qdaemon, &cdummy);
758
759      if (clen < iGremote_packsize)
760	{
761	  size_t csize;
762
763	  /* If the remote packet size is larger than 64 (the default,
764	     which may indicate an older UUCP package), try to fit
765	     this command into a smaller packet.  We still always send
766	     a complete packet, though.  */
767	  if (iGremote_packsize <= 64 || ! fGshort_packets)
768	    csize = iGremote_packsize;
769	  else
770	    {
771	      csize = 32;
772	      while (csize <= clen)
773		csize <<= 1;
774	    }
775
776	  memcpy (zpacket, z, clen);
777	  if (csize > clen)
778	    bzero (zpacket + clen, csize - clen);
779	  fagain = FALSE;
780
781	  if (! fgsenddata (qdaemon, zpacket, csize, 0, 0, (long) 0))
782	    return FALSE;
783	}
784      else
785	{
786	  memcpy (zpacket, z, iGremote_packsize);
787	  z += iGremote_packsize;
788	  clen -= iGremote_packsize;
789	  fagain = TRUE;
790
791	  if (! fgsenddata (qdaemon, zpacket, iGremote_packsize,
792			    0, 0, (long) 0))
793	    return FALSE;
794	}
795    }
796  while (fagain);
797
798  return TRUE;
799}
800
801/* We keep an array of buffers to retransmit as necessary.  Rather
802   than waste static space on large buffer sizes, we allocate the
803   buffers once we know how large the other system expects them to be.
804   The sequence numbers used in the 'g' protocol are only three bits
805   long, so we allocate eight buffers and maintain a correspondence
806   between buffer index and sequence number.  This always wastes some
807   buffer space, but it's easy to implement.
808
809   We leave room at the front of the buffer for the frame header and
810   two additional bytes.  The two extra bytes are used for short
811   packets, which essentially use a longer header and shorter data.
812   We do this to avoid moving the data.  We zero out any unused bytes
813   before the frame, so we can locate the real header given a buffer
814   by finding the first non-zero byte (which will be one of the first
815   three bytes in the buffer).  */
816
817#define CSENDBUFFERS (CMAXWINDOW + 1)
818
819static char *azGsendbuffers[CSENDBUFFERS];
820
821static boolean
822fginit_sendbuffers (fallocate)
823     boolean fallocate;
824{
825  int i;
826
827  /* Free up any remaining old buffers.  */
828  for (i = 0; i < CSENDBUFFERS; i++)
829    {
830      xfree ((pointer) azGsendbuffers[i]);
831      if (fallocate)
832	{
833	  azGsendbuffers[i] = (char *) malloc (CFRAMELEN + 2
834					       + iGremote_packsize);
835	  if (azGsendbuffers[i] == NULL)
836	    return FALSE;
837
838	  /* This bzero might not seem necessary, since before we send
839	     out each packet we zero out any non-data bytes.  However,
840	     if we receive an SRJ at the start of the conversation, we
841	     will send out the packet before it has been set to
842	     anything, thus sending the contents of our heap.  We
843	     avoid this by using bzero.  */
844	  bzero (azGsendbuffers[i], CFRAMELEN + 2 + iGremote_packsize);
845	}
846      else
847	azGsendbuffers[i] = NULL;
848    }
849  return TRUE;
850}
851
852/* Allocate a packet to send out.  The return value of this function
853   must be filled in and passed to fgsenddata, or discarded.  This
854   will ensure that the buffers and iGsendseq stay in synch.  Set
855   *pclen to the amount of data to place in the buffer.  */
856
857/*ARGSUSED*/
858char *
859zggetspace (qdaemon, pclen)
860     struct sdaemon *qdaemon ATTRIBUTE_UNUSED;
861     size_t *pclen;
862{
863  *pclen = iGremote_packsize;
864  return azGsendbuffers[iGsendseq] + CFRAMELEN + 2;
865}
866
867/* Send out a data packet.  This computes the checksum, sets up the
868   header, and sends the packet out.  The argument zdata should point
869   to the return value of zggetspace.  */
870
871/*ARGSIGNORED*/
872boolean
873fgsenddata (qdaemon, zdata, cdata, ilocal, iremote, ipos)
874     struct sdaemon *qdaemon;
875     char *zdata;
876     size_t cdata;
877     int ilocal ATTRIBUTE_UNUSED;
878     int iremote ATTRIBUTE_UNUSED;
879     long ipos ATTRIBUTE_UNUSED;
880{
881  char *z;
882  int itt, iseg;
883  size_t csize;
884  int iclr1, iclr2;
885  unsigned short icheck;
886
887  /* Set the initial length bytes.  See the description at the definition
888     of SHORTDATA, above.  */
889  itt = DATA;
890  csize = iGremote_packsize;
891  iseg = iGremote_segsize + 1;
892
893#if DEBUG > 0
894  if (cdata > csize)
895    ulog (LOG_FATAL, "fgsend_packet: Packet size too large");
896#endif
897
898  iclr1 = -1;
899  iclr2 = -2;
900  if (cdata < csize)
901    {
902      /* If the remote packet size is larger than 64, the default, we
903	 can assume they can handle a smaller packet as well, which
904	 will be more efficient to send.  */
905      if (iGremote_packsize > 64 && fGshort_packets)
906	{
907	  /* The packet size is 1 << (iseg + 4).  */
908	  iseg = 1;
909	  csize = 32;
910	  while (csize < cdata)
911	    {
912	      csize <<= 1;
913	      ++iseg;
914	    }
915	}
916
917      if (csize != cdata)
918	{
919	  size_t cshort;
920
921	  /* We have to add bytes which indicate how short the packet
922	     is.  We do this by pushing the header backward, which we
923	     can do because we allocated two extra bytes for this
924	     purpose.  */
925	  iclr2 = 0;
926	  itt = SHORTDATA;
927	  cshort = csize - cdata;
928	  if (cshort <= 127)
929	    {
930	      --zdata;
931	      zdata[0] = (char) cshort;
932	      zdata[-1] = '\0';
933	      if (cshort > 1)
934		bzero (zdata + cdata + 1, cshort - 1);
935	    }
936	  else
937	    {
938	      zdata -= 2;
939	      zdata[0] = (char) (0x80 | (cshort & 0x7f));
940	      zdata[1] = (char) (cshort >> 7);
941	      bzero (zdata + cdata + 2, cshort - 2);
942	      iclr1 = 0;
943	    }
944	}
945    }
946
947  z = zdata - CFRAMELEN;
948
949  /* Zero out the preceding bytes, in case the last time this buffer
950     was used those bytes were used.  We need to zero out the initial
951     bytes so that we can find the true start of the packet in
952     zgadjust_ack.  */
953  z[iclr1] = '\0';
954  z[iclr2] = '\0';
955
956  z[IFRAME_DLE] = DLE;
957  z[IFRAME_K] = (char) iseg;
958
959  icheck = (unsigned short) igchecksum (zdata, csize);
960
961  /* We're just about ready to go.  Wait until there is room in the
962     receiver's window for us to send the packet.  We do this now so
963     that we send the correct value for the last packet received.
964     Note that if iGsendseq == iGremote_ack, this means that the
965     sequence numbers are actually 8 apart, since the packet could not
966     have been acknowledged before it was sent; this can happen when
967     the window size is 7.  */
968  while (iGsendseq == iGremote_ack
969	 || CSEQDIFF (iGsendseq, iGremote_ack) > iGremote_winsize)
970    {
971      if (! fgwait_for_packet (qdaemon, TRUE, cGtimeout, cGretries))
972	return FALSE;
973    }
974
975  /* Ack all packets up to the next one, since the UUCP protocol
976     requires that all packets be acked in order.  */
977  while (CSEQDIFF (iGrecseq, iGlocal_ack) > 1)
978    {
979      iGlocal_ack = INEXTSEQ (iGlocal_ack);
980      if (! fgsend_control (qdaemon, RR, iGlocal_ack))
981	return FALSE;
982    }
983  iGlocal_ack = iGrecseq;
984
985  z[IFRAME_CONTROL] = (char) ((itt << 6) | (iGsendseq << 3) | iGrecseq);
986
987  iGsendseq = INEXTSEQ (iGsendseq);
988
989  icheck = ((unsigned short)
990	    ((0xaaaa - (icheck ^ (z[IFRAME_CONTROL] & 0xff))) & 0xffff));
991  z[IFRAME_CHECKLOW] = (char) (icheck & 0xff);
992  z[IFRAME_CHECKHIGH] = (char) (icheck >> 8);
993
994  z[IFRAME_XOR] = (char) (z[IFRAME_K] ^ z[IFRAME_CHECKLOW]
995			  ^ z[IFRAME_CHECKHIGH] ^ z[IFRAME_CONTROL]);
996
997  /* If we're waiting for acks of retransmitted packets, then don't
998     send this packet yet.  The other side may not be ready for it
999     yet.  Instead, code in fggot_ack will send the outstanding
1000     packets when an ack is received.  */
1001  ++cGsent_packets;
1002
1003  if (iGretransmit_seq != -1)
1004    {
1005      ++cGdelayed_packets;
1006      return TRUE;
1007    }
1008
1009  DEBUG_MESSAGE2 (DEBUG_PROTO,
1010		  "fgsenddata: Sending packet %d (%d bytes)",
1011		  CONTROL_XXX (z[IFRAME_CONTROL]), cdata);
1012
1013  return fsend_data (qdaemon->qconn, z, CFRAMELEN + csize, TRUE);
1014}
1015
1016/* Recompute the control byte and checksum of a packet so that it
1017   includes the correct packet acknowledgement.  This is called when a
1018   packet is retransmitted to make sure the retransmission does not
1019   confuse the other side.  It returns a pointer to the start of the
1020   packet, skipping the bytes that may be unused at the start of
1021   azGsendbuffers[iseq].  */
1022
1023static char *
1024zgadjust_ack (iseq)
1025     int iseq;
1026{
1027  register char *z;
1028  unsigned short icheck;
1029
1030  z = azGsendbuffers[iseq];
1031  if (*z == '\0')
1032    ++z;
1033  if (*z == '\0')
1034    ++z;
1035
1036  /* If the received packet number is the same, there is nothing
1037     to do.  */
1038  if (CONTROL_YYY (z[IFRAME_CONTROL]) == iGrecseq)
1039    return z;
1040
1041  /* Get the old checksum.  */
1042  icheck = (unsigned short) (((z[IFRAME_CHECKHIGH] & 0xff) << 8)
1043			     | (z[IFRAME_CHECKLOW] & 0xff));
1044  icheck = ((unsigned short)
1045	    (((0xaaaa - icheck) ^ (z[IFRAME_CONTROL] & 0xff)) & 0xffff));
1046
1047  /* Update the control byte.  */
1048  z[IFRAME_CONTROL] = (char) ((z[IFRAME_CONTROL] &~ 07) | iGrecseq);
1049
1050  /* Create the new checksum.  */
1051  icheck = ((unsigned short)
1052	    ((0xaaaa - (icheck ^ (z[IFRAME_CONTROL] & 0xff))) & 0xffff));
1053  z[IFRAME_CHECKLOW] = (char) (icheck & 0xff);
1054  z[IFRAME_CHECKHIGH] = (char) (icheck >> 8);
1055
1056  /* Update the XOR byte.  */
1057  z[IFRAME_XOR] = (char) (z[IFRAME_K] ^ z[IFRAME_CHECKLOW]
1058			  ^ z[IFRAME_CHECKHIGH] ^ z[IFRAME_CONTROL]);
1059
1060  return z;
1061}
1062
1063/* Send a control packet.  These are fairly simple to construct.  It
1064   seems reasonable to me that we should be able to send a control
1065   packet at any time, even if the receive window is closed.  In
1066   particular, we don't want to delay when sending a CLOSE control
1067   message.  If I'm wrong, it can be changed easily enough.  */
1068
1069static boolean
1070fgsend_control (qdaemon, ixxx, iyyy)
1071     struct sdaemon *qdaemon;
1072     int ixxx;
1073     int iyyy;
1074{
1075  char ab[CFRAMELEN];
1076  int ictl;
1077  unsigned short icheck;
1078
1079#if DEBUG > 1
1080  if (FDEBUGGING (DEBUG_PROTO) ||
1081      (FDEBUGGING (DEBUG_ABNORMAL) && ixxx != RR))
1082    ulog (LOG_DEBUG, "fgsend_control: Sending control %s %d",
1083	  azGcontrol[ixxx], iyyy);
1084#endif
1085
1086  ab[IFRAME_DLE] = DLE;
1087  ab[IFRAME_K] = KCONTROL;
1088
1089  ictl = (CONTROL << 6) | (ixxx << 3) | iyyy;
1090  icheck = (unsigned short) (0xaaaa - ictl);
1091  ab[IFRAME_CHECKLOW] = (char) (icheck & 0xff);
1092  ab[IFRAME_CHECKHIGH] = (char) (icheck >> 8);
1093
1094  ab[IFRAME_CONTROL] = (char) ictl;
1095
1096  ab[IFRAME_XOR] = (char) (ab[IFRAME_K] ^ ab[IFRAME_CHECKLOW]
1097			   ^ ab[IFRAME_CHECKHIGH] ^ ab[IFRAME_CONTROL]);
1098
1099  return fsend_data (qdaemon->qconn, ab, (size_t) CFRAMELEN, TRUE);
1100}
1101
1102/* Wait for data to come in.  This continues processing until a
1103   complete file or command has been received.  */
1104
1105boolean
1106fgwait (qdaemon)
1107     struct sdaemon *qdaemon;
1108{
1109  return fgwait_for_packet (qdaemon, FALSE, cGtimeout, cGretries);
1110}
1111
1112/* Get a packet.  This is called when we have nothing to send, but
1113   want to wait for a packet to come in.  If freturncontrol is TRUE,
1114   this will return after getting any control packet.  Otherwise, it
1115   will continue to receive packets until a complete file or a
1116   complete command has been received.  The timeout and the number of
1117   retries are specified as arguments.  The function returns FALSE if
1118   an error occurs or if cretries timeouts of ctimeout seconds were
1119   exceeded.  */
1120
1121static boolean
1122fgwait_for_packet (qdaemon, freturncontrol, ctimeout, cretries)
1123     struct sdaemon *qdaemon;
1124     boolean freturncontrol;
1125     int ctimeout;
1126     int cretries;
1127{
1128  int ctimeouts;
1129  int cgarbage;
1130  int cshort;
1131
1132  ctimeouts = 0;
1133  cgarbage = 0;
1134  cshort = 0;
1135
1136  while (TRUE)
1137    {
1138      boolean fexit;
1139      size_t cneed;
1140      boolean ffound;
1141      size_t crec;
1142
1143      if (! fgprocess_data (qdaemon, TRUE, freturncontrol, &fexit,
1144			    &cneed, &ffound))
1145	return FALSE;
1146
1147      if (fexit)
1148	return TRUE;
1149
1150      DEBUG_MESSAGE1 (DEBUG_PROTO,
1151		      "fgwait_for_packet: Need %lu bytes",
1152		      (unsigned long) cneed);
1153
1154      if (ffound)
1155	{
1156	  ctimeouts = 0;
1157	  cgarbage = 0;
1158	}
1159      else
1160	{
1161	  if (cgarbage > cGgarbage_data)
1162	    {
1163	      ulog (LOG_ERROR, "Too much unrecognized data");
1164	      return FALSE;
1165	    }
1166	}
1167
1168      if (! freceive_data (qdaemon->qconn, cneed, &crec, ctimeout, TRUE))
1169	return FALSE;
1170
1171      cgarbage += crec;
1172
1173      if (crec != 0)
1174	{
1175	  /* If we don't get enough data twice in a row, we may have
1176	     dropped some data and still be looking for the end of a
1177	     large packet.  Incrementing iPrecstart will force
1178	     fgprocess_data to skip that packet and look through the
1179	     rest of the data.  In some situations, this will be a
1180	     mistake.  */
1181	  if (crec >= cneed)
1182	    cshort = 0;
1183	  else
1184	    {
1185	      ++cshort;
1186	      if (cshort > 1)
1187		{
1188		  iPrecstart = (iPrecstart + 1) % CRECBUFLEN;
1189		  cshort = 0;
1190		}
1191	    }
1192	}
1193      else
1194	{
1195	  /* The read timed out.  If we have an unacknowledged packet,
1196	     send it again.  Otherwise, send an RJ with the last
1197	     packet we received correctly.  */
1198	  ++ctimeouts;
1199	  if (ctimeouts > cretries)
1200	    {
1201	      if (cretries > 0)
1202		ulog (LOG_ERROR, "Timed out waiting for packet");
1203	      return FALSE;
1204	    }
1205
1206	  if (INEXTSEQ (iGremote_ack) != iGsendseq)
1207	    {
1208	      int inext;
1209	      char *zsend;
1210
1211	      inext = INEXTSEQ (iGremote_ack);
1212
1213	      DEBUG_MESSAGE1 (DEBUG_PROTO | DEBUG_ABNORMAL,
1214			      "fgwait_for_packet: Resending packet %d",
1215			      inext);
1216
1217	      ++cGresent_packets;
1218	      zsend = zgadjust_ack (inext);
1219	      if (! fsend_data (qdaemon->qconn, zsend,
1220				CFRAMELEN + CPACKLEN (zsend), TRUE))
1221		return FALSE;
1222	      iGretransmit_seq = inext;
1223	    }
1224	  else
1225	    {
1226	      /* Send all pending acks first, to avoid confusing
1227		 the other side.  */
1228	      if (iGlocal_ack != iGrecseq)
1229		{
1230		  if (! fgsend_acks (qdaemon))
1231		    return FALSE;
1232		}
1233	      if (! fgsend_control (qdaemon, RJ, iGrecseq))
1234		return FALSE;
1235	    }
1236	}
1237    }
1238}
1239
1240/* Send acks for all packets we haven't acked yet.  */
1241
1242static boolean
1243fgsend_acks (qdaemon)
1244     struct sdaemon *qdaemon;
1245{
1246  while (iGlocal_ack != iGrecseq)
1247    {
1248      iGlocal_ack = INEXTSEQ (iGlocal_ack);
1249      if (! fgsend_control (qdaemon, RR, iGlocal_ack))
1250	return FALSE;
1251    }
1252  return TRUE;
1253}
1254
1255/* Handle an ack of a packet.  According to Hanrahan's paper, this
1256   acknowledges all previous packets.  If this is an ack for a
1257   retransmitted packet, continue by resending up to two more packets
1258   following the retransmitted one.  This should recover quickly from
1259   a line glitch, while avoiding the problem of continual
1260   retransmission.  */
1261
1262static boolean
1263fggot_ack (qdaemon, iack)
1264     struct sdaemon *qdaemon;
1265     int iack;
1266{
1267  int inext;
1268  char *zsend;
1269
1270  /* We only decrement the error level if we are not retransmitting
1271     packets.  We want to catch a sudden downgrade in line quality as
1272     fast as possible.  */
1273  if (cGerror_level > 0
1274      && iGretransmit_seq == -1
1275      && cGsent_packets % cGerror_decay == 0)
1276    --cGerror_level;
1277  cGexpect_bad_order = 0;
1278
1279  /* Each time packet 0 is acknowledged, we call uwindow_acked since a
1280     new window has been acked.  */
1281  if (iack < iGremote_ack)
1282    uwindow_acked (qdaemon, FALSE);
1283
1284  iGremote_ack = iack;
1285
1286  if (iGretransmit_seq == -1)
1287    return TRUE;
1288
1289  inext = INEXTSEQ (iGretransmit_seq);
1290  if (inext == iGsendseq)
1291    iGretransmit_seq = -1;
1292  else
1293    {
1294      DEBUG_MESSAGE1 (DEBUG_PROTO,
1295		      "fggot_ack: Sending packet %d", inext);
1296
1297      ++cGresent_packets;
1298      zsend = zgadjust_ack (inext);
1299      if (! fsend_data (qdaemon->qconn, zsend, CFRAMELEN + CPACKLEN (zsend),
1300			TRUE))
1301	return FALSE;
1302      inext = INEXTSEQ (inext);
1303      if (inext == iGsendseq)
1304	iGretransmit_seq = -1;
1305      else
1306	{
1307	  DEBUG_MESSAGE1 (DEBUG_PROTO,
1308			  "fggot_ack: Sending packet %d", inext);
1309
1310	  ++cGresent_packets;
1311	  zsend = zgadjust_ack (inext);
1312	  if (! fsend_data (qdaemon->qconn, zsend,
1313			    CFRAMELEN + CPACKLEN (zsend), TRUE))
1314	    return FALSE;
1315	  iGretransmit_seq = inext;
1316	}
1317    }
1318
1319  return TRUE;
1320}
1321
1322/* See if we've received more than the permitted number of errors.  If
1323   we receive a bad packet, we can expect a window full (less one) of
1324   out of order packets to follow, so we discount cGbad_order
1325   accordingly.  */
1326
1327static boolean
1328fgcheck_errors (qdaemon)
1329     struct sdaemon *qdaemon;
1330{
1331  if (cGerror_level > cGmax_errors && cGmax_errors >= 0)
1332    {
1333      ulog (LOG_ERROR, "Too many '%c' protocol errors",
1334	    qdaemon->qproto->bname);
1335      return FALSE;
1336    }
1337
1338  return TRUE;
1339}
1340
1341/* Process the receive buffer into a data packet, if possible.  All
1342   control packets are handled here.  When a data packet is received,
1343   fgprocess_data calls fgot_data with the data; if that sets its
1344   pfexit argument to TRUE fgprocess_data will set *pfexit to TRUE and
1345   return TRUE.  Also, if the freturncontrol argument is TRUE
1346   fgprocess_data will set *pfexit to TRUE and return TRUE.  Otherwise
1347   fgprocess_data will continue trying to process data.  If some error
1348   occurs, fgprocess_data will return FALSE.  If there is not enough
1349   data to form a complete packet, then *pfexit will be set to FALSE,
1350   *pcneed will be set to the number of bytes needed to form a
1351   complete packet (unless pcneed is NULL) and fgprocess_data will
1352   return TRUE.  If this function found a data packet, and pffound is
1353   not NULL, it will set *pffound to TRUE; this can be used to tell
1354   valid data from an endless stream of garbage and control packets.
1355   If fdoacks is TRUE, received packets will be acknowledged;
1356   otherwise they must be acknowledged later.  */
1357
1358static boolean
1359fgprocess_data (qdaemon, fdoacks, freturncontrol, pfexit, pcneed, pffound)
1360     struct sdaemon *qdaemon;
1361     boolean fdoacks;
1362     boolean freturncontrol;
1363     boolean *pfexit;
1364     size_t *pcneed;
1365     boolean *pffound;
1366{
1367  *pfexit = FALSE;
1368  if (pffound != NULL)
1369    *pffound = FALSE;
1370
1371  while (iPrecstart != iPrecend)
1372    {
1373      char ab[CFRAMELEN];
1374      int i, iget, cwant;
1375      unsigned short ihdrcheck, idatcheck;
1376      const char *zfirst, *zsecond;
1377      int cfirst, csecond;
1378      boolean fduprr;
1379
1380      /* Look for the DLE which must start a packet.  */
1381      if (abPrecbuf[iPrecstart] != DLE)
1382	{
1383	  char *zdle;
1384
1385	  cfirst = iPrecend - iPrecstart;
1386	  if (cfirst < 0)
1387	    cfirst = CRECBUFLEN - iPrecstart;
1388
1389	  zdle = memchr (abPrecbuf + iPrecstart, DLE, (size_t) cfirst);
1390
1391	  if (zdle == NULL)
1392	    {
1393	      iPrecstart = (iPrecstart + cfirst) % CRECBUFLEN;
1394	      continue;
1395	    }
1396
1397	  /* We don't need % CRECBUFLEN here because zdle - (abPrecbuf
1398	     + iPrecstart) < cfirst <= CRECBUFLEN - iPrecstart.  */
1399	  iPrecstart += zdle - (abPrecbuf + iPrecstart);
1400	}
1401
1402      /* Get the first six bytes into ab.  */
1403      for (i = 0, iget = iPrecstart;
1404	   i < CFRAMELEN && iget != iPrecend;
1405	   i++, iget = (iget + 1) % CRECBUFLEN)
1406	ab[i] = abPrecbuf[iget];
1407
1408      /* If there aren't six bytes, there is no packet.  */
1409      if (i < CFRAMELEN)
1410	{
1411	  if (pcneed != NULL)
1412	    *pcneed = CFRAMELEN - i;
1413	  return TRUE;
1414	}
1415
1416      /* Make sure these six bytes start a packet.  The check on
1417	 IFRAME_DLE is basically a debugging check, since the above
1418	 code should have ensured that it will never fail.  If this is
1419	 not the start of a packet, bump iPrecstart and loop around to
1420	 look for another DLE.  */
1421      if (ab[IFRAME_DLE] != DLE
1422	  || ab[IFRAME_K] < 1
1423	  || ab[IFRAME_K] > 9
1424	  || ab[IFRAME_XOR] != (ab[IFRAME_K] ^ ab[IFRAME_CHECKLOW]
1425				^ ab[IFRAME_CHECKHIGH] ^ ab[IFRAME_CONTROL])
1426	  || CONTROL_TT (ab[IFRAME_CONTROL]) == ALTCHAN)
1427	{
1428	  ++cGbad_hdr;
1429	  ++cGerror_level;
1430
1431	  DEBUG_MESSAGE4 (DEBUG_PROTO | DEBUG_ABNORMAL,
1432			  "fgprocess_data: Bad header: K %d TT %d XOR byte %d calc %d",
1433			  ab[IFRAME_K] & 0xff,
1434			  CONTROL_TT (ab[IFRAME_CONTROL]),
1435			  ab[IFRAME_XOR] & 0xff,
1436			  (ab[IFRAME_K]
1437			   ^ ab[IFRAME_CHECKLOW]
1438			   ^ ab[IFRAME_CHECKHIGH]
1439			   ^ ab[IFRAME_CONTROL]) & 0xff);
1440
1441	  if (! fgcheck_errors (qdaemon))
1442	    return FALSE;
1443
1444	  iPrecstart = (iPrecstart + 1) % CRECBUFLEN;
1445	  continue;
1446	}
1447
1448      /* The zfirst and cfirst pair point to the first set of data for
1449	 this packet; the zsecond and csecond point to the second set,
1450	 in case the packet wraps around the end of the buffer.  */
1451      zfirst = abPrecbuf + iPrecstart + CFRAMELEN;
1452      cfirst = 0;
1453      zsecond = NULL;
1454      csecond = 0;
1455
1456      if (ab[IFRAME_K] == KCONTROL)
1457	{
1458	  /* This is a control packet.  It should not have any data.  */
1459	  if (CONTROL_TT (ab[IFRAME_CONTROL]) != CONTROL)
1460	    {
1461	      ++cGbad_hdr;
1462	      ++cGerror_level;
1463
1464	      DEBUG_MESSAGE0 (DEBUG_PROTO | DEBUG_ABNORMAL,
1465			      "fgprocess_data: Bad header: control packet with data");
1466
1467	      if (! fgcheck_errors (qdaemon))
1468		return FALSE;
1469
1470	      iPrecstart = (iPrecstart + 1) % CRECBUFLEN;
1471	      continue;
1472	    }
1473
1474	  idatcheck = (unsigned short) (0xaaaa - ab[IFRAME_CONTROL]);
1475	  cwant = 0;
1476	}
1477      else
1478	{
1479	  int cinbuf;
1480	  unsigned short icheck;
1481
1482	  /* This is a data packet.  It should not be type CONTROL.  */
1483	  if (CONTROL_TT (ab[IFRAME_CONTROL]) == CONTROL)
1484	    {
1485	      ++cGbad_hdr;
1486	      ++cGerror_level;
1487
1488	      DEBUG_MESSAGE0 (DEBUG_PROTO | DEBUG_ABNORMAL,
1489			      "fgprocess_data: Bad header: data packet is type CONTROL");
1490
1491	      if (! fgcheck_errors (qdaemon))
1492		return FALSE;
1493
1494	      iPrecstart = (iPrecstart + 1) % CRECBUFLEN;
1495	      continue;
1496	    }
1497
1498	  cinbuf = iPrecend - iPrecstart;
1499	  if (cinbuf < 0)
1500	    cinbuf += CRECBUFLEN;
1501	  cinbuf -= CFRAMELEN;
1502
1503	  /* Make sure we have enough data.  If we don't, wait for
1504	     more.  */
1505
1506	  cwant = (int) CPACKLEN (ab);
1507	  if (cinbuf < cwant)
1508	    {
1509	      if (pcneed != NULL)
1510		*pcneed = cwant - cinbuf;
1511	      return TRUE;
1512	    }
1513
1514	  /* Set up the data pointers and compute the checksum.  */
1515	  if (iPrecend >= iPrecstart)
1516	    cfirst = cwant;
1517	  else
1518	    {
1519	      cfirst = CRECBUFLEN - (iPrecstart + CFRAMELEN);
1520	      if (cfirst >= cwant)
1521		cfirst = cwant;
1522	      else if (cfirst > 0)
1523		{
1524		  zsecond = abPrecbuf;
1525		  csecond = cwant - cfirst;
1526		}
1527	      else
1528		{
1529		  /* Here cfirst is non-positive, so subtracting from
1530		     abPrecbuf will actually skip the appropriate number
1531		     of bytes at the start of abPrecbuf.  */
1532		  zfirst = abPrecbuf - cfirst;
1533		  cfirst = cwant;
1534		}
1535	    }
1536
1537	  if (csecond == 0)
1538	    icheck = (unsigned short) igchecksum (zfirst, (size_t) cfirst);
1539	  else
1540	    icheck = (unsigned short) igchecksum2 (zfirst, (size_t) cfirst,
1541						   zsecond,
1542						   (size_t) csecond);
1543
1544	  idatcheck = ((unsigned short)
1545		       (((0xaaaa - (icheck ^ (ab[IFRAME_CONTROL] & 0xff)))
1546			 & 0xffff)));
1547	}
1548
1549      ihdrcheck = (unsigned short) (((ab[IFRAME_CHECKHIGH] & 0xff) << 8)
1550				    | (ab[IFRAME_CHECKLOW] & 0xff));
1551
1552      if (ihdrcheck != idatcheck)
1553	{
1554	  DEBUG_MESSAGE2 (DEBUG_PROTO | DEBUG_ABNORMAL,
1555			  "fgprocess_data: Bad checksum: header 0x%x, data 0x%x",
1556			  ihdrcheck, idatcheck);
1557
1558	  ++cGbad_checksum;
1559	  ++cGerror_level;
1560
1561	  if (! fgcheck_errors (qdaemon))
1562	    return FALSE;
1563
1564	  /* If the checksum failed for a data packet, then if it was
1565	     the one we were expecting send an RJ, otherwise ignore
1566	     it.  Previously if this code got the wrong packet number
1567	     it would send an RR, but that may confuse some Telebit
1568	     modems and it doesn't help in any case since the receiver
1569	     will probably just ignore the RR as a duplicate (that's
1570	     basically what this code does).  If we totally missed the
1571	     packet we will time out and send an RJ in the function
1572	     fgwait_for_packet above.  */
1573	  if (CONTROL_TT (ab[IFRAME_CONTROL]) != CONTROL)
1574	    {
1575	      /* Make sure we've acked everything up to this point.  */
1576	      if (iGrecseq != iGlocal_ack)
1577		{
1578		  if (! fgsend_acks (qdaemon))
1579		    return FALSE;
1580		}
1581
1582	      /* If this is the packet we wanted, tell the sender that
1583		 it failed.  */
1584	      if (CONTROL_XXX (ab[IFRAME_CONTROL]) == INEXTSEQ (iGrecseq))
1585		{
1586		  if (! fgsend_control (qdaemon, RJ, iGrecseq))
1587		    return FALSE;
1588		  cGexpect_bad_order += iGrequest_winsize - 1;
1589		}
1590	    }
1591
1592	  /* We can't skip the packet data after this, because if we
1593	     have lost incoming bytes the next DLE will be somewhere
1594	     in what we thought was the packet data.  */
1595	  iPrecstart = (iPrecstart + 1) % CRECBUFLEN;
1596	  continue;
1597	}
1598
1599      /* We have a packet; remove the processed bytes from the receive
1600	 buffer.  */
1601      iPrecstart = (iPrecstart + cwant + CFRAMELEN) % CRECBUFLEN;
1602
1603      /* Store the control byte for the handshake routines.  */
1604      iGpacket_control = ab[IFRAME_CONTROL] & 0xff;
1605
1606      /* Annoyingly, some UUCP packages appear to send an RR packet
1607	 rather than an RJ packet when they want a packet to be
1608	 resent.  If we get a duplicate RR and we've never seen an RJ,
1609	 we treat the RR as an RJ.  */
1610      fduprr = FALSE;
1611      if (cGremote_rejects == 0
1612	  && CONTROL_TT (ab[IFRAME_CONTROL]) == CONTROL
1613	  && CONTROL_XXX (ab[IFRAME_CONTROL]) == RR
1614	  && iGremote_ack == CONTROL_YYY (ab[IFRAME_CONTROL])
1615	  && INEXTSEQ (iGremote_ack) != iGsendseq
1616	  && iGretransmit_seq == -1)
1617	{
1618	  DEBUG_MESSAGE0 (DEBUG_PROTO | DEBUG_ABNORMAL,
1619			  "fgprocess_data: Treating duplicate RR as RJ");
1620	  fduprr = TRUE;
1621	}
1622
1623      /* Update the received sequence number from the yyy field of a
1624	 data packet (if it is the one we are expecting) or an RR
1625	 control packet.  If we've been delaying sending packets until
1626	 we received an ack, this may send out some packets.  */
1627      if ((CONTROL_TT (ab[IFRAME_CONTROL]) != CONTROL
1628	   && CONTROL_XXX (ab[IFRAME_CONTROL]) == INEXTSEQ (iGrecseq))
1629	  || (CONTROL_XXX (ab[IFRAME_CONTROL]) == RR && ! fduprr))
1630	{
1631	  if (! fggot_ack (qdaemon, CONTROL_YYY (ab[IFRAME_CONTROL])))
1632	    return FALSE;
1633	}
1634
1635      /* If this isn't a control message, make sure we have received
1636	 the expected packet sequence number, acknowledge the packet
1637	 if it's the right one, and process the data.  */
1638      if (CONTROL_TT (ab[IFRAME_CONTROL]) != CONTROL)
1639	{
1640	  if (CONTROL_XXX (ab[IFRAME_CONTROL]) != INEXTSEQ (iGrecseq))
1641	    {
1642	      /* We got the wrong packet number.  */
1643	      DEBUG_MESSAGE2 (DEBUG_PROTO | DEBUG_ABNORMAL,
1644			      "fgprocess_data: Got packet %d; expected %d",
1645			      CONTROL_XXX (ab[IFRAME_CONTROL]),
1646			      INEXTSEQ (iGrecseq));
1647
1648	      if (cGexpect_bad_order > 0)
1649		--cGexpect_bad_order;
1650	      else
1651		{
1652		  ++cGbad_order;
1653		  ++cGerror_level;
1654		  if (! fgcheck_errors (qdaemon))
1655		    return FALSE;
1656		}
1657
1658	      /* This code used to send an RR to encourage the other
1659		 side to get back in synch, but that may confuse some
1660		 Telebit modems and does little good in any case,
1661		 since the other side will probably just ignore it
1662		 anyhow (that's what this code does).  */
1663	      continue;
1664	    }
1665
1666	  /* We got the packet we expected.  */
1667	  ++cGrec_packets;
1668	  if (cGerror_level > 0
1669	      && cGrec_packets % cGerror_decay == 0)
1670	    --cGerror_level;
1671	  cGexpect_bad_order = 0;
1672
1673	  iGrecseq = INEXTSEQ (iGrecseq);
1674
1675	  DEBUG_MESSAGE1 (DEBUG_PROTO,
1676			  "fgprocess_data: Got packet %d", iGrecseq);
1677
1678	  /* Tell the caller that we found something.  */
1679	  if (pffound != NULL)
1680	    *pffound = TRUE;
1681
1682	  /* If we are supposed to do acknowledgements here, send back
1683	     an RR packet.  */
1684	  if (fdoacks)
1685	    {
1686	      if (! fgsend_acks (qdaemon))
1687		return FALSE;
1688	    }
1689
1690	  /* If this is a short data packet, adjust the data pointers
1691	     and lengths.  */
1692	  if (CONTROL_TT (ab[IFRAME_CONTROL]) == SHORTDATA)
1693	    {
1694	      int cshort, cmove;
1695
1696	      if ((zfirst[0] & 0x80) == 0)
1697		{
1698		  cshort = zfirst[0] & 0xff;
1699		  cmove = 1;
1700		}
1701	      else
1702		{
1703		  int cbyte2;
1704
1705		  if (cfirst > 1)
1706		    cbyte2 = zfirst[1] & 0xff;
1707		  else
1708		    cbyte2 = zsecond[0] & 0xff;
1709		  cshort = (zfirst[0] & 0x7f) + (cbyte2 << 7);
1710		  cmove = 2;
1711		}
1712
1713	      DEBUG_MESSAGE1 (DEBUG_PROTO,
1714			      "fgprocess_data: Packet short by %d",
1715			      cshort);
1716
1717	      /* Adjust the start of the buffer for the bytes used
1718		 by the count.  */
1719	      if (cfirst > cmove)
1720		{
1721		  zfirst += cmove;
1722		  cfirst -= cmove;
1723		}
1724	      else
1725		{
1726		  zfirst = zsecond + (cmove - cfirst);
1727		  cfirst = csecond - (cmove - cfirst);
1728		  csecond = 0;
1729		}
1730
1731	      /* Adjust the length of the buffer for the bytes we are
1732		 not supposed to consider.  */
1733	      cshort -= cmove;
1734	      if (csecond >= cshort)
1735		csecond -= cshort;
1736	      else
1737		{
1738		  cfirst -= cshort - csecond;
1739		  csecond = 0;
1740		}
1741
1742#if DEBUG > 0
1743	      /* This should not happen, but just in case.  */
1744	      if (cfirst < 0)
1745		cfirst = 0;
1746#endif
1747	    }
1748
1749	  if (! fgot_data (qdaemon, zfirst, (size_t) cfirst,
1750			   zsecond, (size_t) csecond,
1751			   -1, -1, (long) -1,
1752			   INEXTSEQ (iGremote_ack) == iGsendseq,
1753			   pfexit))
1754	    return FALSE;
1755
1756	  /* If fgot_data told us that we were finished, get out.  */
1757	  if (*pfexit)
1758	    return TRUE;
1759
1760	  /* If we've been asked to return control packets, get out
1761	     now.  */
1762	  if (freturncontrol)
1763	    {
1764	      *pfexit = TRUE;
1765	      return TRUE;
1766	    }
1767
1768	  continue;
1769	}
1770
1771      /* Handle control messages here. */
1772#if DEBUG > 1
1773      if (FDEBUGGING (DEBUG_PROTO)
1774	  || (FDEBUGGING (DEBUG_ABNORMAL)
1775	      && CONTROL_XXX (ab[IFRAME_CONTROL]) != RR))
1776	ulog (LOG_DEBUG, "fgprocess_data: Got control %s %d",
1777	      azGcontrol[CONTROL_XXX (ab[IFRAME_CONTROL])],
1778	      CONTROL_YYY (ab[IFRAME_CONTROL]));
1779#endif
1780
1781      switch (CONTROL_XXX (ab[IFRAME_CONTROL]))
1782	{
1783	case CLOSE:
1784	  /* The other side has closed the connection.  */
1785	  if (fLog_sighup)
1786	    {
1787	      ulog (LOG_ERROR, "Received unexpected CLOSE packet");
1788	      (void) fgsend_control (qdaemon, CLOSE, 0);
1789	    }
1790	  return FALSE;
1791	case RR:
1792	  /* Acknowledge receipt of a packet.  This was already handled
1793	     above, unless we are treating it as RJ.  */
1794	  if (! fduprr)
1795	    break;
1796	  /* Fall through.  */
1797	case RJ:
1798	  /* The other side dropped a packet.  Begin retransmission with
1799	     the packet following the one acknowledged.  We don't
1800	     retransmit the packets immediately, but instead wait
1801	     for the first one to be acked.  This prevents us from
1802	     sending an entire window several times if we get several
1803	     RJ packets.  */
1804	  iGremote_ack = CONTROL_YYY (ab[IFRAME_CONTROL]);
1805	  iGretransmit_seq = INEXTSEQ (iGremote_ack);
1806	  if (iGretransmit_seq == iGsendseq)
1807	    iGretransmit_seq = -1;
1808	  else
1809	    {
1810	      char *zpack;
1811
1812	      DEBUG_MESSAGE2 (DEBUG_PROTO | DEBUG_ABNORMAL,
1813			      "fgprocess_data: Remote reject: next %d resending %d",
1814			      iGsendseq, iGretransmit_seq);
1815
1816	      ++cGresent_packets;
1817	      if (fduprr)
1818		++cGremote_duprrs;
1819	      else
1820		++cGremote_rejects;
1821	      ++cGerror_level;
1822	      if (! fgcheck_errors (qdaemon))
1823		return FALSE;
1824	      zpack = zgadjust_ack (iGretransmit_seq);
1825	      if (! fsend_data (qdaemon->qconn, zpack,
1826				CFRAMELEN + CPACKLEN (zpack),
1827				TRUE))
1828		return FALSE;
1829	    }
1830	  break;
1831	case SRJ:
1832	  /* Selectively reject a particular packet.  This is not used
1833	     by UUCP, but it's easy to support.  */
1834	  DEBUG_MESSAGE1 (DEBUG_PROTO | DEBUG_ABNORMAL,
1835			  "fgprocess_data: Selective reject of %d",
1836			  CONTROL_YYY (ab[IFRAME_CONTROL]));
1837	  {
1838	    char *zpack;
1839
1840	    ++cGresent_packets;
1841	    ++cGremote_rejects;
1842	    ++cGerror_level;
1843	    zpack = zgadjust_ack (CONTROL_YYY (ab[IFRAME_CONTROL]));
1844	    if (! fsend_data (qdaemon->qconn, zpack,
1845			      CFRAMELEN + CPACKLEN (zpack),
1846			      TRUE))
1847	      return FALSE;
1848	  }
1849	  break;
1850	case INITC:
1851	case INITB:
1852	case INITA:
1853	  /* Ignore attempts to reinitialize.  */
1854	  break;
1855	}
1856
1857      /* If we've been asked to return control packets, get out.  */
1858      if (freturncontrol)
1859	{
1860	  *pfexit = TRUE;
1861	  return TRUE;
1862	}
1863
1864      /* Loop around to look for the next packet, if any.  */
1865    }
1866
1867  /* There is no data left in the receive buffer.  */
1868  if (pcneed != NULL)
1869    *pcneed = CFRAMELEN;
1870  return TRUE;
1871}
1872
1873/* Compute the 'g' protocol checksum.  This is unfortunately rather
1874   awkward.  This is the most time consuming code in the entire
1875   program.  It's also not a great checksum, since it can be fooled
1876   by some single bit errors.  */
1877
1878/* Sorry about this knavery, but it speeds up the VAX code
1879   significantly.  It would be better to rewrite the whole routine in
1880   assembler.  */
1881#ifdef __GNUC__
1882#ifdef __vax__
1883#define VAX_ASM 1
1884#endif
1885#endif
1886
1887#if VAX_ASM
1888#define ROTATE(i) \
1889  asm ("cvtwl %1,%0\n\trotl $1,%0,%0" : "=g" (i) : "g" (i))
1890#else
1891#define ROTATE(i) i += i + ((i & 0x8000) >> 15)
1892#endif
1893
1894#define ITERATION \
1895      /* Rotate ichk1 left.  */ \
1896      ROTATE (ichk1); \
1897 \
1898      /* The guts of the checksum.  */ \
1899      b = BUCHAR (*z++); \
1900      if (b != 0) \
1901	{ \
1902	  ichk1 &= 0xffff; \
1903	  ichk1 += b; \
1904	  ichk2 += ichk1 ^ c; \
1905	  if ((ichk1 >> 16) != 0) \
1906	    ichk1 ^= ichk2; \
1907	} \
1908      else \
1909	{ \
1910	  ichk2 += ichk1 ^ c; \
1911	  ichk1 ^= ichk2; \
1912	} \
1913 \
1914      --c
1915
1916static int
1917igchecksum (z, c)
1918     register const char *z;
1919     register size_t c;
1920{
1921  register unsigned long ichk1, ichk2;
1922
1923  ichk1 = 0xffff;
1924  ichk2 = 0;
1925
1926  do
1927    {
1928      register unsigned int b;
1929
1930      ITERATION;
1931      ITERATION;
1932      ITERATION;
1933      ITERATION;
1934    }
1935  while (c > 0);
1936
1937  return ichk1 & 0xffff;
1938}
1939
1940/* We use a separate function compute the checksum if the block is
1941   split around the end of the receive buffer since it occurs much
1942   less frequently and the checksum is already high up in the
1943   profiles.  These functions are almost identical, and this one
1944   actually only has a few more instructions in the inner loop.  */
1945
1946static int
1947igchecksum2 (zfirst, cfirst, zsecond, csecond)
1948     const char *zfirst;
1949     size_t cfirst;
1950     const char *zsecond;
1951     size_t csecond;
1952{
1953  register unsigned long ichk1, ichk2;
1954  register const char *z;
1955  register size_t c;
1956
1957  z = zfirst;
1958  c = cfirst + csecond;
1959
1960  ichk1 = 0xffff;
1961  ichk2 = 0;
1962
1963  do
1964    {
1965      register unsigned int b;
1966
1967      ITERATION;
1968
1969      /* If the first buffer has been finished, switch to the second.  */
1970      --cfirst;
1971      if (cfirst == 0)
1972	z = zsecond;
1973    }
1974  while (c > 0);
1975
1976  return ichk1 & 0xffff;
1977}
1978