/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* |_o_o|\\ Copyright (c) 1990 The Software Distillery.  All Rights Reserved */
/* |. o.| || This program may not be distributed without the permission of   */
/* | .	| || the authors:			      BBS: (919) 382-8265    */
/* | o	| ||   Dave Baker      Alan Beale	  Jim Cooper		     */
/* |  . |//    Jay Denebeim    Bruce Drake	  Gordon Keener 	     */
/* ======      John Mainwaring Andy Mercier	  Jack Rouse		     */
/*	       John Toebes     Mary Ellen Toebes  Doug Walker  Mike Whitcher */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
   
/*
 *  QUICKB.C - Quick B Protocol Support routines
 *
 *	converted to C by Paul M. Resch
 *	modified to function as an Amiga XPR protocol library by
 *		Jack Rouse of the Software Distillery.
 */

/*
 * This module implements the B-Protocol Functions.
 *
 * bp_DLE should be invoked whenever a <DLE> is received.
 * bp_ENQ should be called whenever an <ENQ> is received.
 * bp_ESC_I should be called when the sequence <ESC><I> is received.
 *
 * cgetc is an external procedure which returns a character from the
 *	communications port or -1 if no character is received within the time
 *	specified (in microseconds).
 * cputc is an external procedure which sends a character to the communication
 *	port.
 *
 * This source was originally derived from QUICKB.INC, version 121687, written
 * by Russ Ranshaw, CompuServe Incorporated.
 *
 */

#include "quickb.h"

/* Table of control characters that need to be masked */

static	char	mask_table[] = {
                0, 0, 0, 1, 0, 1, 0, 0,   /* NUL SOH SOB ETX EOT ENQ SYN BEL */
                0, 0, 0, 0, 0, 0, 0, 0,   /* BS  HT  LF  VT  FF  CR  SO  SI  */
                1, 1, 0, 1, 0, 1, 0, 0,   /* DLE DC1 DC2 DC3 DC4 NAK ^V  ^W  */
                0, 0, 0, 0, 0, 0, 0, 0};  /* CAN ^Y  ^Z  ESC ?   ?   ?   ?   */

static	char	hex_digit[] = "0123456789ABCDEF";

static int SA_Flush(struct XPR_DATA *xd);
static int send_packet(struct XPR_DATA *xd, int size);

/*
 * crc
 *
 * Calculates XMODEM-style CRC (uses the CCITT V.41 polynomial but
 * completely backwards from the normal bit ordering).
 */


static	unsigned short	crc_table[] = {
        0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7,
        0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF,
        0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6,
        0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE,
        0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485,
        0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D,
        0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4,
        0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC,
        0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823,
        0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B,
        0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12,
        0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A,
        0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41,
        0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49,
        0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70,
        0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78,
        0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F,
        0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067,
        0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E,
        0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256,
        0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D,
        0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
        0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C,
        0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634,
        0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB,
        0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3,
        0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A,
        0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92,
        0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9,
        0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1,
        0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8,
        0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0
	};


/*
 * Init_CRC initializes for XMODEM style CRC calculation by setting
 * crc_16 to value.  Typically value is 0 for XMODEM and -1 for
 * B+ Protocl.  It returns the initial value.
 */
static	int	init_CRC (struct XPR_DATA *xd, int value)
{
	return (int)( xd->crc_16 = value );
}

/*
  Upd_CRC updates crc_16 and returns the updated value. */

static	unsigned int	upd_CRC (struct XPR_DATA *xd, unsigned int value)
{
	xd->crc_16 = crc_table [((xd->crc_16 >> 8) ^ (value)) & 0xff] ^	(xd->crc_16 << 8);
	return( (unsigned int)xd->crc_16 );
}

/* Update the checksum/CRC */

static	void	do_checksum(struct XPR_DATA *xd, int c)
{
	if (xd->Quick_B && xd->Use_CRC)
		xd->checksum = upd_CRC (xd, c);
	else
	{
		xd->checksum = xd->checksum << 1;

		if (xd->checksum > 255)
			xd->checksum = (xd->checksum & 0xFF) + 1;

		xd->checksum = xd->checksum + c;

		if (xd->checksum > 255)
			xd->checksum = (xd->checksum & 0xFF) + 1;
	}
}

