/* dlink - data link transfer routines for bmodem */

/*
 * by David Betz, BYTE Magazine/BIX
 * 
 * statements involving bm_infoinit(), bm_info() added by Willy Langeveld for
 * VLT
 * 
 * ANSIsized and made re-entrant by Marc Boucher for XPR implementation.
 * 
 * 91.08.13 [astp] Fixed pre-computed crc table, which I added 91.08.10 *sigh*
 */

#include <string.h>
#include <stdio.h>

#include "xprxmodem.h"

#include "proto-dlink.h"
#include "proto-xprxmodem.h"
#include "proto-callback.h"

#define WTYPE unsigned short

/* useful definitions */
#define TRUE    1
#define FALSE   0

/* protocol characters */
#define SOH     0x01		/* start of a 128 byte block */
#define STX     0x02		/* start of a 1024 byte block */
#define EOT     0x04		/* end of a complete file */
#define ACK     0x06		/* positive acknowledgement */
#define NAK     0x15		/* negative acknowledgement */
#define CAN     0x18		/* cancel transfer */
#define CRC     'C'		/* CRC request (instead of NAK to start a
				 * transfer) */

/* routine status codes */
#define DT_EOF  -1
#define DT_OK   1

/* number of times to retry */
#define RETRY   10

/* timeout loop counters */
#define STIME   4		/* timeout between characters of a packet */
#define LTIME   20		/* timeout waiting for an ACK/NAK */
#define XTIME   60		/* timeout waiting for initial NAK */

/* dlabort - wait for the line to clear */
static void dlabort(struct XPR_IO * IO)
{
	int res;

	do
		res = md_get(IO, STIME);
	while ((res != DT_TIME) && (res != DT_ERR));
}

/* chk_compute - compute the checksum */
static int chk_compute(unsigned char *buf, int len)
{
	int chk, i;

	for (chk = i = 0; i < len; ++i)
		chk += buf[i];
	return (chk & 0xFF);
}

#ifndef PRECOMPUTECRC
/* crc_compute - compute the CRC value */
static int crc_compute(unsigned char *buf, int len)
{
	int crc, shifter, highbit, i;

	buf[len++] = '\0';
	buf[len++] = '\0';
	for (crc = i = 0; i < len; ++i)
		for (shifter = 0x80; shifter; shifter >>= 1) {
			highbit = crc & 0x8000;
			crc <<= 1;
			crc |= (buf[i] & shifter ? 1 : 0);
			if (highbit)
				crc ^= 0x1021;
		}
	return (crc & 0xFFFF);
}
#else
/*
 * Pre-computed CRC polynomials (crctab) by Mark G. Mendel, 7/86
 * (Network Systems Corp.); Credit also due to Stephen Satchell
 * (Satchell Evaluations) for the improved updcrc (crc_compute)
 * function, and Chuck Forsberg (Omen Technology) who wrote RBSB.c
 * which Stephen extracted the original CRC table & functions.
 */
static WTYPE crctab[256] = /* as calculated by initcrctab() */ {
    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
} ;

static WTYPE crc_compute(unsigned char *buf, int len)
{
     register WTYPE crc = 0;
     register unsigned char *cp = buf;

	buf[len++] = '\0';
	buf[len++] = '\0';

     while( len-- ) {
          crc = crctab[((crc >> 8) & 255)] ^ (crc << 8) ^ *cp++;
     }

     return( crc );
}
#endif

static char *blkchk[] =
{"Checksum", "CRC-16"};
static char *timefmt = "%02ld:%02ld:%02ld";

