/*
This program is distributed under the terms of the 'MIT license'. The text
of this licence follows...

Copyright (c) 2006 J.D.Medhurst (a.k.a. Tixy)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

/**
@file

@brief Implementation of Y-Modem receive protocol.
*/

#include "../common/common.h"
#include "ymodem_rx.h"


#include <string.h> // for memcpy and memset


/**
Minimum time in milli-seconds to wait for data from receiver.
*/
const unsigned ReceiveTimeout = 1*1000;


YModemRx::YModemRx(SerialPort& port)
	: YModem(port)
	{
	}


/**
Transmit a single character.

@param c The character.

@return One if successful, or a negative error value if failed.
*/
int YModemRx::OutChar(uint8_t c)
	{
	int result = Port.Out(&c,1,1000);
	if(result==0)
		return ErrorTimeout;
	return result;
	}


/**
Receive a block of data.
If #ExpectCRC is true, possible formats of blocks are:
- 128 byte block with CRC - SOH, blk-num, ~blk-num, data[128], CRC-hi, CRC-lo
- 1k byte block with CRC - STX, blk-num, ~blk-num, data[1024], CRC-hi, CRC-lo

If #ExpectCRC is false, possible formats of blocks are:
- 128 byte block with checksum - SOH, blk-num, ~blk-num, data[128], chsum
- 1k byte block with checksum - STX, blk-num, ~blk-num, data[1024], chsum

@param out		The stream of data write received data to.

@return The number of data bytes in the received block,
        zero if transfer ended, or a negative error value if failed.
*/
int YModemRx::ReceiveBlock(OutStream& out)
	{
	uint8_t block[1+2+1024+2];	// buffer to hold data for the block

	int retryCount = 10;		// number of attempts to send the block
do_retry:
	// count attenpts...
	if(!retryCount--)
		return ErrorBlockRetriesExceded;

	size_t blockSize = 128;		// assume 128 byte blocks until we know better
	uint8_t* data = block;
	size_t size = 1+2+blockSize+1+ExpectCRC;
	do
		{
		// receive some data...
		int result = Port.In(data,size,ReceiveTimeout);
		if(result<0)
			return result;

		// check for timeout...
		if(result==0)
			{
			if(data==block)
				return ErrorTimeout; // nothing received
			// not all data received so some may have been lost...
			goto retry;
			}

		// check for end of transmission...
		if(block[0]==EOT)
			{
			int result = OutChar(ACK);
			if(result<0)
				return result;
			return out.Out(0,0); // store zero bytes to signal end
			}

		// check for 1K blocks...
		if(block[0]==STX && blockSize!=1024)
			{
			blockSize = 1024;
			size += 1024-128;
			}

		// adjust pointers for next chunk of data...
		data += result;
		size -= result;
		}
	while(size);

	if(block[0] != (blockSize==1024 ? STX : SOH))
		goto retry; // block start invalid
	if(block[1] != (block[2]^0xff))
		goto retry; // block number invalid
	if(block[1] != (BlockNumber&0xffu))
		goto retry; // block number invalid

	if(ExpectCRC)
		{
		uint16_t crc = CRC16(block+1+2,blockSize);
		uint16_t receiveCrc = (block[1+2+blockSize+0]<<8)+block[1+2+blockSize+1];
		if(crc!=receiveCrc)
			goto retry; // crc invalid
		}
	else
		{
		uint8_t sum = Checksum(block+1+2,blockSize);
		if(sum!=block[1+2+blockSize])
			goto retry; // checksum invalid
		}

	{
	//  output received data...
	int result = out.Out(block+3,blockSize);
	if(result<0)
		return result;

	// block transferred OK...
	if(SendBlockACK)
		{
		result = OutChar(ACK);
		if(result<0)
			return result;
		}
	++BlockNumber;
	return blockSize;
	}

retry:
	while(InChar(ReceiveTimeout)>=0) // flush input buffers
		{}
	int result = OutChar(NAKChar);
	if(result<0)
		return result;
	goto do_retry;
	}