static	void	send_failure(struct XPR_DATA *xd, int code )
{
	register PACKET	*p;

	xd->ack_SA = 0;
	xd->fill_SA = 0;
	xd->SA_Waiting = 0;
	xd->Aborting = TRUE;		/* inform get_ACK we're aborting */

	p = &xd->SA_Buf [0];
	p->buf[0] = 'F';
	p->buf[1] = code;

	if ( send_packet (xd, 1))
		SA_Flush(xd);   /* Gotta wait for the host to ACK it */
}

/*
 * bp_ENQ is called when the terminal emulator receives the character <ENQ>
 * from the host.  Its purpose is to initialize for B Protocol and tell the
 * host that we support Quick B.
 */

void	bp_ENQ(struct XPR_DATA *xd)
{
	xd->seq_num = 0;
	xd->buffer_size = 511;               /* Set up defaults */
	xd->Quick_B     = FALSE;             /* Not Quick B Protocol */
	xd->Use_CRC     = FALSE;             /* Not CRC_16      */
	xd->SA_Enabled  = FALSE;             /* No Send-Ahead by us */
	xd->SA_Max      = 1;                 /* = single packet sent */

	cputc (xd, DLE);
	cputc (xd, '+');

	cputc (xd, DLE);
	cputc (xd, '0');
}

/*
 * bp_ESC_I is called when <ESC><I> is received by the terminal emulator.
 * Note that Quick B allows +XX to be added to the end of the response, where
 * XX is the two hex digits of the standard B Protocol checksum of the
 * preceeding characters in the response.
 */
static	char	esc_I_response[] = "#VCO,PB,DT,+";

void	bp_ESC_I(struct XPR_DATA *xd)
{
	int	save_Use_CRC;
	register int	i;

	save_Use_CRC = xd->Use_CRC;
	xd->Use_CRC = FALSE;
	xd->checksum = 0;

	i = 0;
	while( esc_I_response[i] )
	{
		cputc (xd, esc_I_response [i]);
		do_checksum (xd, esc_I_response [i]);
		i++;
	}

/* Append two hex digits of checksum to response */

	cputc (xd,  hex_digit[ (xd->checksum >> 4) & 0x0F ]);
	cputc (xd,  hex_digit[ xd->checksum & 0x0F ] );
	cputc (xd, CR);

	xd->Use_CRC = save_Use_CRC;
}


static	void	send_masked_byte(struct XPR_DATA *xd, int c)
{
	c = c & 0xFF;

	if (c < 32)
	{
		if (mask_table [c] != 0)
		{
			cputc (xd, DLE);
			cputc (xd, c + '@');
		}
		else
			cputc (xd, c);
	}
	else
		cputc (xd, c);

	xd->s_counter = (xd->s_counter + 1) % 512;
}

static	void	send_ack(struct XPR_DATA *xd)
{
	cputc(xd, DLE);
	cputc(xd, xd->seq_num + '0');
}

static	void	send_nak(struct XPR_DATA *xd)
{
	cputc(xd, NAK);
}


static	void	send_enq(struct XPR_DATA *xd)
{
	cputc(xd, ENQ);
}

static	int	read_byte(struct XPR_DATA *xd)
{
	xd->timed_out = FALSE;

	xd->cchar = cgetc(xd, 10000000L);

	if (xd->cchar < 0 )
		return( FALSE );

	xd->r_counter = (xd->r_counter + 1) % 512;
	return( TRUE );
}


static	int	read_masked_byte(struct XPR_DATA *xd)
{
	xd->masked = FALSE;

	if (read_byte(xd) == FALSE)
		return( FALSE );

	if (xd->cchar == DLE)
	{
		if (read_byte(xd) == FALSE)
			return( FALSE );
		xd->cchar &= 0x1F;
		xd->masked = TRUE;
	}

	return( TRUE );
}

/* Increment Sequence Number */

static	int	incr_seq (int value)
{
	return( value == 9 ? 0 : value + 1 );
}


static	int	read_packet (struct XPR_DATA *xd,
	int lead_in_seen, int from_send_packet)
/*   Lead_in_Seen is TRUE if the <DLE><B> has been seen already.  */

/*   from_send_packet is TRUE if called from Send_Packet          */
/*        (causes exit on first error detected)                   */

