//..............................................................................
//
// Sniffer session
//

import "io_base.jncx"
import "io_pcap.jncx"
import "io_IpDefragmenter.jnc"
import "io_PcapDeviceUi.jnc"
import "io_BufferUi.jnc"
import "std_Buffer.jnc"
import "doc_Plugin.jnc"
import "gui_Dialog.jnc"
import "gui_History.jnc"
import "gui_StdSessionInfo.jnc"
import "log_ThroughputCalc.jnc"
import "log_ChecksumCalc.jnc"

using extension gui.ComboBoxHistory;

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

class SnifferSession: doc.Session
{
protected:
	enum Defaults
	{
		Promiscious  = false,
		SnapshotSize = 8 * 1024,
		ReadTimeout  = 200,
	}

	enum State
	{
		Closed,
		Capturing,
	}

	enum ActionId
	{
		Capture,
		_Count,
	}

	enum IconId
	{
		Capture,
		StopCapture,
		_Count,
	}

	enum StatusPaneId
	{
		State,
		_Count,
	}

protected:
	// pcap

	State bindable m_state;
	io.Pcap m_pcap;
	io.IpDefragmenter m_ipDefragmenter;
	std.Buffer m_readBuffer;
	uint_t m_syncId;

	// toolbar, status bar & menu

	gui.Action* m_actionTable [ActionId._Count];
	gui.Icon* m_iconTable [IconId._Count];
	gui.StatusPane* m_statusPaneTable [StatusPaneId._Count];
	gui.ComboBox* m_deviceCombo;
	gui.ComboBox* m_filterCombo;
	gui.FileDlg* m_fileDlg;

	// property grid

	gui.EnumProperty* m_deviceProp;
	gui.BoolProperty* m_promisciousProp;
	gui.StringProperty* m_filterProp;
	gui.IntProperty* m_ipFragmentLimitProp;
	gui.IntProperty* m_ipFragmentTimeoutProp;
	gui.IntProperty* m_snapshotSizeProp;
	io.BufferPropertySet m_bufferPropertySet;

	// information grid

	gui.StdSessionInfoSet m_stdSessionInfoSet;
	log.ThroughputInfoSet m_throughputInfoSet;
	log.ChecksumInfoSet m_checksumInfoSet;

public:
	construct (doc.PluginHost* pluginHost);

	bool errorcode capture ();

	bool errorcode capture (
		io.PcapDeviceDesc const* device,
		char const* filterString
		);

	bool errorcode openCapFile (
		char const* fileName,
		char const* filterString
		);

	stopCapture ();

	override void load (doc.Storage* storage);
	override void save (doc.Storage* storage);
	override void updateProperties ();
	override bool errorcode applyProperties ();
	override void restoreDefaultProperties ();

	override size_t errorcode transmit (
		void const* p,
		size_t size
		);

protected:
	onCapture ()
	{
		try (m_state ? stopCapture () : capture ());
	}

	onSetFilter ()
	{
		try (m_state ? applyFilter () : capture ());
	}

	onDeviceComboEnter ()
	{
		try capture ();
	}

	onFileDlgCompleted (gui.StdDlgButton button);

	onPcapEvent (
		uint_t syncId,
		io.PcapEvents triggeredEvents
		);

	bool errorcode applyFilter ();

	processPacket (
		void const* p,
		size_t size
		);

	waitPcapEvents ();
	createUi ();

	reactor m_uiReactor ();
}

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

SnifferSession.construct (doc.PluginHost* pluginHost)
{
	basetype.construct (pluginHost);

	createUi ();

	pluginHost.m_log.attachRepresenter (representSnifferLog);
	pluginHost.m_log.registerSelectionProcessor (log.ThroughputCalcRangeProcessor.factory ~(m_throughputInfoSet));
	pluginHost.m_log.registerSelectionProcessor (log.ChecksumCalcRangeProcessor.factory ~(m_checksumInfoSet));
}

