module CCID_Emulation {

/* This module implements multiplexing/demultiplexing of USB CCID, enabling different
 * TTCN-3 test components to talk to different CCID slots
 *
 * (C) 2019 by Harald Welte <laforge@gnumonks.org>
 * All rights reserved.
 */


import from General_Types all;
import from Osmocom_Types all;
import from Misc_Helpers all;

import from USB_Types all;
import from USB_Templates all;
import from USB_PortType all;
import from USB_PortTypes all;
import from USB_Component all;

import from CCID_Types all;
import from CCID_Templates all;

modulepar {
	boolean mp_quirk_resetpar_returns_slotsts := false;
};

type enumerated CCID_Emulation_Event_UpDown {
	CCID_EVENT_UP,
	CCID_EVENT_DOWN
};

type union CCID_Emulation_Event {
	CCID_Emulation_Event_UpDown up_down
};

type port CCID_SLOT_PT message {
	inout CCID_PDU, CCID_Emulation_Event;
} with { extension "internal" }

type record CCID_Emulation_Params {
	USB_Device_Match usb_dev_match
};

type component CCID_Emulation_CT extends USB_CT {
	var integer g_interface;
	var integer g_ep_in;
	var integer g_ep_out;
	var integer g_ep_irq;
	var CCID_Emulation_Params g_pars;

	var integer g_next_bseq := 0;

	/* ports to the test components; one for each theoretically possible slot */
	port CCID_SLOT_PT SLOT[256];
}

private const octetstring c_oct261 := '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'O;

private function f_usb_submit_xfer(USB_endpoint ep, octetstring data := c_oct261,
				   USB_transfer_type ttype := USB_TRANSFER_TYPE_BULK,
				   integer tout_ms := 30000) runs on CCID_Emulation_CT
{
	var integer req_hdl := f_usb_get_req_hdl();
	var USB_transfer xfer := {
		device_hdl := g_dev_hdl,
		transfer_hdl := req_hdl,
		endpoint := ep,
		ttype := ttype,
		data := data,
		timeout_msec := tout_ms
	};
	USB.send(xfer);
}

function main(CCID_Emulation_Params pars) runs on CCID_Emulation_CT {
	var USB_transfer_compl tc;
	var CCID_PDU ccid_in, ccid_out;
	var integer i, v_i;

	g_pars := pars;

	f_usb_init(g_pars.usb_dev_match);

	log(f_usb_get_desc_tree());

	var integer i_config := f_usb_get_config();
	var USB_Descriptor_Node root;
	log("USB Configuration: ", i_config);
	root := f_usb_get_desc_tree();
	log(root);

	/* iterate over list of interfaces in current configuration */
	for (i := 0; i < lengthof(root.children[i_config].children); i:=i+1) {
		var USB_Descriptor_Node ifn := root.children[i_config].children[i];
		var USB_InterfaceDescriptor ifd := ifn.desc.interface;
		/* Search for CCID interface */
		if (ifd.bInterfaceClass == '0B'O and
		    ifd.bInterfaceSubClass == '00'O and ifd.bInterfaceProtocol == '00'O) {
			g_interface := ifd.bInterfaceNumber;
			var integer j;
			/* determine endpoints inside interface */
			for (j := 0; j < lengthof(ifn.children); j:=j+1) {
				log("Iterating over ", ifn.children[j]);
				if (ischosen(ifn.children[j].desc.endpoint)) {
					var USB_EndpointDescriptor epd := ifn.children[j].desc.endpoint;
					select (epd.bmAttributes.TranferType) {
					case (USB_EpTransfer_BULK) {
						if (epd.bEndpointAddress and4b '80'O == '80'O) {
							g_ep_in := oct2int(epd.bEndpointAddress);
						} else {
							g_ep_out := oct2int(epd.bEndpointAddress);
						}
						}
					case (USB_EpTransfer_INTERRUPT) {
						g_ep_irq := oct2int(epd.bEndpointAddress);
						}
					}
				}
			}
			break;
		}
	}

	log("USB Endpoints found: IN: ", int2oct(g_ep_in, 1), ", OUT: ", int2oct(g_ep_out, 1),
		" IRQ: ", int2oct(g_ep_irq, 1));

	f_usb_claim_interface(g_dev_hdl, g_interface);

	/* submit xfer fro IN and IRQ endpoints */
	f_usb_submit_xfer(g_ep_in);
	f_usb_submit_xfer(g_ep_irq, ttype := USB_TRANSFER_TYPE_INTERRUPT);

	/* let everyone know we're alive and kicking */
	for (i := 0; i < 256; i := i+1) {
		if (SLOT[i].checkstate("Connected")) {
			SLOT[i].send(CCID_Emulation_Event:{up_down:=CCID_EVENT_UP});
		}
	}

	while (true) {

	alt {
	[] USB.receive(tr_UsbXfer_compl(g_ep_out, USB_TRANSFER_TYPE_BULK, USB_TRANSFER_COMPLETED,
					     g_dev_hdl, ?)) -> value tc {
		/* do nothing; normal completion of OUT transfer */
		}
	[] USB.receive(tr_UsbXfer_compl(g_ep_in, USB_TRANSFER_TYPE_BULK, USB_TRANSFER_COMPLETED,
					     g_dev_hdl, ?)) -> value tc {
		/* Submit another IN transfer */
		f_usb_submit_xfer(g_ep_in);
		/* forward to slot-specific port */
		ccid_in := dec_CCID_PDU(tc.data);
		SLOT[ccid_in.hdr.bSlot].send(ccid_in);
		}
	[] USB.receive(tr_UsbXfer_compl(g_ep_irq, USB_TRANSFER_TYPE_INTERRUPT,
					     USB_TRANSFER_COMPLETED, g_dev_hdl, ?)) -> value tc {
		/* Submit another IRQ transfer */
		f_usb_submit_xfer(g_ep_irq, ttype := USB_TRANSFER_TYPE_INTERRUPT);
		/* forward to all slot-specific ports with connected components */
/*
		ccid_in := dec_CCID_PDU(tc.data);
		for (i := 0; i < 256; i := i+1) {
			if (SLOT[i].checkstate("Connected")) {
				SLOT[i].send(ccid_in);
			}
		}
*/
		}
	[] USB.receive(tr_UsbXfer_compl(g_ep_irq, USB_TRANSFER_TYPE_INTERRUPT,
					     USB_TRANSFER_TIMED_OUT, g_dev_hdl, ?)) -> value tc {
		/* Submit another IRQ transfer */
		f_usb_submit_xfer(g_ep_irq, ttype := USB_TRANSFER_TYPE_INTERRUPT);
		}
	[] USB.receive(tr_UsbXfer_compl(?, ?, USB_TRANSFER_ERROR, g_dev_hdl, ?)) -> value tc {
		setverdict(fail, "Unexpected USB_TRANSFER_ERROR on EP ", int2hex(tc.endpoint, 2));
		mtc.stop;
		}
	[] USB.receive(tr_UsbXfer_compl(?, ?, USB_TRANSFER_TIMED_OUT, g_dev_hdl, ?)) -> value tc {
		setverdict(fail, "Unexpected USB_TRANSFER_TIMED_OUT on EP ", int2hex(tc.endpoint, 2));
		mtc.stop;
		}
	[] USB.receive(tr_UsbXfer_compl(?, ?, USB_TRANSFER_OVERFLOW, g_dev_hdl, ?)) -> value tc {
		setverdict(fail, "Unexpected USB_TRANSFER_OVERFLOW on EP ", int2hex(tc.endpoint, 2));
		mtc.stop;
		}
	[] USB.receive(tr_UsbXfer_compl(?, ?, ?, g_dev_hdl, ?)) -> value tc {
		setverdict(fail, "Unexpected USB Endpoint ", int2hex(tc.endpoint, 2));
		mtc.stop;
		}
	[] USB.receive(tr_UsbXfer_compl(?, ?, ?, ?, ?)) -> value tc {
		setverdict(fail, "Unexpected USB Device ", tc.device_hdl);
		mtc.stop;
		}
	[] USB.receive {
		setverdict(fail, "Unexpected Message from USB");
		mtc.stop;
		}

	[] any from SLOT.receive(CCID_PDU:?) -> value ccid_out @index value v_i {
		var octetstring bin;
		ccid_out.hdr.bSlot := v_i;
		ccid_out.hdr.bSeq := g_next_bseq;
		g_next_bseq := (g_next_bseq + 1) mod 256;
		bin := enc_CCID_PDU(ccid_out);
		f_usb_submit_xfer(g_ep_out, bin, tout_ms := 3000);
		}


	} /* alt */
	} /* while (true) */
}




/* per-slot test component; manages one slot */
type component Slot_CT {
	var uint8_t g_slot_nr;
	port CCID_SLOT_PT CCID;
	timer g_Tguard := 120.0;
};

/* altstep running on the per-slot test component */
altstep as_Tguard() runs on Slot_CT {
	[] g_Tguard.timeout {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "Tguard timeout");
		}
}