/*   Returns True if packet is available from host. */
{
	int	State, next_seq, block_num, errors, new_cks;
	int	i;

	xd->packet_received = FALSE;
	for(i=0; i<xd->buffer_size; i++ )
		xd->r_buffer[i] = 0;
	next_seq = (xd->seq_num +  1) % 10;
	errors = 0;

	if (lead_in_seen)		/* Start off on the correct foot */
		State = R_GET_SEQ;
	else
		State = R_GET_DLE;

	while (TRUE)
	{
		switch  (State) {
		case R_GET_DLE :
			(*xd->xpr_chkmisc)();
			if (!xd->Aborting && (*xd->xpr_chkabort)())
			{
				send_failure (xd, 'A');
				return( FALSE );
			}

			if (!read_byte(xd))
	            		State = R_TIMED_OUT;
			else if ((xd->cchar & 0x7F) == DLE)
	        	    	State = R_GET_B;
			else if ((xd->cchar & 0x7F) == ENQ)
        			State = R_SEND_ACK;
			break;

		case R_GET_B :
			if (!read_byte(xd))
				State = R_TIMED_OUT;
			else if ((xd->cchar & 0x7F) == 'B')
				State = R_GET_SEQ;
			else if (xd->cchar == ENQ)
				State = R_SEND_ACK;
			else
				State = R_GET_DLE;
			break;

		case R_GET_SEQ :
			if (!read_byte(xd))
				State = R_TIMED_OUT;
			else if (xd->cchar == ENQ)
				State = R_SEND_ACK;
			else
			{
				if (xd->Quick_B && xd->Use_CRC)
					xd->checksum = init_CRC (xd, -1);
				else xd->checksum = 0;

				block_num = xd->cchar - '0';

				do_checksum(xd, xd->cchar);

				i = 0;
				State = R_GET_DATA;
			}
			break;

		case R_GET_DATA :
			xd->r_counter = 0;
			if (!read_masked_byte(xd))
				State = R_TIMED_OUT;
			else if ((xd->cchar == ETX) && !xd->masked)
			{
				do_checksum(xd, ETX);
				State = R_GET_CHECKSUM;
			}
			else if (i >= MAX_BUF_SIZE)
				State = R_TIMED_OUT;
			else
			{
				xd->r_buffer[i] = xd->cchar;
				i = i + 1;
				do_checksum(xd, xd->cchar);
			}
			break;

		case R_GET_CHECKSUM :
			if (!read_masked_byte(xd))
				State = R_TIMED_OUT;
			else
			{
				if (xd->Quick_B && xd->Use_CRC)
				{
					xd->checksum = upd_CRC (xd, xd->cchar);

					if (!read_masked_byte(xd))
						new_cks = xd->checksum ^ 0xFF;
					else
					{
						xd->checksum = upd_CRC (xd, xd->cchar);
						new_cks = 0;
					}
				}
				else new_cks = xd->cchar;

				if (new_cks != xd->checksum)
					State = R_TIMED_OUT;
				else if (xd->r_buffer[0] == 'F') /* Watch for Failure Packet */
					State = R_SUCCESS;       /* which is accepted regardless */
				else if (block_num == xd->seq_num)	/* Watch for duplicate block */
					State = R_SEND_ACK;
				else if (block_num != next_seq)
					State = R_TIMED_OUT;        /* Bad sequence number */
				else
					State = R_SUCCESS;
			}
			break;

		case R_TIMED_OUT :
			xd->xpru.xpru_updatemask = XPRU_TIMEOUTS;
			++xd->xpru.xpru_timeouts;
			(*xd->xpr_update)(&xd->xpru);

			if ((++errors > MAX_ERRORS) || (from_send_packet))
				return( FALSE );

			send_nak(xd);

			if (from_send_packet)
				return( FALSE );

			State = R_GET_DLE;
			break;

		case R_SEND_ACK :
			send_ack(xd);
			State = R_GET_DLE;        /* wait for the next block */
			break;

		case R_SUCCESS :
			xd->seq_num = block_num;
			xd->r_size = i;
			xd->packet_received = TRUE;
#if 0
			xd->xpru.xpru_updatemask = XPRU_PACKETTYPE;
			xd->xpru.xpru_packettype = xd->r_buffer[0];
			(*xd->xpr_update)(&xd->xpru);
#endif
			return( TRUE );
			break;
		}
	}
}