SnifferSession.createUi ()
{
	// toolbar

	m_pluginHost.m_toolBar.addLabel ("Device:");
	m_deviceCombo = io.createPcapDeviceComboBox (m_pluginHost.m_toolBar);
	m_deviceCombo.m_onEnter += onDeviceComboEnter;

	m_pluginHost.m_toolBar.addLabel ("Filter:");
	m_filterCombo = m_pluginHost.m_toolBar.addComboBox (-1);
	m_filterCombo.m_isEditable = true;
	m_filterCombo.m_onEnter += onSetFilter;

	m_iconTable [IconId.Capture] = new gui.Icon ("images/capture.png");
	m_iconTable [IconId.StopCapture] = new gui.Icon ("images/pause.png");

	m_actionTable [ActionId.Capture] = createAction ("Capture", m_iconTable [IconId.Capture]);
	m_actionTable [ActionId.Capture].m_onTriggered += onCapture;

	// status bar

	m_statusPaneTable [StatusPaneId.State] = m_pluginHost.m_statusBar.addPane (, 80);

	// property grid

	gui.GroupProperty* group = m_pluginHost.m_propertyGrid.createGroupProperty (
		"Connection",
		"Pcap-specific connection settings"
		);

	m_deviceProp = io.createPcapDeviceProperty (
		m_pluginHost.m_propertyGrid,
		group,,,
		"Device",
		"Specify the device to capture on"
		);

	m_promisciousProp = m_pluginHost.m_propertyGrid.createBoolProperty (
		group,,
		"Promiscious mode",
		"Put the capturing interface into promiscious mode"
		);

	m_filterProp = m_pluginHost.m_propertyGrid.createStringProperty (
		group,,
		"Capture filter",
		"Capture only the packets which have passed this primary filter"
		);

	group = m_pluginHost.m_propertyGrid.createGroupProperty (
		"IP defragmenter",
		"IP defragmentation settings"
		);

	m_ipFragmentLimitProp  = m_pluginHost.m_propertyGrid.createIntProperty (
		group,,
		"IP fragment limit",
		"Specify the maximum number of IP fragments"
		);

	m_ipFragmentTimeoutProp  = m_pluginHost.m_propertyGrid.createIntProperty (
		group,,
		"IP fragment timeout (ms)",
		"Specify the maximum delay between IP fragments"
		);

	group = m_pluginHost.m_propertyGrid.createGroupProperty (
		"Buffering",
		"Advanced buffering options affecting throughtput and compatibility"
		);

	m_snapshotSizeProp = m_pluginHost.m_propertyGrid.createIntProperty (
		group,,
		"Snapshot size",
		"Specify the Pcap snapshot size"
		);

	m_snapshotSizeProp.m_spinBoxStep = 1024;

	m_bufferPropertySet.createProperties (
		m_pluginHost.m_propertyGrid,
		group,,
		io.BufferPropertySet.PropertyId.ReadBufferSize |
		io.BufferPropertySet.PropertyId.WriteBufferSize |
		io.BufferPropertySet.PropertyId.NotifyReadBufferFull
		);

	// information grid

	gui.InformationGroup* infoGroup = m_pluginHost.m_informationGrid.createGroup ("Network sniffer");

	m_stdSessionInfoSet.createInformationValues (
		m_pluginHost.m_informationGrid,
		infoGroup,,
		gui.StdSessionInfoSet.InfoId.SessionTime |
		gui.StdSessionInfoSet.InfoId.TotalSize
		);

	m_throughputInfoSet.createInformationValuesGrouped (
		m_pluginHost.m_informationGrid,,,
		log.ThroughputInfoSet.InfoId.TimeSpan |
		log.ThroughputInfoSet.InfoId.TotalSize |
		log.ThroughputInfoSet.InfoId.TotalThroughput
		);

	m_checksumInfoSet.createInformationValuesGrouped (m_pluginHost.m_informationGrid);

	m_pluginHost.m_informationGrid.resizeNameColumnToContents ();

	m_uiReactor.start ();
}

SnifferSession.onFileDlgCompleted (gui.StdDlgButton button)
{
	if (button != gui.StdDlgButton.Ok)
		return;

	char const* fileName = m_fileDlg.m_filePath;
	char const* filterString = m_filterCombo.m_editText;
	m_filterCombo.addEditTextToHistory ();

	try openCapFile (fileName, filterString);
}

bool errorcode SnifferSession.capture ()
{
	stopCapture ();

	if (m_deviceCombo.m_currentIndex == -1)
		return false;

	io.PcapDeviceDesc const* device = m_deviceCombo.m_currentData;
	if (!device)
	{
		if (!m_fileDlg)
		{
			m_fileDlg = new gui.FileDlg;
			m_fileDlg.m_onCompleted += onFileDlgCompleted;
		}

		m_fileDlg.m_kind = gui.FileDlgKind.Open;
		m_fileDlg.m_title = "Open Wireshark File (*.cap; *.pcap)...";
		m_fileDlg.m_filter = "Wireshark .cap files (*.cap; *.pcap);; All files (*.*)";
		m_fileDlg.show ();
		return true;
	}

	char const* filterString = m_filterCombo.m_editText;
	m_filterCombo.addEditTextToHistory ();

	return try capture (device, filterString);
}