static void bm_info(struct XPR_IO * IO, int error)
{
	long (*xupdate) (), (*xchkmisc) (void);
	struct XPR_UPDATE xpru;
	long secs, micros, elapsed;
	char buff1[20], buff2[20];
	int blksiz, Iblknum;

	blksiz=IO->xpr_data->msglength;
	Iblknum=IO->xpr_data->blknum;

	xchkmisc = IO->xpr_chkmisc;

	if (xchkmisc)
		xchkmisc();

	/*
	 * Calculate elapsed time in tenths of seconds
	 */
	CurrentTime(&secs, &micros);
	secs -= IO->xpr_data->startsecs;
	micros -= IO->xpr_data->startmics;
	elapsed = (secs * 10L) + (micros / 100000L);

	/*
	 * Always update data rate and elapsed time
	 */
	xpru.xpru_updatemask = XPRU_DATARATE | XPRU_ELAPSEDTIME;

	sprintf(buff1, timefmt, secs / 3600L, (secs / 60L) % 60L, secs % 60L);
	xpru.xpru_elapsedtime = buff1;

	if (elapsed)
		xpru.xpru_datarate = ((long) blksiz * Iblknum * 10L) / elapsed;
	else
		xpru.xpru_datarate = 0;

	/*
	 * If we know the file size and the data rate we can compute the
	 * estimated time.
	 */
	if (IO->xpr_data->filsiz) {
		if (xpru.xpru_datarate) {
			xpru.xpru_updatemask |= XPRU_EXPECTTIME;
			secs = IO->xpr_data->filsiz / xpru.xpru_datarate;
			sprintf(buff2, timefmt, secs / 3600L, (secs / 60L) % 60L, secs % 60L);
			xpru.xpru_expecttime = buff2;
		}
	}

	/*
	 * On error, timeout or otherwise, update different things
	 */
	if (error == DT_ERR) {
		IO->xpr_data->numerrs++;
		xpru.xpru_updatemask |= XPRU_ERRORS;
		xpru.xpru_errors = IO->xpr_data->numerrs;
	} else if (error == DT_TIME) {
		IO->xpr_data->numtime++;
		xpru.xpru_updatemask |= XPRU_TIMEOUTS;
		xpru.xpru_timeouts = IO->xpr_data->numtime;
	} else {
		xpru.xpru_updatemask |= XPRU_BLOCKS | XPRU_BLOCKSIZE |
			XPRU_BLOCKCHECK | XPRU_BYTES;
		xpru.xpru_blocks = (long) Iblknum;
		xpru.xpru_blocksize = (long) blksiz;
		xpru.xpru_bytes = (long) blksiz *(long) Iblknum;

		xpru.xpru_blockcheck = IO->xpr_data->crcmode ? blkchk[1] : blkchk[0];
	}

	/*
	 * Do the actual update
	 */
	if ((xupdate = IO->xpr_update) != NULL)
		calla(xupdate, &xpru);

	return;
}

/* mdsnd - send a buffer of data */
static int mdsnd(struct XPR_IO * IO)
{
	int plength, retries, ch;

	/* setup the packet header */
	IO->xpr_data->packet[0] = IO->xpr_data->msgstart;
	IO->xpr_data->packet[1] = IO->xpr_data->blknum;
	IO->xpr_data->packet[2] = ~IO->xpr_data->blknum;

	/* compute the block check code */
	if (IO->xpr_data->crcmode) {	/* compute the CRC */
		long dumb_index;/* workaround manx expression too complex bug */

		IO->xpr_data->chksum = (int)crc_compute(IO->xpr_data->buffer, IO->xpr_data->msglength);
		IO->xpr_data->buffer[IO->xpr_data->msglength] = IO->xpr_data->chksum >> 8;
		dumb_index = IO->xpr_data->msglength + 1;
		IO->xpr_data->buffer[dumb_index] = IO->xpr_data->chksum;
		plength = IO->xpr_data->msglength + 5;
	} else {		/* compute the checksum */
		long dumb_index;/* workaround manx expression too complex bug */

		IO->xpr_data->chksum = chk_compute(IO->xpr_data->buffer, IO->xpr_data->msglength);
		dumb_index = IO->xpr_data->msglength;
		IO->xpr_data->buffer[dumb_index] = IO->xpr_data->chksum;
		plength = IO->xpr_data->msglength + 4;
	}

	/* send data and wait for an ACK */
	for (retries = 0; retries < RETRY; retries++) {

		/* send the data */
		md_write(IO, (char *)IO->xpr_data->packet, plength);

		/* return on an ACK */
		if ((ch = md_get(IO, LTIME)) == ACK)
			return (DT_OK);

		/* abort transfer on two successive CAN's */
		else if (ch == CAN) {
			if ((ch = md_get(IO, STIME)) == ACK)
				return (DT_OK);
			else if (ch == CAN)
				break;
		} else if (ch == DT_ERR) {
			dlabort(IO);
			md_put(IO, CAN);
			md_put(IO, CAN);
			return (DT_ERR);
		}
		bm_info(IO, ch);
	}

	/* return failure */
	return (DT_ERR);
}

/* msgput - put a message data character */
static int msgput(struct XPR_IO * IO, int ch)
{
	int sts;

	IO->xpr_data->buffer[IO->xpr_data->bufptr++] = ch;
	if (IO->xpr_data->bufptr == IO->xpr_data->msglength) {
		bm_info(IO, 0);
		if ((sts = mdsnd(IO)) != DT_OK)
			return (sts);
		++IO->xpr_data->blknum;
		IO->xpr_data->bufptr = 0;
	}
	return (ch);
}