static	void	send_data (struct XPR_DATA *xd, int Buffer_Number)
{
	int	i;
	register PACKET	*p;

	xd->s_counter = 0;
	p = &xd->SA_Buf [Buffer_Number];
	if (xd->Quick_B && xd->Use_CRC)
		xd->checksum = init_CRC (xd, -1);
	else
		xd->checksum = 0;

	cputc(xd, DLE);
	cputc(xd, 'B');

	cputc(xd, p->seq + '0');
        do_checksum(xd, p->seq + '0');

	for (i = 0; i<=p->num; i++ )
	{
		send_masked_byte(xd, p->buf[i]);
		do_checksum(xd, p->buf[i]);
	}

	cputc(xd, ETX);
	do_checksum (xd, ETX);

	if (xd->Quick_B && xd->Use_CRC)
		send_masked_byte (xd, xd->checksum >> 8);

	send_masked_byte(xd, xd->checksum);
}

static	int	incr_SA (int old_value)
{
	return( old_value == MAX_SA ? 0 : old_value + 1 );
}

/*
 * ReSync is called to restablish syncronism with the remote.  This is
 * accomplished by sending <ENQ><ENQ> and waiting for the sequence
 * <DLE><d><DLE><d> to be received, ignoring everything else.
 *
 * Return is -1 on time out, else the digit <d>.
 */
#define	GET_FIRST_DLE		1
#define	GET_FIRST_DIGIT		2
#define	GET_SECOND_DLE		3
#define	GET_SECOND_DIGIT	4

static	int	ReSync(struct XPR_DATA *xd)
{
	int	State, Digit_1;

	cputc (xd, ENQ);     /* Send <ENQ><ENQ> */
	cputc (xd, ENQ);
	State = GET_FIRST_DLE;

	while(1)
	{
		switch (State) {
		case GET_FIRST_DLE :
			if( !read_byte(xd) )
				return( -1 );
			if( xd->cchar == DLE )
				State = GET_FIRST_DIGIT;
			break;
		case GET_FIRST_DIGIT :
			if( !read_byte(xd) )
				return( -1 );
			if( (xd->cchar >= '0') && (xd->cchar <= '9') )
			{
				Digit_1 = xd->cchar;
				State = GET_SECOND_DLE;
			}
			break;
		case GET_SECOND_DLE :
			if( !read_byte(xd) )
				return( -1 );
			if( xd->cchar == DLE )
				State = GET_SECOND_DIGIT;
			break;
		case GET_SECOND_DIGIT :
			if( !read_byte(xd) )
				return( -1 );
			if( (xd->cchar >= '0') && (xd->cchar <= '9') )
			{
				if( Digit_1 == xd->cchar )
					return( xd->cchar );
				else
				{
					Digit_1 = xd->cchar;
					State = GET_SECOND_DLE;
				}
			}
			else
				State = GET_SECOND_DLE;
			break;
		}
	}
}

/*
 * get_ACK is called to wait until the SA_Buf indicated by ack_SA
 * has been ACKed by the host.
 */