/**
Receive first block of data.

@param out		The stream of data write received data to.
@param timeout	Time in milliseconds to wait sender to become ready.

@return Zero if transfer was successful, or a negative error value if failed.
*/
int YModemRx::ReceiveInitialise(OutStream& out, unsigned timeout)
	{
	for(;;)
		{
		int result = OutChar(ModeChar);
		if(result!=ErrorTimeout)
			{
			if(result<0)
				return result;
			result = ReceiveBlock(out);
			if(result!=ErrorTimeout)
				return result;
			}
		if(timeout<ReceiveTimeout)
			return ErrorTimeout;
		timeout -= ReceiveTimeout;
		}
	}


int YModemRx::ReceiveX(OutStream& out, unsigned timeout, bool useCrc)
	{
	ModeChar = useCrc ? (uint8_t)'C' : (uint8_t)NAK;
	ExpectCRC = useCrc;
	SendBlockACK = true;
	NAKChar = ModeChar;

	// get first block...
	BlockNumber = 1;
	int result = ReceiveInitialise(out,timeout);
	if(result==ErrorTimeout)
		return result;

	// get rest of data...
	while(result)
		{
		if(result<0)
			goto error;
		result = ReceiveBlock(out);
		}

	// done...
	return 0;

error:
	Cancel();
	return result;
	}


/**
Construct with no data.
*/
inline YModemRx::OutBlock0::OutBlock0()
	: Size(0)
	{}


int YModemRx::OutBlock0::Open(const char* /*fileName*/, size_t /*size*/)
	{
	return ErrorOutputStreamError;
	}


/**
Receive data for block zero.

@param data		Pointer to data.
@param size		Size of data.

@return Zero.
*/
int YModemRx::OutBlock0::Out(const uint8_t* data, size_t size)
	{
	memcpy(Buffer,data,size);
	Size = size;
	return 0;
	}


/**
Parse received data.

@param[out] fileName	Name of file.
@param[out] fileSize	Size of file being received.

@return Zero if successful, or a negative error value if failed.
*/
int YModemRx::OutBlock0::Parse(const char*& fileName, size_t& fileSize)
	{
	const char* buffer = (char*)Buffer;
	size_t bufferSize = Size;

	// fileName is at start of block...
	fileName = (char*)buffer;
	const char* bufferEnd = buffer+bufferSize;
	while(*buffer++)
		{
		if(buffer>=bufferEnd)
			return YModemRx::ErrorReceivedBadData;
		}

	// size (as decimal number) follows name string...
	size_t size = 0;
	while(buffer<bufferEnd)
		{
		unsigned digit = *buffer++;
		if(!digit)
			break;
		if(digit==' ')
			break;
		digit -= '0';
		if(digit>9)
			return YModemRx::ErrorReceivedBadData;
		size_t oldSize = size;
		size = size*10+digit;
		if(size<oldSize)
			return YModemRx::ErrorReceivedBadData; // overflow
		}
	fileSize = size;

	// done...
	return 0;
	}


int YModemRx::ReceiveY(OutStream& out, unsigned timeout, bool gMode)
	{
	ModeChar = gMode ? 'G' : 'C';
	ExpectCRC = true;
	SendBlockACK = !gMode;
	NAKChar = ModeChar;
	unsigned fileCount = 0;
	int result;

	for(;;)
		{
		// get block zero...
		YModemRx::OutBlock0 block0;
		BlockNumber = 0;
		result = ReceiveInitialise(block0,timeout);
		if(result==ErrorTimeout && !fileCount)
			return result; // sender not ready
		if(result<0)
			goto error;
		if(result!=128)
			return 0;

		// process block zero...
		const char* fileName;
		size_t size;
		result = block0.Parse(fileName,size);
		if(result<0)
			goto error;
		if(fileName[0]==0)
			return 0; // empty file name indicates end of transfer
		if(fileCount)
			return ErrorMultipleFilesSent; // we only support single file transfers
		result = out.Open(fileName,size);
		if(result<0)
			goto error;

		// get rest of data...
		NAKChar = NAK;
		result = OutChar(ModeChar);
		while(result)
			{
			if(result<0)
				goto error;
			result = ReceiveBlock(out);
			}

		// file received OK.
		++fileCount;
		}
error:
	Cancel();
	return result;
	}