/* mdrcv - receive a buffer of data */
static int mdrcv(struct XPR_IO * IO)
{
	int plength, i, ch, retries;

	/* receive data */
	for (retries = 0; retries < RETRY + 1; retries++) {

		/* check for data packet or eot */
		if ((ch = md_get(IO, LTIME)) == DT_TIME) {
			bm_info(IO, ch);
			md_put(IO, IO->xpr_data->nak);
			continue;
		} else if (ch == DT_ERR) {
			bm_info(IO, ch);
			dlabort(IO);
			md_put(IO, CAN);
			md_put(IO, CAN);
			return (DT_ERR);
		} else if (ch == EOT) {	/* end of transfer */
			md_put(IO, ACK);
			return (DT_EOF);
		} else if (ch == SOH)	/* start of a short packet */
			IO->xpr_data->msglength = SMSGLEN;
		else if (ch == STX)	/* start of a long packet */
			IO->xpr_data->msglength = LMSGLEN;
		else {
			bm_info(IO, DT_ERR);
			dlabort(IO);
			md_put(IO, IO->xpr_data->nak);
			continue;
		}

		/* reset the NAK character */
		IO->xpr_data->nak = NAK;

		/* compute the packet length */
		plength = IO->xpr_data->msglength + (IO->xpr_data->crcmode ? 5 : 4);

		/* receive the data */
		for (i = 1; i < plength; IO->xpr_data->packet[i++] = ch) {
			if ((ch = md_get(IO, STIME)) == DT_TIME)
				break;
			else if (ch == DT_ERR)
				break;
		}

		/* check for timeout */
		if (ch == DT_TIME) {
			bm_info(IO, ch);
			md_put(IO, NAK);
			continue;
		}
		if (ch == DT_ERR) {
			bm_info(IO, ch);
			dlabort(IO);
			md_put(IO, CAN);
			md_put(IO, CAN);
			return (DT_ERR);
		}
		/* check the block number */
		if (IO->xpr_data->packet[1] != (~IO->xpr_data->packet[2] & 0xFF)) {
			bm_info(IO, DT_ERR);
			md_put(IO, NAK);
			continue;
		}
		/* check the block check code */
		if (IO->xpr_data->crcmode) {	/* CRC */
			IO->xpr_data->chksum = (IO->xpr_data->buffer[IO->xpr_data->msglength] << 8) | IO->xpr_data->buffer[IO->xpr_data->msglength + 1];
			if (IO->xpr_data->chksum != (int)crc_compute(IO->xpr_data->buffer, IO->xpr_data->msglength)) {
				bm_info(IO, DT_ERR);
				md_put(IO, NAK);
				continue;
			}
		} else {	/* checksum */
			IO->xpr_data->chksum = IO->xpr_data->buffer[IO->xpr_data->msglength];
			if (IO->xpr_data->chksum != chk_compute(IO->xpr_data->buffer, IO->xpr_data->msglength)) {
				bm_info(IO, DT_ERR);
				md_put(IO, NAK);
				continue;
			}
		}

		/* check the block number */
		if (IO->xpr_data->packet[1] == (IO->xpr_data->blknum & 0xFF)) {
			md_put(IO, ACK);
			return (DT_OK);
		} else if (IO->xpr_data->packet[1] != ((IO->xpr_data->blknum - 1) & 0xFF)) {
			bm_info(IO, DT_ERR);
			dlabort(IO);
			md_put(IO, CAN);
			md_put(IO, CAN);
			return (DT_ERR);
		}
		/* send a ack */
		md_put(IO, ACK);
	}

	/* return failure */
	return (DT_ERR);
}

/* msgget - get a message data character */
static int msgget(struct XPR_IO * IO)
{
	int sts;

	if (IO->xpr_data->bufptr == IO->xpr_data->msglength) {
		if ((sts = mdrcv(IO)) != DT_OK)
			return (sts);
		bm_info(IO, 0);
		++IO->xpr_data->blknum;
		IO->xpr_data->bufptr = 0;
	}
	return (IO->xpr_data->buffer[IO->xpr_data->bufptr++]);
}