static	int	get_ACK(struct XPR_DATA *xd)
{
	int	State, errors, block_num, i;
	int	Sent_ENQ;
	int	SA_Index;

	xd->packet_received = FALSE;
	errors = 0;
	Sent_ENQ = FALSE;
	State = S_GET_DLE;

	while( TRUE )
	{
		switch (State) {
		case S_GET_DLE :
			(*xd->xpr_chkmisc)();
			if (!xd->Aborting && (*xd->xpr_chkabort)())
			{
				send_failure (xd, 'A');
				return( FALSE );
			}

			if (!read_byte(xd))
				State = S_TIMED_OUT;
			else if (xd->cchar == DLE)
				State = S_GET_NUM;
			else if (xd->cchar == NAK)
			{
				xd->xpru.xpru_updatemask = XPRU_ERRORS;
				++xd->xpru.xpru_errors;
				(*xd->xpr_update)(&xd->xpru);
				if (++errors > MAX_ERRORS)
					return( FALSE );
				State = S_SEND_ENQ;
			}
			else if (xd->cchar == ETX)
				State = S_SEND_NAK;
			break;

		case S_GET_NUM :
			if (!read_byte(xd))
				State = S_TIMED_OUT;
			else if ((xd->cchar >= '0') && (xd->cchar <= '9'))
				State = S_HAVE_ACK;	/* Received ACK */
			else if (xd->cchar == 'B')
				State = S_GET_PACKET; /* Try to get packet */
			else if (xd->cchar == NAK)
			{
				xd->xpru.xpru_updatemask = XPRU_ERRORS;
				++xd->xpru.xpru_errors;
				(*xd->xpr_update)(&xd->xpru);
				if (++errors > MAX_ERRORS)
					return( FALSE );
				State = S_SEND_ENQ;
			}
			else
				State = S_TIMED_OUT;
			break;

		case S_GET_PACKET :
			if (read_packet (xd, TRUE, TRUE))
			{
				if (xd->r_buffer [0] == 'F')
				{
					send_ack(xd);
					return( FALSE );
				}
				else
					return( TRUE );
			}

			State = S_TIMED_OUT; /* On a bad receive, try again */
			break;
		case S_HAVE_ACK:
			block_num = xd->cchar - '0';
			if (xd->SA_Buf [xd->ack_SA].seq == block_num)
			{	/* This is the one we're waiting for */
				xd->ack_SA = incr_SA(xd->ack_SA);
				xd->SA_Waiting--;
				return( TRUE );
			}
			else if (xd->SA_Buf [incr_SA (xd->ack_SA)].seq == block_num &&
				(xd->SA_Waiting == 2) )
			{	/* Must have missed an ACK */
				xd->ack_SA = incr_SA (xd->ack_SA);
				xd->ack_SA = incr_SA (xd->ack_SA);
				xd->SA_Waiting -= 2;
				return( TRUE );
			}
			else if (xd->SA_Buf [xd->ack_SA].seq == incr_seq (block_num))
			{
				if( Sent_ENQ )
					State = S_SEND_DATA;
				else
					State = S_GET_DLE;
			}
			else
				State = xd->Aborting ? S_GET_DLE : S_TIMED_OUT;
			Sent_ENQ = FALSE;
			break;
		case S_TIMED_OUT :
			xd->xpru.xpru_updatemask = XPRU_TIMEOUTS;
			++xd->xpru.xpru_timeouts;
			(*xd->xpr_update)(&xd->xpru);

			if (++errors > MAX_ERRORS)
				return( FALSE );
			else
			{
				if( xd->Aborting && (errors > 3) )
					return( FALSE );
			}
			State = S_SEND_ENQ;
			break;

		case S_SEND_NAK :
			xd->xpru.xpru_updatemask = XPRU_ERRORS;
			++xd->xpru.xpru_errors;
			(*xd->xpr_update)(&xd->xpru);

			if (++errors > MAX_ERRORS)
				return( FALSE );

			send_nak(xd);

			State = S_GET_DLE;
			break;

		case S_SEND_ENQ :
			xd->xpru.xpru_updatemask = XPRU_ERRORS;
			++xd->xpru.xpru_errors;
			(*xd->xpr_update)(&xd->xpru);

			if (++errors > MAX_ERRORS)
				return( FALSE );
			xd->cchar = ReSync(xd);
			if( xd->cchar == -1 )
				State = S_SEND_ENQ;
			else
				State = S_HAVE_ACK;
			Sent_ENQ = TRUE;
			break;

		case S_SEND_DATA :
			SA_Index = xd->ack_SA;

			for (i = 1; i<=xd->SA_Waiting; i++ )
			{
				send_data (xd, SA_Index);
				SA_Index = incr_SA (SA_Index);
			}

			State = S_GET_DLE;
			Sent_ENQ = FALSE;
			break;
		}
	}
} /* get_ACK */

static	int	send_packet (struct XPR_DATA *xd, int size)
{
	(*xd->xpr_chkmisc)();

	if (xd->SA_Waiting == xd->SA_Max)
		if (!get_ACK(xd))
			return( FALSE );

	xd->seq_num = incr_seq (xd->seq_num);
	xd->SA_Buf [xd->fill_SA].seq = xd->seq_num;
	xd->SA_Buf [xd->fill_SA].num = size;
	send_data (xd, xd->fill_SA);
	xd->fill_SA = incr_SA (xd->fill_SA);
	xd->SA_Waiting = xd->SA_Waiting + 1;
	return( TRUE );
}
/*
 * SA_Flush is called after sending the last packet to get host's
 * ACKs on outstanding packets.
 */
static	int	SA_Flush(struct XPR_DATA *xd)
{
	while( xd->SA_Waiting > 0 )
		if (!get_ACK(xd))
			return( FALSE );
	return( TRUE );
}