bool errorcode SnifferSession.capture (
	io.PcapDeviceDesc const* device,
	char const* filterString
	)
{
	stopCapture ();
	startSession ();

	writeLogString (SnifferLogRecordCode.StartingCapture, filterString);

	m_pcap.m_readBufferSize = m_bufferPropertySet.m_readBufferSizeProp.m_value;
	m_pcap.m_writeBufferSize = m_bufferPropertySet.m_writeBufferSizeProp.m_value;

	bool result = try m_pcap.openDevice (
		device.m_name,
		filterString,
		m_snapshotSizeProp.m_value,
		m_promisciousProp.m_value,
		Defaults.ReadTimeout
		);

	if (!result)
	{
		writeLogLastError (SnifferLogRecordCode.CaptureError);
		return false;
	}

	m_state = State.Capturing;
	writeLog (SnifferLogRecordCode.CaptureStarted);
	waitPcapEvents ();
	m_stdSessionInfoSet.startSession (m_pluginHost.m_mainThreadScheduler);
	return true;
}

bool errorcode SnifferSession.openCapFile (
	char const* fileName,
	char const* filterString
	)
{
	writeLogString (SnifferLogRecordCode.StartingCapture, filterString);

	m_pcap.m_readBufferSize = m_bufferPropertySet.m_readBufferSizeProp.m_value;

	bool result = try m_pcap.openFile (
		fileName,
		filterString
		);

	if (!result)
	{
		writeLogLastError (SnifferLogRecordCode.CaptureError);
		return false;
	}

	m_state = State.Capturing;
	writeLog (SnifferLogRecordCode.CaptureStarted);
	waitPcapEvents ();
	m_stdSessionInfoSet.startSession (m_pluginHost.m_mainThreadScheduler);
	return true;
}

SnifferSession.stopCapture ()
{
	if (!m_state)
		return;

	writeLog (SnifferLogRecordCode.CaptureStopped);
	m_pcap.close ();
	m_state = State.Closed;
	m_syncId++;
	m_stdSessionInfoSet.endSession ();
}

bool errorcode SnifferSession.applyFilter ()
{
	char const* filter = m_filterCombo.m_editText;
	m_filterCombo.addEditTextToHistory ();

	if (!m_state.Capturing)
		return true;

	writeLogString (SnifferLogRecordCode.ChangingFilter, filter);
	bool result = try m_pcap.setFilter (filter);
	if (!result)
	{
		writeLogLastError (SnifferLogRecordCode.FilterError);
		return false;
	}

	writeLog (SnifferLogRecordCode.FilterChanged);
	return true;
}

SnifferSession.waitPcapEvents ()
{
	io.PcapEvents eventMask =
		io.PcapEvents.IoError |
		io.PcapEvents.ReadBufferFull |
		io.PcapEvents.IncomingData |
		io.PcapEvents.Eof;

	if (!m_isTransmitEnabled)
		eventMask |= io.PcapEvents.WriteBufferReady;

	m_pcap.wait (eventMask, onPcapEvent ~(++m_syncId) @ m_pluginHost.m_mainThreadScheduler);
}

void SnifferSession.load (doc.Storage* storage)
{
	m_filterCombo.loadHistory (storage, "captureFilterHistory");
	m_deviceCombo.m_currentIndex = storage.readInt ("deviceIdx");
	m_filterCombo.m_editText = storage.readString ("captureFilter");
	m_promisciousProp.m_value = storage.readBool ("promiscious", Defaults.Promiscious);
	m_ipFragmentLimitProp.m_value = storage.readInt ("ipFragmentLimit", io.IpDefragmenter.DefIpFragmentLimit);
	m_ipFragmentTimeoutProp.m_value = storage.readInt ("ipFragmentTimeout", io.IpDefragmenter.DefIpFragmentTimeout);
	m_snapshotSizeProp.m_value = storage.readInt ("snapshotSize", Defaults.SnapshotSize);

	m_bufferPropertySet.load (storage);
	m_readBuffer.setSize (m_bufferPropertySet.m_readBufferSizeProp.m_value);
}

void SnifferSession.save (doc.Storage* storage)
{
	m_bufferPropertySet.save (storage);
	m_filterCombo.saveHistory (storage, "captureFilterHistory");
	storage.writeInt ("deviceIdx", (int) m_deviceCombo.m_currentIndex);
	storage.writeString ("captureFilter", m_filterCombo.m_editText);
	storage.writeBool ("promiscious", m_promisciousProp.m_value);
	storage.writeInt ("ipFragmentLimit", m_ipFragmentLimitProp.m_value);
	storage.writeInt ("ipFragmentTimeout", m_ipFragmentTimeoutProp.m_value);
	storage.writeInt ("snapshotSize", m_snapshotSizeProp.m_value);
}