altstep as_ccid_any() runs on Slot_CT {
	var CCID_PDU pdu;
	[] CCID.receive(CCID_PDU:?) -> value pdu {
		setverdict(fail, "Received unexpected CCID ", pdu);
		self.stop;
		}
	[] CCID.receive {
		setverdict(fail, "Received unexpected non-CCID");
		self.stop;
		}
}

/* transceive a CCID command (send 'tx' on OUT; expect 'rx' on IN) */
private function f_ccid_xceive(template (value) CCID_PDU tx, template (present) CCID_PDU exp_rx)
runs on Slot_CT return CCID_PDU {
	var CCID_PDU pdu;

	tx.hdr.bSlot := g_slot_nr;
	exp_rx.hdr.bSlot := g_slot_nr;

	CCID.send(tx);
	alt {
	[] CCID.receive(exp_rx) -> value pdu {
		return pdu;
		}
	[] as_ccid_any();
	}
	return pdu;
}

private template (present) CCID_Header_IN tr_inact :=
	tr_CCID_HeaderIN_OK(icc_status := (CCID_ICC_STATUS_PRES_INACT, CCID_ICC_STATUS_NO_ICC));

private template (present) CCID_Header_IN tr_act :=
	tr_CCID_HeaderIN_OK(icc_status := CCID_ICC_STATUS_PRES_ACT);