/* Send_File is called to send a file to the host */
static	int	send_file(struct XPR_DATA *xd, char *name)
{
	long	fd;
	int	n;
	register PACKET	*p;

	xd->xpru.xpru_updatemask = XPRU_FILENAME;
	xd->xpru.xpru_filename = name;
	xd->xpru.xpru_filesize = (*xd->xpr_finfo)(name, 1L);
	if (xd->xpru.xpru_filesize != 0) /* inform the user of the size */
		xd->xpru.xpru_updatemask |= XPRU_FILESIZE;
	(*xd->xpr_update)(&xd->xpru);

	fd = bfopen(xd, name, "r");
	xd->xpru.xpru_bytes = 0L;

	if (fd == 0)
  	{
		errormsg(xd, "** Cannot find that file **");
		send_failure(xd, 'E');
		return( FALSE );
	}

	do
	{
		p = &xd->SA_Buf [xd->fill_SA];
		p->buf[0] = 'N';
		n = xbfread(xd, &p->buf[1], (long)xd->buffer_size, fd);

		if (n > 0)
		{
			if (send_packet (xd, n) == FALSE)
			{
				bfclose(xd, fd);
				return( FALSE );
			}
			xd->xpru.xpru_updatemask = XPRU_BYTES;
			xd->xpru.xpru_bytes += n;
			(*xd->xpr_update)(&xd->xpru);
		}
	} while( n == xd->buffer_size );

	bfclose(xd, fd);

	if (n < 0)
	{	/* dead code?  Fread does not distinguish EOF and error */
		send_failure (xd, 'E');

		errormsg(xd, "** Read failure...aborting **");
		return(FALSE);
	}

/* Inform host that the file was sent */
	p = &xd->SA_Buf [xd->fill_SA];
	p->buf[0] = 'T';
	p->buf[1] = 'C';

	if (send_packet(xd, 2) == FALSE)
		return( FALSE );
	else
	{
		xd->xpru.xpru_updatemask = XPRU_MSG;
		xd->xpru.xpru_msg = "Waiting for host...";
		(*xd->xpr_update)(&xd->xpru);
		if (!SA_Flush(xd))
			return( FALSE );
		/* delete the file if requested */
		if (xd->optDelt == 'Y' && xd->xpr_unlink)
			(*xd->xpr_unlink)(name);
		return( TRUE );
	}
}

/*
 * do_transport_parameters is called when a Packet type of + is received.
 * It sends a packet of our local Quick B parameters and sets the Our_xx
 * parameters to the minimum of the sender's and our own parameters.
 */
static void do_transport_parameters(struct XPR_DATA *xd)
{
	register PACKET	*p;

	xd->His_WS = xd->r_buffer [1];     /* Pick out Sender's parameters */
	xd->His_WR = xd->r_buffer [2];
	xd->His_BS = xd->r_buffer [3];
	xd->His_CM = xd->r_buffer [4];

	p = &xd->SA_Buf [xd->fill_SA];
	p->buf [0] = '+';  /* Prepare to return our own parameters */
	p->buf [1] = DEF_WS;
	p->buf [2] = DEF_WR;
	p->buf [3] = DEF_BS;
	p->buf [4] = DEF_CM;
	p->buf [5] = DEF_DQ;

	if (!send_packet (xd, 5))
		return;

	if (SA_Flush(xd))                 /* Wait for host's ACK on our packet */
	{
/* Take minimal subset of Transport Params. */
/* If he can send ahead, we can receive it. */
		xd->Our_WR = min(xd->His_WS, DEF_WR);

/* If he can receive send ahead, we can send it. */
		xd->Our_WS = min(xd->His_WR, DEF_WS);

		xd->Our_BS = min(xd->His_BS, DEF_BS);
		xd->Our_CM = min(xd->His_CM, DEF_CM);

		if (xd->Our_BS == 0)
			xd->Our_BS = 4;    /* Default */

		xd->buffer_size = xd->Our_BS * 128;

		xd->Quick_B = TRUE;

		if (xd->Our_CM == 1)
			xd->Use_CRC = TRUE;

		if (xd->Our_WS != 0)
		{
			xd->SA_Enabled = TRUE;
			xd->SA_Max     = MAX_SA;
		}
	}
}

/*
  do_application_parameters is called when a ? packet is received.
  This version ignores the host's packet and returns a ? packet
  saying that normal B Protocol File Transfer is supported.
  (Well, actually it says that no extended application packets are
   supported.  The T packet is assumed to be standard.) */