void SnifferSession.updateProperties ()
{
	m_deviceProp.m_currentIndex = m_deviceCombo.m_currentIndex;
	m_filterProp.m_value = m_filterCombo.m_editText;
}

bool errorcode SnifferSession.applyProperties ()
{
	m_deviceCombo.m_currentIndex = m_deviceProp.m_currentIndex;
	m_filterCombo.m_editText = m_filterProp.m_value;
	m_ipDefragmenter.m_fragmentLimit = m_ipFragmentLimitProp.m_value;
	m_ipDefragmenter.m_timeout = m_ipFragmentTimeoutProp.m_value;
	m_readBuffer.setSize (m_bufferPropertySet.m_readBufferSizeProp.m_value);

	if (!m_pcap.m_isOpen)
		return true;

	m_pcap.m_readBufferSize = m_bufferPropertySet.m_readBufferSizeProp.m_value;
	m_pcap.m_writeBufferSize = m_bufferPropertySet.m_writeBufferSizeProp.m_value;
	applyFilter ();
	return true;
}

void SnifferSession.restoreDefaultProperties ()
{
	m_deviceProp.m_currentIndex = 0;
	m_promisciousProp.m_value = Defaults.Promiscious;
	m_snapshotSizeProp.m_value = Defaults.SnapshotSize;
	m_ipFragmentLimitProp.m_value = io.IpDefragmenter.DefIpFragmentLimit;
	m_ipFragmentTimeoutProp.m_value = io.IpDefragmenter.DefIpFragmentTimeout;
	m_bufferPropertySet.restoreDefaults ();
}

size_t errorcode SnifferSession.transmit (
	void const* p,
	size_t size
	)
{
	if (!m_pcap)
		return -1;

	size_t result = try m_pcap.write (p, size);
	if (result != -1)
	{
		writeLog (SnifferLogRecordCode.InjectedPacket, p, result);
		m_stdSessionInfoSet.addTxData (size);
	}

	return result;
}

SnifferSession.onPcapEvent (
	uint_t syncId,
	io.PcapEvents triggeredEvents
	)
{
	if (syncId != m_syncId)
		return;

	if (triggeredEvents & io.PcapEvents.IoError)
	{
		writeLog (log.StdRecordCode.Error, m_pcap.m_ioError, m_pcap.m_ioError.m_size);
		stopCapture ();
		return;
	}

	if ((triggeredEvents & io.PcapEvents.ReadBufferFull) &&
		m_bufferPropertySet.m_notifyReadBufferFullProp.m_value)
		writeLog (log.StdRecordCode.RxBufferFull);

	if (triggeredEvents & io.PcapEvents.IncomingData)
	{
		size_t result = m_pcap.read (m_readBuffer.m_p, m_readBuffer.m_size);
		if (result)
			processPacket (m_readBuffer.m_p, result);
	}

	if (triggeredEvents & io.PcapEvents.Eof)
	{
		stopCapture ();
		return;
	}

	waitPcapEvents ();
}

SnifferSession.processPacket (
	void const* p,
	size_t size
	)
{
	writeLog (SnifferLogRecordCode.Packet, p, size);
	m_stdSessionInfoSet.addRxData (size);

	// defragment IPv4

	if (size < sizeof (io.EthernetHdr) + sizeof (io.IpHdr))
		return;

	io.EthernetHdr const* ethernetHdr = (io.EthernetHdr const*) p;
	if (ethernetHdr.m_type != io.EthernetType.Ip)
		return;

	p += sizeof (io.EthernetHdr);
	size -= sizeof (io.EthernetHdr);

	io.IpHdr const* ipHdr = (io.IpHdr const*) p;
	if ((ipHdr.m_flags & io.IpFlags.Mf) || ipHdr.m_fragmentOffset)
	{
		ipHdr = m_ipDefragmenter.defragment (ipHdr, size);
		if (ipHdr)
		{
			size = dynamic sizeof (ipHdr);
			writeLog (SnifferLogRecordCode.DefragmentedIp, ipHdr, size);
		}
	}
}

reactor SnifferSession.m_uiReactor ()
{
	m_title = $"Pcap $(m_deviceCombo.m_currentText)";
	m_isTransmitEnabled = m_state == State.Capturing;
	m_actionTable [ActionId.Capture].m_text = m_state ? "Stop Capture" : "Capture";
	m_actionTable [ActionId.Capture].m_icon = m_iconTable [m_state ? IconId.StopCapture : IconId.Capture];
	m_statusPaneTable [StatusPaneId.State].m_text = m_state ? "Capturing" : "Closed";
}

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