/* Send IccPowerOn on OUT; expect DataBlock in retunr */
function f_ccid_power_on(CCID_PowerSelect psel := CCID_PWRSEL_AUTO,
			 template (present) CCID_Header_IN hdr_in := tr_act)
runs on Slot_CT return CCID_PDU {
	var CCID_PDU pdu;

	pdu := f_ccid_xceive(ts_CCID_IccPowerOn(g_slot_nr, psel),
			     tr_CCID_DataBlock(g_slot_nr, hdr_in := hdr_in) );
	return pdu;
}

/* Send IccPowerOn on OUT; expect SlotStatus in return */
function f_ccid_power_off(template (present) CCID_Header_IN hdr_in := tr_inact)
runs on Slot_CT return CCID_PDU {
	var CCID_PDU pdu;

	pdu := f_ccid_xceive(ts_CCID_IccPowerOff(g_slot_nr),
			     tr_CCID_SlotStatus(slot := g_slot_nr, hdr_in := hdr_in) );
	return pdu;
}

/* Send IccClockCommand on OUT; expect SlotStatus in return */
function f_ccid_clock_cmd(CCID_ClockCommand cmd,
			  template (present) CCID_Header_IN hdr_in := tr_CCID_HeaderIN_OK)
runs on Slot_CT return CCID_PDU {
	var CCID_PDU pdu;

	pdu := f_ccid_xceive(ts_CCID_ClockCommand(g_slot_nr, cmd),
			     tr_CCID_SlotStatus(slot := g_slot_nr, hdr_in := hdr_in));
	return pdu;
}

/* Send XfrBlock on OUT; expect DataBlock in return */
function f_ccid_xfr(octetstring tx, template octetstring rx) runs on Slot_CT return octetstring {
	var CCID_PDU pdu;

	pdu := f_ccid_xceive(ts_CCID_XfrBlock(g_slot_nr, tx, 0),
			     tr_CCID_DataBlock(g_slot_nr, ?, ?, rx) );
	return pdu.u.DataBlock.abData;
}

/* Send SetParameters on OUT; expect Parameters on IN */
function f_ccid_set_par(template (value) CCID_ProtocolData par,
			template (present) CCID_Header_IN hdr_in := tr_CCID_HeaderIN_OK)
runs on Slot_CT return CCID_PDU {
	var CCID_PDU pdu;

	pdu := f_ccid_xceive(ts_CCID_SetParameters(g_slot_nr, par),
			     tr_CCID_Parameters(g_slot_nr, hdr_in := hdr_in));
	return pdu;
}

/* Send GetParameters on OUT; expect Parameters on IN */
function f_ccid_get_par(template (present) CCID_Header_IN hdr_in := tr_CCID_HeaderIN_OK)
runs on Slot_CT return CCID_PDU {
	var CCID_PDU pdu;

	pdu := f_ccid_xceive(ts_CCID_GetParameters(g_slot_nr),
			     tr_CCID_Parameters(g_slot_nr, hdr_in := hdr_in));
	return pdu;
}

/* Send ResetParameters on OUT; expect Parameters on IN */
function f_ccid_reset_par(template (present) CCID_Header_IN hdr_in := tr_CCID_HeaderIN_OK)
runs on Slot_CT return CCID_PDU {
	var CCID_PDU pdu;

	/* [at least] Omnikey seems to have failed to follow the CCID spec here :/ */
	if (mp_quirk_resetpar_returns_slotsts) {
		pdu := f_ccid_xceive(ts_CCID_ResetParameters(g_slot_nr),
				     tr_CCID_SlotStatus(g_slot_nr, hdr_in := hdr_in));
	} else {
		pdu := f_ccid_xceive(ts_CCID_ResetParameters(g_slot_nr),
				     tr_CCID_Parameters(g_slot_nr, hdr_in := hdr_in));
	}
	return pdu;
}

/* Send Escape on OUT; expect Escape on IN */
function f_ccid_escape(template (value) octetstring data,
			template (present) CCID_Header_IN hdr_in := tr_CCID_HeaderIN_OK)
runs on Slot_CT return CCID_PDU {
	var CCID_PDU pdu;

	pdu := f_ccid_xceive(ts_CCID_Escape(g_slot_nr, data),
			     tr_CCID_EscapeIN(g_slot_nr, hdr_in := hdr_in));
	return pdu;
}

function f_ccid_get_slotstatus(template (present) CCID_Header_IN hdr_in := tr_CCID_HeaderIN_OK)
runs on Slot_CT return CCID_PDU {
	var CCID_PDU pdu;

	pdu := f_ccid_xceive(ts_CCID_GetSlotStatus(g_slot_nr),
			     tr_CCID_SlotStatus(g_slot_nr, hdr_in := hdr_in));
	return pdu;
}




}