static	void	do_application_parameters(struct XPR_DATA *xd)
{
	register PACKET	*p;

	p = &xd->SA_Buf [xd->fill_SA];
	p->buf[0] = '?';     /* Build the ? packet */
	p->buf[1] = 1;             /* The T packet flag  */

	if (send_packet (xd, 1))            /* Send the packet    */
		SA_Flush(xd);
}

/* Receive_File is called to receive a file from the host */
static	int	receive_file (register struct XPR_DATA *xd, char *name)
{
	long	fd;
	long	bytes;

	if (xd->optOwrt == 'N')
	{	/* avoid overwriting existing files */
		char *end = name + strlen(name);
		int dupno = 0;
		while ((fd = (*xd->xpr_fopen)(name, "r")) != 0)
		{
			(*xd->xpr_fclose)(fd);
			if (++dupno == 1)
			{
				strcpy(end, ".dup");
				end += 4;
			}
			else if (dupno < 100)
				stci_d(end, dupno);	/* ".dupN" suffix */
			else
				break;	/* give up, overwrite .dup99 */
		}
	}
	else if (xd->optOwrt == 'S' && (fd = (*xd->xpr_fopen)(name, "r")) != 0)
	{
		(*xd->xpr_fclose)(fd);
		errormsg(xd, "File already exists, skipping");
		send_failure(xd, 'E');
		return FALSE;
	}

	xd->xpru.xpru_updatemask = XPRU_FILENAME;
	xd->xpru.xpru_filename = name;
	(*xd->xpr_update)(&xd->xpru);

	fd = bfopen(xd, name, "w");
	xd->xpru.xpru_bytes = 0L;

	if (fd == 0)
	{
		errormsg(xd, "** Cannot open file...aborting **");
		send_failure(xd, 'E');
		return( FALSE );
	}

	send_ack(xd);

/* Process each incoming packet until 'TC' packet received or failure */

	while( TRUE )
	{
		if (read_packet (xd, FALSE, FALSE))
		{
			switch (xd->r_buffer[0]) {
			case 'N' :
				bytes = xd->r_size - 1;

				if (xbfwrite(xd, &xd->r_buffer[1], bytes, fd) != bytes )
				{
					errormsg(xd, "** Write failure...aborting **");
					send_failure (xd, 'E');
					goto failed;
				}
				send_ack(xd);
				xd->xpru.xpru_updatemask = XPRU_BYTES|XPRU_BLOCKSIZE|XPRU_BLOCKS;
				xd->xpru.xpru_bytes += bytes;
				xd->xpru.xpru_blocksize = bytes;
				++xd->xpru.xpru_blocks;
				(*xd->xpr_update)(&xd->xpru);
				break;

			case 'T' :
				if (xd->r_buffer[1] != 'C')
				{
					errormsg(xd, "** Invalid termination packet...aborting **");
					send_failure (xd, 'N');
					goto failed;
				}
				bfclose(xd, fd);

				send_ack(xd);
				return( TRUE );

			case 'F' :
				send_ack(xd);
				errormsg(xd, "** Failure packet received...aborting **");
				goto failed;
			}
		}
	 	else
		{
			errormsg(xd, "** Failed to receive packet...aborting **");
			goto failed;
		}
	}

failed: /* transfer failed, delete partial file if requested */
	bfclose(xd, fd);
	if (xd->optKeep == 'N' && xd->xpr_unlink)
		(*xd->xpr_unlink)(name);
	return( FALSE );
}

/*
 * bp_DLE is called from the main program when the character <DLE> is
 * received from the host.
 *
 * This routine calls read_packet and dispatches to the appropriate
 * handler for the incoming packet.
 */