/* dl_snd - send data across the link */
int dl_snd(struct XPR_IO * IO, int (*getch) (struct XPR_IO * IO))
{
	int ch, retries;

	IO->xpr_data->abort = 0;

	/* setup message length */
	if (IO->xpr_data->big) {
		IO->xpr_data->msgstart = STX;
		IO->xpr_data->msglength = LMSGLEN;
	} else {
		IO->xpr_data->msgstart = SOH;
		IO->xpr_data->msglength = SMSGLEN;
	}

	/* initialize */
	IO->xpr_data->blknum = 1;	/* start a block number 1 */
	IO->xpr_data->bufptr = 0;	/* start with an empty buffer */

	/* wait for the initial NAK (or CRC) */
	for (retries = 0; retries < RETRY; retries++)
		if ((ch = md_get(IO, XTIME)) == NAK) {	/* start of checksum
							 * transfer */
			IO->xpr_data->crcmode = FALSE;
			break;
		} else if (IO->xpr_data->crc_conf && ch == CRC) {	/* start of CRC transfer */
			IO->xpr_data->crcmode = TRUE;
			break;
		} else if (ch == DT_ERR) {
			bm_info(IO, DT_ERR);
			dlabort(IO);
			return (FALSE);
		} else if (ch == DT_TIME) {
			bm_info(IO, DT_TIME);
			dlabort(IO);
			return (FALSE);
		} else
			dlabort(IO);

	/* check for failure */
	if (retries >= RETRY)
		return (FALSE);

	/* send each byte */
	while ((ch = (*getch) (IO)) != EOF)
		if (msgput(IO, ch) == DT_ERR)
			return (FALSE);

	/* flush partial buffer */
	if (IO->xpr_data->bufptr > 0)
		while (IO->xpr_data->bufptr > 0)
			if (msgput(IO, 0) == DT_ERR)
				return (FALSE);

	/* send EOT and wait for ACK */
	for (retries = 0; retries < RETRY; retries++) {
		md_put(IO, EOT);
		if (md_get(IO, LTIME) == ACK)
			return (TRUE);
	}

	/* return failure */
	return (FALSE);
}

/* dl_rcv - receive data across the link */
int dl_rcv(struct XPR_IO * IO, void (*putch) (struct XPR_IO * IO, int ch))
{
	int ch;

	/* initialize */
	IO->xpr_data->abort = 0;
	IO->xpr_data->blknum = 1;
	IO->xpr_data->bufptr = IO->xpr_data->msglength = SMSGLEN;

	/* send the initial NAK (or CRC) */
	IO->xpr_data->nak = (IO->xpr_data->crc_conf ? CRC : NAK);
	IO->xpr_data->crcmode = IO->xpr_data->crc_conf;
	md_put(IO, IO->xpr_data->nak);

	/* receive each byte */
	while ((ch = msgget(IO)) != DT_EOF && ch != DT_ERR)
		(*putch) (IO, ch);

	/* return with status */
	return (ch == DT_EOF);
}

void bm_infoinit(struct XPR_IO * IO, int send, long size)
{
	long (*xupdate) ();
	struct XPR_UPDATE xpru;
	char buff[20];

	IO->xpr_data->numerrs = 0L;
	IO->xpr_data->numtime = 0L;

	if (send)
		strcpy(buff, "Send    ");
	else
		strcpy(buff, "Receive ");
	if (IO->xpr_data->ascii)
		strcat(buff, "Text  ");
	else
		strcat(buff, "Binary");

	xpru.xpru_updatemask = XPRU_MSG | XPRU_FILENAME |
		XPRU_BLOCKSIZE | XPRU_BLOCKCHECK | XPRU_BYTES |
		XPRU_BLOCKS | XPRU_TIMEOUTS | XPRU_ERRORS;
	IO->xpr_data->filsiz = size;
	if (size)
		xpru.xpru_updatemask |= XPRU_FILESIZE;

	xpru.xpru_filename = IO->xpr_filename;
	xpru.xpru_filesize = size;
	xpru.xpru_msg = buff;
	xpru.xpru_blocks = 0L;
	xpru.xpru_errors = 0L;
	xpru.xpru_timeouts = 0L;
	xpru.xpru_blocksize = IO->xpr_data->big ? 1024L : 128L;
	xpru.xpru_blockcheck = IO->xpr_data->crc_conf ? blkchk[1] : blkchk[0];
	xpru.xpru_bytes = 0L;

	if ((xupdate = IO->xpr_update) != NULL)
		calla(xupdate, &xpru);

	CurrentTime(&IO->xpr_data->startsecs, &IO->xpr_data->startmics);

	return;
}
