//..............................................................................
//
// UDP packet decoder
//

import "doc_PluginHost.jnc"
import "io_IpDecoder.jnc"

//..............................................................................

class UdpDecoder: io.IpDecoder
{
protected:
	log.Writer*	m_logWriter;

public:
	io.SocketAddress m_filterAddress; // freely adjustible

public:
	construct(doc.PluginHost* pluginHost)
	{
		m_logWriter = pluginHost.m_log.m_writer;
	}

protected:
	override bool decodeTransportHdr(
		io.SocketAddress* srcAddress,
		io.SocketAddress* dstAddress,
		io.IpProtocol protocol,
		void const* p,
		size_t size
		);
}

// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

bool UdpDecoder.decodeTransportHdr(
	io.SocketAddress* srcAddress,
	io.SocketAddress* dstAddress,
	io.IpProtocol protocol,
	void const* p,
	size_t size
	)
{
	if (protocol != io.IpProtocol.Udp || size < sizeof(io.UdpHdr))
		return false;

	io.UdpHdr const* udpHdr = (io.UdpHdr const*) p;
	if (udpHdr.m_length < sizeof(io.UdpHdr) || udpHdr.m_length > size)
		return false;

	srcAddress.m_port = udpHdr.m_srcPort;
	dstAddress.m_port = udpHdr.m_dstPort;

	if (m_filterAddress.m_family &&
		!srcAddress.isMatch(m_filterAddress) &&
		!dstAddress.isMatch(m_filterAddress))
		return false;

	p += sizeof(io.UdpHdr);
	size = udpHdr.m_length - sizeof(io.UdpHdr);

	UdpFlowMonPacketParams params;
	params.m_srcAddress = *srcAddress;
	params.m_dstAddress = *dstAddress;
	params.m_size = size;

	m_logWriter.write(UdpFlowMonLogRecordCode.Packet, &params, sizeof(params));
	m_logWriter.write(log.StdRecordCode.Rx, p, size);
	return true;
}

//..............................................................................