void	bp_DLE(struct XPR_DATA *xd)
{
	int	xoff_flag;
	char	filename[300];
	long	oldserial;		/* old serial port settings */
	long	newserial;
	long	info;
/*
 * Begin by getting the next character.  If it is <B> then enter the
 * B_Protocol state.  Otherwise simply return.
 */

	if (xd->xio->xpr_setserial)
	{	/* set transparent mode 8-N-1 */
		oldserial = (*xd->xio->xpr_setserial)(-1L);
		if (oldserial != -1)
		{
			newserial = oldserial & 0xFFFFE0BC;
			if (newserial != oldserial)
				(*xd->xio->xpr_setserial)(newserial);
			else
				oldserial = -1L;
		}
	}
	else
		oldserial = -1L;

	if (cgetc (xd, 1000000L) != 'B')
		goto do_return;

	xd->ack_SA  = 0;    /* Initialize Send-ahead variables */
	xd->fill_SA = 0;
	xd->SA_Waiting = 0;
	xd->Aborting = FALSE;	/* not aborting ... yet */
	xd->Done = FALSE;
/*  <DLE><B> received; begin B Protocol */

	xoff_flag   = TRUE;

	xd->r_counter   = 0;
	xd->s_counter   = 0;

	memset(&xd->xpru, 0, sizeof(xd->xpru));

	xd->xpru.xpru_updatemask = XPRU_MSG;
	xd->xpru.xpru_msg = "Entering protocol";
	(*xd->xpr_update)(&xd->xpru);

	if (read_packet (xd, TRUE, FALSE))
	{
/* Dispatch on the type of packet just received */

	        switch (xd->r_buffer[0]) {
		case 'T':     /* File Transfer Application */
			xd->xpru.xpru_updatemask = XPRU_PROTOCOL|XPRU_BLOCKCHECK|XPRU_ERRORS|XPRU_TIMEOUTS;
			xd->xpru.xpru_protocol = "B protocol";
			xd->xpru.xpru_blockcheck = "Checksum";
			if (xd->Quick_B)
			{
				xd->xpru.xpru_protocol = filename;
				strcpy(filename, "Quick B");

				if (xd->Use_CRC)
					xd->xpru.xpru_blockcheck = "CRC-16";

				if (xd->Our_WS != 0) /* Allow send-ahead if other end agrees */
					strcat(filename, " Send-Ahead");
			}
			(*xd->xpr_update)(&xd->xpru);

			switch (xd->r_buffer[1]) {
			case 'D' :	/* downloading */
				break;
			case 'U' :	/* uploading */
				break;
			default :
				send_failure(xd, 'N');
				goto do_return;
			}

			switch (xd->r_buffer[2]) {
			case 'A':	/* ascii file */
				break;
			case 'B':	/* binary file */
				break;
			default :
				send_failure(xd, 'N');        /* not implemented */
				goto do_return;
			}

			/* get the file name */
			xd->r_buffer[xd->r_size] = '\0';
			strcpy(filename, &xd->r_buffer[3]);

			/* display file size for uploads */
			xd->xpru.xpru_updatemask = XPRU_MSG;

			/* determine text/binary status */
			xd->TextC = -1;
			if (xd->optText == 'N')
				xd->TextMode = FALSE;
			else if (xd->optText == 'Y')
				xd->TextMode = TRUE;
			else if (xd->optText == 'H')
				xd->TextMode = (xd->r_buffer[2] == 'A');
			else
			{	/* use comm program suggestion */
				info = (*xd->xpr_finfo)(filename, 2L);
				/* if the call failed, default to binary */
				xd->TextMode = (info == 2L);
			}
			/* tell the user what we decided */
			xd->xpru.xpru_msg = xd->r_buffer[1] == 'D'
				? (xd->TextMode ? "Receiving text..."
						: "Receiving binary...")
				: (xd->TextMode ? "Sending text..."
						: "Sending binary...");
			(*xd->xpr_update)(&xd->xpru);

			if (xd->r_buffer[1] == 'U')
			{
				if( send_file(xd, filename))
				{
					xd->xpru.xpru_updatemask = XPRU_MSG;
					xd->xpru.xpru_msg = "Transfer completed!";
					(*xd->xpr_update)(&xd->xpru);
				}
			}
			else
			{
				if( receive_file(xd, filename))
				{
					xd->xpru.xpru_updatemask = XPRU_MSG;
					xd->xpru.xpru_msg = "Transfer completed!";
					(*xd->xpr_update)(&xd->xpru);
				}
			}
			xd->Done = TRUE;
			break;

		case '+':          /* Received Transport Parameters Packet */
			do_transport_parameters(xd);
			break;

		case '?':          /* Received Application Parameters Packet */
			do_application_parameters(xd);
			break;

		default:	/* Unknown packet; tell host we don't know */
			send_failure (xd, 'N');
            		break;

		}  /* of case */
	}     /* of if read_packet the */

do_return:
	if (oldserial != -1)
		(*xd->xio->xpr_setserial)(oldserial);
}
