module GGSN_Tests {

/* GGSN test suite in TTCN-3
 * (C) 2017-2019 Harald Welte <laforge@gnumonks.org>
 * (C) 2018-2019 sysmocom - s.f.m.c. GmbH
 * All rights reserved.
 *
 * Released under the terms of GNU General Public License, Version 2 or
 * (at your option) any later version.
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 */


	import from General_Types all;
	import from Osmocom_Types all;
	import from Misc_Helpers all;
	import from IPL4asp_PortType all;
	import from IPL4asp_Types all;
	import from GTP_CodecPort all;
	import from GTP_CodecPort_CtrlFunct all;
	import from GTP_Templates all;
	import from GTPC_Types all;
	import from GTPU_Types all;
	import from IPCP_Types all;
	import from PAP_Types all;
	import from IP_Types all;
	import from ICMP_Types all;
	import from ICMPv6_Types all;
	import from Native_Functions all;
	import from Osmocom_VTY_Functions all;
	import from TELNETasp_PortType all;

	const integer GTP0_PORT := 3386;
	const integer GTP1C_PORT := 2123;
	const integer GTP1U_PORT := 2152;

	modulepar {
		/* Default IP addresses. May be overridden by GGSN_Tests configuration files. */

		/* The SGSN simulated by TTCN3 will bind to these addresses for GTP control and GTP user planes. */
		charstring m_bind_ip_gtpc := "127.23.42.1";
		charstring m_bind_ip_gtpu := "127.23.42.1";

		/* Addresses the GGSN which is being tested is listening on for SGSN connections. */
		charstring m_ggsn_ip_gtpc := "127.0.0.6";
		charstring m_ggsn_ip_gtpu := "127.0.0.6";

		/*
		 * Our tests expect to see these DNS servers in 'Create PDP context responses' sent by the GGSN.
		 * These addresses must therefore match 'ip[v6] dns' options configured in osmo-ggsn.conf.
		 *
		 * These addresses are not expected to serve actual DNS requests. However, tests may expect to be
		 * able to ping these addresses (currently, IPv4 addresses must respond with an ICMP 'echo reply',
		 * and IPv6 addresses may respond with either ICMPv6 'echo reply' or 'destination unreachable').
		 */
		charstring m_ggsn_ip4_dns1 := "192.168.100.1"
		charstring m_ggsn_ip4_dns2 := "8.8.8.8"
		charstring m_ggsn_ip6_dns1 := "2001:4860:4860::8888"
		charstring m_ggsn_ip6_dns2 := "2001:4860:4860::8844"

		/*
		 * Additional address ranges are defined in osmo-ggsn.conf from which addresses are assigned
		 * to MS "behind" the simulated SGSN. These addresses appear on tun devices used by osmo-ggsn.
		 * The tests expect to be able to send ping packets between any two simulated MS within the same
		 * address range. This requires IP forwarding to be enabled on the corresponding tun interfaces.
		 */
	}

	type set PdpContext {
		hexstring	imsi,
		octetstring	msisdn optional,
		octetstring	apn,
		ProtConfigOptions	pco_req optional,
		ProtConfigOptions	pco_neg optional,
		EndUserAddress	eua,
		OCT16		ip6_prefix optional,
		BIT4		nsapi,
		/* TEI (Data) local side */
		OCT4		teid,
		/* TEI (Control) local side */
		OCT4		teic,
		/* TEI (Data) remote side */
		OCT4		teid_remote,
		/* TEI (Control) remote side */
		OCT4		teic_remote
	}

	type component GT_CT {
		port GTPC_PT GTPC;
		port GTPU_PT GTPU;

		var boolean g_initialized := false;

		var OCT1 g_restart_ctr := '01'O;
		/* FIXME: unify with g_bind_ip + parse from config file */
		var OCT4 g_sgsn_ip_c;
		var OCT4 g_sgsn_ip_u;
		/* FIXME: parse remName from config file */
		var GtpPeer g_peer_c := { connId := 0, remName := m_ggsn_ip_gtpc, remPort := GTP1C_PORT };
		var GtpPeer g_peer_u := { connId := 0, remName := m_ggsn_ip_gtpu, remPort := GTP1U_PORT };
		timer T_default := 3.0;

		/* next to-be-sent GTP-C sequence number */
		var uint16_t g_c_seq_nr;
		/* next to-be-sent GTP-U sequence number */
		var uint16_t g_d_seq_nr;

		port TELNETasp_PT GGSNVTY;
		var boolean use_gtpu_txseq := false;
		var boolean g_use_echo := false;
	}

	private function f_init_vty() runs on GT_CT {
		map(self:GGSNVTY, system:GGSNVTY);
		f_vty_set_prompts(GGSNVTY);
		f_vty_transceive(GGSNVTY, "enable");
	}

	private function f_vty_set_gpdu_txseq(boolean enable) runs on GT_CT {
		f_vty_enter_config(GGSNVTY);
		f_vty_transceive(GGSNVTY, "ggsn ggsn0");

		f_vty_transceive(GGSNVTY, "apn internet");
		if (enable) {
			f_vty_transceive(GGSNVTY, "g-pdu tx-sequence-numbers");
		} else {
			f_vty_transceive(GGSNVTY, "no g-pdu tx-sequence-numbers");
		}
		f_vty_transceive(GGSNVTY, "exit");

		f_vty_transceive(GGSNVTY, "apn inet6");
		if (enable) {
			f_vty_transceive(GGSNVTY, "g-pdu tx-sequence-numbers");
		} else {
			f_vty_transceive(GGSNVTY, "no g-pdu tx-sequence-numbers");
		}
		f_vty_transceive(GGSNVTY, "exit");

		f_vty_transceive(GGSNVTY, "apn inet46");
		if (enable) {
			f_vty_transceive(GGSNVTY, "g-pdu tx-sequence-numbers");
		} else {
			f_vty_transceive(GGSNVTY, "no g-pdu tx-sequence-numbers");
		}
		f_vty_transceive(GGSNVTY, "end");
	}

	private function f_verify_gtpu_txseq(in PDU_GTPU gtpu, in boolean expect_gptu_txseq) return boolean {
			if (expect_gptu_txseq) {
				if (gtpu.s_bit != '1'B) {
					log("GTPU sequence number expected but not present")
					return false;
				}
			} else {
				if (gtpu.s_bit != '0'B) {
					log("GTPU sequence number not expected but present")
					return false;
				}
			}
			return true;
	}

	private function f_vty_enable_echo_interval(boolean enable) runs on GT_CT {
		f_vty_enter_config(GGSNVTY);
		f_vty_transceive(GGSNVTY, "ggsn ggsn0");
		if (enable) {
			f_vty_transceive(GGSNVTY, "echo-interval 5");
		} else {
			f_vty_transceive(GGSNVTY, "no echo-interval");
		}
		f_vty_transceive(GGSNVTY, "end");
	}

	function f_init() runs on GT_CT {
		if (g_initialized == true) {
			return;
		}
		g_initialized := true;

		g_sgsn_ip_c := f_inet_addr(m_bind_ip_gtpc);
		g_sgsn_ip_u := f_inet_addr(m_bind_ip_gtpu);

		var Result res;
		map(self:GTPC, system:GTPC);
		res := GTP_CodecPort_CtrlFunct.f_IPL4_listen(GTPC, m_bind_ip_gtpc, GTP1C_PORT, {udp:={}});
		log("GTP1C ConnectionID: ", res.connId);
		g_peer_c.connId := res.connId;

		map(self:GTPU, system:GTPU);
		res := GTP_CodecPort_CtrlFunct.f_GTPU_listen(GTPU, m_bind_ip_gtpu, GTP1U_PORT, {udp:={}});
		g_peer_u.connId:= res.connId;

		g_restart_ctr := f_rnd_octstring(1);
		g_c_seq_nr := f_rnd_int(65535);
		g_d_seq_nr := f_rnd_int(65535);

		f_init_vty();
		f_vty_set_gpdu_txseq(use_gtpu_txseq);
		f_vty_enable_echo_interval(g_use_echo);
	}

	/* Altstep implementing responses to any incoming echo requests */
	altstep pingpong() runs on GT_CT {
		var Gtp1cUnitdata ud;
		var Gtp1uUnitdata udu;
		[g_use_echo] GTPC.receive(tr_GTPC_PING(?)) -> value ud {
			var uint16_t seq := oct2int(ud.gtpc.opt_part.sequenceNumber);
			GTPC.send(ts_GTPC_PONG(ud.peer, seq, g_restart_ctr));
			repeat;
		};
		[not g_use_echo] GTPC.receive(tr_GTPC_PING(?)) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
						"GTP Echo Req rceived but not enabled in VTY");
		};
		[] T_default.timeout {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
						"pinpong T_default timeout");
		};
	}

	/* 'internet' in DNS encoding */
	const octetstring c_ApnInternet := '08696E7465726E6574'O;
	const octetstring c_ApnInet6 := '05696E657436'O;
	const octetstring c_ApnInet46 := '06696E65743436'O;

	/* return random NSAPI */
	function f_rnd_nsapi() return BIT4 {
		return int2bit(f_rnd_int(16), 4);
	}

	/* return random TEI[DC] */
	function f_rnd_tei() return OCT4 {
		return int2oct(f_rnd_int(4294967296), 4);
	}

	/* define an (internal) representation of a PDP context */
	template PdpContext t_DefinePDP(hexstring imsi, octetstring msisdn, octetstring apn,
					EndUserAddress eua) := {
		imsi := imsi,
		msisdn := msisdn,
		nsapi := f_rnd_nsapi(),
		apn := apn,
		pco_req := omit,
		eua := eua,
		teid := f_rnd_tei(),
		teic := f_rnd_tei()
	}

	/* send GTP-C for a given context and increment sequence number */
	function f_send_gtpc(in template Gtp1cUnitdata data) runs on GT_CT {
		GTPC.send(data);
		g_c_seq_nr := g_c_seq_nr + 1;
	}

	/* send GTP-U for a given context and increment sequence number */
	function f_send_gtpu(inout PdpContext ctx, in octetstring data) runs on GT_CT {
		if (use_gtpu_txseq) {
			GTPU.send(ts_GTP1U_GPDU(g_peer_u, g_d_seq_nr, ctx.teid_remote, data));
			g_d_seq_nr := g_d_seq_nr + 1;
		} else {
			GTPU.send(ts_GTP1U_GPDU(g_peer_u, omit, ctx.teid_remote, data));
		}
	}

	function f_handle_create_req(inout PdpContext ctx, in Gtp1cUnitdata ud, in OCT1 exp_cause := '80'O) runs on GT_CT {
		var CreatePDPContextResponse cpr := ud.gtpc.gtpc_pdu.createPDPContextResponse;
		if (exp_cause == '80'O and exp_cause == cpr.cause.causevalue) {
			/*  Check if EUA type corresponds to requested type */
			if (match(ctx.eua, t_EuaIPv4(?)) and
			    not match(cpr.endUserAddress, tr_EuaIPv4(?))){
				setverdict(fail);
			}
			if (match(ctx.eua, t_EuaIPv6(?)) and
			    not match(cpr.endUserAddress, tr_EuaIPv6(?))) {
				setverdict(fail);
			}
			if (match(ctx.eua, t_EuaIPv4v6(?, ?)) and
			    not match(cpr.endUserAddress, tr_EuaIPv4v6(?, ?))) {
				setverdict(fail);
			}
			/* Check if PCO response corresponds to request */
			if (ispresent(ctx.pco_req)) {
				if (match(ctx.pco_req, ts_PCO_IPv4_DNS_CONT) and
				    not match(cpr.protConfigOptions, tr_PCO_IPv4_DNS_CONT_resp(?))) {
					log("IPv4 DNS Container requested, but missing");
					setverdict(fail);
				}
				if (match(ctx.pco_req, ts_PCO_IPv6_DNS) and
				    not match(cpr.protConfigOptions, tr_PCO_IPv6_DNS_resp(?))) {
					log("IPv6 DNS Container requested, but missing");
					setverdict(fail);
				}
			}
			ctx.teid_remote := cpr.teidDataI.teidDataI;
			ctx.teic_remote := cpr.teidControlPlane.teidControlPlane;
			ctx.eua := cpr.endUserAddress;
			ctx.pco_neg := cpr.protConfigOptions;
			setverdict(pass);
		} else if (exp_cause != '80'O and exp_cause == cpr.cause.causevalue) {
			if (ispresent(cpr.endUserAddress)) {
				log("EUA received on createPDPContextResponse cause=" & oct2str(cpr.cause.causevalue));
				setverdict(fail);
			}
			setverdict(pass);
		} else {
			setverdict(fail);
		}
	}

	/* send a PDP context activation */
	function f_pdp_ctx_act(inout PdpContext ctx, OCT1 exp_cause := '80'O) runs on GT_CT {
		var Gtp1cUnitdata ud;
		var default d;

		log("sending CreatePDP");
		f_send_gtpc(ts_GTPC_CreatePDP(g_peer_c, g_c_seq_nr, ctx.imsi, g_restart_ctr,
						  ctx.teid, ctx.teic, ctx.nsapi, ctx.eua, ctx.apn,
						  g_sgsn_ip_c, g_sgsn_ip_u, ctx.msisdn, ctx.pco_req));
		T_default.start;
		d := activate(pingpong());
		alt {
			[] GTPC.receive(tr_GTPC_MsgType(g_peer_c, createPDPContextResponse, ctx.teic)) -> value ud {
				f_handle_create_req(ctx, ud, exp_cause);
			}
		}
		deactivate(d);
		T_default.stop;
	}

	function f_pdp_ctx_exp_del_req(PdpContext ctx, template (omit) OCT1 expect_cause := omit, boolean expect_teardown := false) runs on GT_CT {
		var Gtp1cUnitdata ud;
		var default d;

		T_default.start;
		d := activate(pingpong());
		alt {
			[] GTPC.receive(tr_GTPC_MsgType(g_peer_c, deletePDPContextRequest, ctx.teic)) -> value ud {
				if (istemplatekind(expect_cause, "omit") and not ispresent(ud.gtpc.gtpc_pdu.deletePDPContextRequest.cause.causevalue)) {
					setverdict(pass);
				} else if (not istemplatekind(expect_cause, "omit") and
					   ispresent(ud.gtpc.gtpc_pdu.deletePDPContextRequest.cause.causevalue) and
					   ud.gtpc.gtpc_pdu.deletePDPContextRequest.cause.causevalue == valueof(expect_cause)) {
					setverdict(pass);
				} else {
					setverdict(fail);
				}

				if (expect_teardown == ispresent(ud.gtpc.gtpc_pdu.deletePDPContextRequest.tearDownIndicator)) {
					setverdict(pass);
				} else {
					setverdict(fail);
				}
			}
		}
		deactivate(d);
		T_default.stop;
	}

	function f_pdp_ctx_del(PdpContext ctx, template BIT1 teardown_ind, OCT1 expect_causevalue := '80'O) runs on GT_CT {
		var Gtp1cUnitdata ud;
		var default d;
		var OCT4 expect_teid;

		/* 3GPP TS 29.060 sec 7.3.6 specifies TEID used in response
		   message with cause value "Non existent" shall be zero. */
		if (expect_causevalue == 'C0'O) {
			expect_teid := '00000000'O;
		} else {
			expect_teid := ctx.teic;
		}

		f_send_gtpc(ts_GTPC_DeletePDP(g_peer_c, g_c_seq_nr, ctx.teic_remote, ctx.nsapi, teardown_ind));
		T_default.start;
		d := activate(pingpong());
		alt {
			[] GTPC.receive(tr_GTPC_MsgType(g_peer_c, deletePDPContextResponse, expect_teid)) -> value ud {
				if (ud.gtpc.gtpc_pdu.deletePDPContextResponse.cause.causevalue == expect_causevalue) {
					setverdict(pass);
				} else {
					setverdict(fail);
				}
			}
		}
		deactivate(d);
		T_default.stop;
	}
	/* IPv6 router solicitation  fe80::2 -> ff02::2 from 02:88:b5:1f:25:59 */
	const octetstring c_router_solicit := '6000000000103afffe800000000000000000000000000002ff02000000000000000000000000000285009f2b0000000001010288b51f2559'O;
	/* IPv6 neighbor solicitation fe80::2 -> ff02::1:ff00:2 from 02:88:b5:1f:25:59 */
	const octetstring c_neigh_solicit:= '6000000000203afffe800000000000000000000000000002ff0200000000000000000001ff00000287009f9600000000fe80000000000000000000000000000201010288b51f2559'O;

	/* template for sending an ICMPv4 echo request */
	template PDU_ICMP ts_ICMPv4_ERQ := {
		echo := {
			type_field := 8,
			code := 0,
			checksum := '0000'O,
			identifier := '0345'O,
			sequence_number := '0001'O,
			data := ''O
		}
	}

	/* template for receiving/matching an ICMPv4 echo request */
	template PDU_ICMP tr_ICMPv4_ERQ := {
		echo := {
			type_field := 8,
			code := 0,
			checksum := ?,
			identifier := ?,
			sequence_number := ?,
			data := ?
		}
	}

	/* template for receiving/matching an ICMPv4 echo reply */
	template PDU_ICMP tr_ICMPv4_ERP(template octetstring data := *) := {
		echo_reply := {
			type_field := 0,
			code := 0,
			checksum := ?,
			identifier := ?,
			sequence_number := ?,
			data := data
		}
	}

	/* template for receiving/matching an ICMPv6 Destination Unreachable  */
	template PDU_ICMP tr_ICMPv4_DU := {
		destination_unreachable := {
			type_field := 1,
			code := ?,
			checksum := ?,
			unused := ?,
			original_ip_msg  := ?
		}
	}

	/* template to construct IPv4_packet from input arguments, ready for use in f_IPv4_enc() */
	template IPv4_packet ts_IP4(OCT4 srcaddr, OCT4 dstaddr, LIN1 proto, LIN2_BO_LAST tlen, octetstring payload) := {
		header := {
			ver := 4,
			hlen := 5,
			tos := 0,
			tlen := tlen,
			id := 35902,
			res := '0'B,
			dfrag := '1'B,
			mfrag := '0'B,
			foffset := 0,
			ttl := 64,
			proto := proto,
			cksum := 0,
			srcaddr := srcaddr,
			dstaddr := dstaddr
		},
		ext_headers := omit,
		payload := payload
	}

	/* template to generate a 'Prefix Information' ICMPv6 option */
	template OptionField ts_ICMP6_OptPrefix(OCT16 prefix, INT1 prefix_len) := {
		prefixInformation := {
			typeField := 3,
			lengthIndicator := 8,
			prefixLength := prefix_len,
			reserved1 := '000000'B,
			a_Bit := '0'B,
			l_Bit := '0'B,
			validLifetime := oct2int('FFFFFFFF'O),
			preferredLifetime := oct2int('FFFFFFFF'O),
			reserved2 := '00000000'O,
			prefix := prefix
		}
	}

	/* template for sending an ICMPv6 echo request */
	template PDU_ICMPv6 ts_ICMPv6_ERQ := {
		echoRequest := {
			typeField := 128,
			code := 0,
			checksum := '0000'O,
			identifier := 0,
			sequenceNr := 0,
			data := ''O
		}
	}

	/* template for sending an ICMPv6 router solicitation */
	template PDU_ICMPv6 ts_ICMPv6_RS := {
		routerSolicitation := {
			typeField := 133,
			code := 0,
			checksum := '0000'O,
			reserved := '00000000'O,
			/* TODO: do we need 'Source link-layer address' ? */
			options := omit
		}
	}

	/* template for sending an ICMPv6 router advertisement */
	template PDU_ICMPv6 ts_ICMPv6_RA(OCT16 prefix, INT1 prefix_len) := {
		routerAdvertisement := {
			typeField := 134,
			code := 0,
			checksum := '0000'O,
			curHopLimit := ?,
			reserved := '000000'B,
			o_Bit := '0'B,
			m_Bit := '0'B,
			routerLifetime := oct2int('FFFF'O),
			reachableTime := oct2int('FFFFFFFF'O),
			retransTimer := oct2int('FFFFFFFF'O),
			options := {
				ts_ICMP6_OptPrefix(prefix, prefix_len)
			}
		}
	}

	/* template for sending an ICMPv6 neighbor solicitation */
	template PDU_ICMPv6 ts_ICMPv6_NS(OCT16 target_addr) := {
		neighborSolicitation := {
			typeField := 135,
			code := 0,
			checksum := '0000'O,
			reserved := '00000000'O,
			targetAddress := target_addr,
			/* TODO: do we need 'Source link-layer address' ? */
			options := omit
		}
	}

	/* derive ICMPv6 link-local address from lower 64bit of link_id */
	/* template for receiving/matching an ICMPv6 'Prefix Information' option */
	template OptionField tr_ICMP6_OptPrefix(template OCT16 prefix, template INT1 prefix_len) := {
		prefixInformation := {
			typeField := 3,
			lengthIndicator := 4,
			prefixLength := prefix_len,
			reserved1 := ?,
			a_Bit := ?,
			l_Bit := ?,
			validLifetime := ?,
			preferredLifetime := ?,
			reserved2 := ?,
			prefix := prefix
		}
	}

	/* template for receiving/matching an ICMPv6 router advertisement */
	template PDU_ICMPv6 tr_ICMPv6_RA(template OCT16 prefix, template INT1 prefix_len) := {
		routerAdvertisement := {
			typeField := 134,
			code := 0,
			checksum := ?,
			curHopLimit := ?,
			reserved := ?,
			o_Bit := '0'B,
			m_Bit := '0'B,
			routerLifetime := ?,
			reachableTime := ?,
			retransTimer := ?,
			options := {
				tr_ICMP6_OptPrefix(prefix, prefix_len)
			}
		}
	}

	/* template for receiving/matching an ICMPv6 Destination Unreachable  */
	template PDU_ICMPv6 tr_ICMPv6_DU := {
		destinationUnreachable := {
			typeField := 1,
			code := ?,
			checksum := ?,
			unused := ?,
			originalIpMsg  := ?
		}
	}

	/* template for receiving/matching an ICMPv6 echo request */
	template PDU_ICMPv6 tr_ICMPv6_ERQ := {
		echoRequest := {
			typeField := 128,
			code := 0,
			checksum := ?,
			identifier := ?,
			sequenceNr := ?,
			data := ?
		}
	}

	/* template for receiving/matching an ICMPv6 echo reply */
	template PDU_ICMPv6 tr_ICMPv6_ERP(template octetstring data := *) := {
		echoReply := {
			typeField := 129,
			code := 0,
			checksum := ?,
			identifier := ?,
			sequenceNr := ?,
			data := data
		}
	}

	/* template to construct IPv6_packet from input arguments, ready for use in f_IPv6_enc() */
	template IPv6_packet ts_IP6(OCT16 srcaddr, OCT16 dstaddr, LIN1 nexthead, octetstring payload, LIN1 hlim := 255) := {
		header := {
			ver := 6,
			trclass := 0,
			flabel := 0,
			plen := 0,
			nexthead := nexthead,
			hlim := hlim,
			srcaddr := srcaddr,
			dstaddr := dstaddr
		},
		ext_headers := omit,
		payload := payload
	}

	function f_ipv6_link_local(in OCT16 link_id) return OCT16 {
		 return 'FE80000000000000'O & substr(link_id, 8, 8);
	}

	function f_ipv6_global(in OCT16 link_id) return OCT16 {
		 return substr(link_id, 0, 8) & '1234123412341234'O;
	}

	/* Create a new different IPv6 addr from input. Starts mangling at byte prefix. */
	function f_ipv6_mangle(in OCT16 addr, in integer prefix := 0) return OCT16 {
		var integer i;
		var octetstring res := substr(addr, 0, prefix);
		for (i := prefix; i < lengthof(addr); i := i + 1) {
			var octetstring a := addr[i] xor4b '11'O;
			res := res & a;
		}
		return res;
	}

	/* Compute solicited-node multicast address as per RFC4291 2.7.1 */
	function f_ipv6_sol_node_mcast(in OCT16 addr) return OCT16 {
		return 'FF0200000000000000000001FF'O & substr(addr, 13, 3);
	}

	/* generate and encode ICMPv6 router solicitation */
	function f_gen_icmpv6_router_solicitation(in OCT16 link_id) return octetstring {
		const OCT16 c_ip6_all_router_mcast := 'FF020000000000000000000000000002'O;
		var OCT16 saddr := f_ipv6_link_local(link_id);

		var octetstring tmp;
		tmp := f_enc_PDU_ICMPv6(valueof(ts_ICMPv6_RS), saddr, c_ip6_all_router_mcast);
		var IPv6_packet ip6 := valueof(ts_IP6(saddr, c_ip6_all_router_mcast, 58, tmp));

		return f_IPv6_enc(ip6);
	}

	/* create ICMPv6 router solicitation deriving link-id from PDP Context EUA */
	function f_icmpv6_rs_for_pdp(in PdpContext ctx) return octetstring {
		var OCT16 interface_id := ctx.eua.endUserAddress.endUserAddressIPv6.ipv6_address;
		return f_gen_icmpv6_router_solicitation(interface_id);
	}

	/* generate and encode ICMPv6 neighbor solicitation */
	function f_gen_icmpv6_neigh_solicit(in OCT16 saddr, in OCT16 daddr, in OCT16 tgt_addr) return octetstring {
		var octetstring tmp;
		tmp := f_enc_PDU_ICMPv6(valueof(ts_ICMPv6_NS(tgt_addr)), saddr, daddr);
		var IPv6_packet ip6 := valueof(ts_IP6(saddr, daddr, 58, tmp));
		return f_IPv6_enc(ip6);
	}

	/* generate and encode ICMPv6 neighbor solicitation for PDP Context */
	function f_gen_icmpv6_neigh_solicit_for_pdp(in PdpContext ctx) return octetstring {
		var OCT16 interface_id := ctx.eua.endUserAddress.endUserAddressIPv6.ipv6_address;
		var OCT16 link_local := f_ipv6_link_local(interface_id);
		var OCT16 daddr := f_ipv6_sol_node_mcast(link_local);

		return f_gen_icmpv6_neigh_solicit(link_local, daddr, link_local);
	}

	/* Send an ICMPv4 echo msg through GTP given pdp ctx, and ip src and dst addr */
	function f_gen_icmpv4_echo(OCT4 saddr, OCT4 daddr) return octetstring {
		var octetstring tmp := f_enc_PDU_ICMP(valueof(ts_ICMPv4_ERQ));
		var IPv4_packet ip4 := valueof(ts_IP4(saddr, daddr, 1, 50, tmp));
		var octetstring data := f_IPv4_enc(ip4);
		var OCT2 cksum := f_IPv4_checksum(data);
		data[10] := cksum[0];
		data[11] := cksum[1];
		return data;
	}

	/* Send an ICMPv6 echo msg through GTP given pdp ctx, and ip src and dst addr */
	function f_gen_icmpv6_echo(OCT16 saddr, OCT16 daddr) return octetstring {
		var octetstring tmp := f_enc_PDU_ICMPv6(valueof(ts_ICMPv6_ERQ), saddr, daddr);
		var IPv6_packet ip6 := valueof(ts_IP6(saddr, daddr, 58, tmp));
		var octetstring data := f_IPv6_enc(ip6);
		return data;
	}

	/* Wait for ICMPv4 from GTP */
	function f_wait_icmp4(PdpContext ctx, template PDU_ICMP expected) runs on GT_CT {
		var Gtp1uUnitdata ud;
		T_default.start;
		alt {
			[] GTPU.receive(tr_GTPU_GPDU(g_peer_u, ?)) -> value ud {
				if (f_verify_gtpu_txseq(ud.gtpu, use_gtpu_txseq) == false) {
					setverdict(fail);
					stop;
				}
				var octetstring gpdu := ud.gtpu.gtpu_IEs.g_PDU_IEs.data;
				var IPv4_packet ip4 := f_IPv4_dec(gpdu);
				if (ip4.header.ver != 4) {
					repeat;
				}
				var PDU_ICMP icmp4 := f_dec_PDU_ICMP(ip4.payload);
				if (not match(icmp4, expected)) {
					repeat;
				}
			}
			[] GTPU.receive { setverdict(fail); }
			[] T_default.timeout { setverdict(fail); }
		}
		T_default.stop;
	}

	/* Wait for ICMPv4 echo request from GTP */
	function f_wait_icmp4_echo_request(PdpContext ctx) runs on GT_CT {
		f_wait_icmp4(ctx, tr_ICMPv4_ERQ);
	}

	/* Wait for ICMPv4 echo reply (or unreachable) from GTP */
	function f_wait_icmp4_echo_reply(PdpContext ctx) runs on GT_CT {
		f_wait_icmp4(ctx, (tr_ICMPv4_ERP, tr_ICMPv4_DU));
	}

	/* Wait for ICMPv6 from GTP */
	function f_wait_icmp6(PdpContext ctx, template PDU_ICMPv6 expected) runs on GT_CT {
		var Gtp1uUnitdata ud;
		T_default.start;
		alt {
			[] GTPU.receive(tr_GTPU_GPDU(g_peer_u, ?)) -> value ud {
				if (f_verify_gtpu_txseq(ud.gtpu, use_gtpu_txseq) == false) {
					setverdict(fail);
					stop;
				}
				var octetstring gpdu := ud.gtpu.gtpu_IEs.g_PDU_IEs.data;
				var IPv6_packet ip6 := f_IPv6_dec(gpdu);
				if (ip6.header.ver != 6 or ip6.header.nexthead != 58) {
					repeat;
				}
				var PDU_ICMPv6 icmp6 := f_dec_PDU_ICMPv6(ip6.payload);
				if (not match(icmp6, expected)) {
					repeat;
				}
				/* We are waiting for RA, update ctx */
				if (match(icmp6, tr_ICMPv6_RA(?, 64))) {
					ctx.ip6_prefix := icmp6.routerAdvertisement.options[0].prefixInformation.prefix;
					log("RA with /64 prefix ", ctx.ip6_prefix);
				}
			}
			[] GTPU.receive(tr_GTPU_GPDU(?, ?)) { repeat; }
			[] GTPU.receive { setverdict(fail); }
			[] T_default.timeout { setverdict(fail); }
		}
		T_default.stop;
	}

	/* wait for GGSN to send us an ICMPv6 router advertisement */
	function f_wait_rtr_adv(PdpContext ctx) runs on GT_CT {
		f_wait_icmp6(ctx, tr_ICMPv6_RA(?, 64));
	}

	/* Wait for ICMPv6 echo request from GTP */
	function f_wait_icmp6_echo_request(PdpContext ctx) runs on GT_CT {
		f_wait_icmp6(ctx, tr_ICMPv6_ERQ);
	}

	/* Wait for ICMPv6 echo reply (or unreachable) from GTP */
	function f_wait_icmp6_echo_reply(PdpContext ctx) runs on GT_CT {
		f_wait_icmp6(ctx, (tr_ICMPv6_ERP,tr_ICMPv6_DU));
	}

	/* create ICMPv6 router solicitation deriving link-id from PDP Context EUA */
	function f_icmpv6_rs_for_pdp46(in PdpContext ctx) return octetstring {
		var OCT16 interface_id := ctx.eua.endUserAddress.endUserAddressIPv4andIPv6.ipv6_address;
		return f_gen_icmpv6_router_solicitation(interface_id);
	}

	/* generate and encode ICMPv6 neighbor solicitation for PDP Context */
	function f_gen_icmpv6_neigh_solicit_for_pdp46(in PdpContext ctx) return octetstring {
		var OCT16 interface_id := ctx.eua.endUserAddress.endUserAddressIPv4andIPv6.ipv6_address;
		var OCT16 link_local := f_ipv6_link_local(interface_id);
		var OCT16 daddr := f_ipv6_sol_node_mcast(link_local);

		return f_gen_icmpv6_neigh_solicit(link_local, daddr, link_local);
	}

	/* Assert we don't receive a ICMPv4/6 echo reply (or unreachable) from GTP */
	function f_wait_gtpu_fail(PdpContext ctx) runs on GT_CT {
		T_default.start;
		alt {
			[] GTPU.receive { setverdict(fail); }
			[] T_default.timeout { }
		}
		T_default.stop;
	}

	/* list of protocols where we don't accept duplicates */
	const OCT2List protocol_ids_nodupes := { 'C021'O, 'C023'O, 'C223'O, '8021'O };
	private function f_PCO_permits_duplicates(OCT2 id) return boolean {
		var integer i;
		for (i := 0; i < lengthof(protocol_ids_nodupes); i := i+1) {
			if (id == protocol_ids_nodupes[i]) {
				return false;
			}
		}
		return true;
	}

	/* ensure that every given protocol Identifier exist only exactly once in the PCO */
	function f_PCO_ensure_no_duplicates(ProtConfigOptions pco) {
		var OCT2List protocol_ids := {};
		var integer i, j;
		for (i := 0; i < lengthof(pco.protocols); i := i+1) {
			var OCT2 id := pco.protocols[i].protocolID;
			for (j := 0; j < lengthof(protocol_ids); j := j+1) {
				if (not f_PCO_permits_duplicates(id) and id == protocol_ids[j]) {
					setverdict(fail,  "Duplicate ProtocolID ", id, " already present in ", pco.protocols);
				}
			}
			protocol_ids := protocol_ids & { id };
		}
	}

	/* Test IPv6 context activation for dynamic IPv6 EUA without request of IPv6 DNS */
	testcase TC_pdp6_act_deact() runs on GT_CT {
		f_init();

		var PdpContext ctx := valueof(t_DefinePDP(f_rnd_imsi('26242'H), '1234'O, c_ApnInet6, valueof(t_EuaIPv6Dyn)));
		f_pdp_ctx_act(ctx);
		f_pdp_ctx_del(ctx, '1'B);
	}

	/* Test IPv6 context activation for dynamic IPv6 EUA wirh request of IPv6 DNS in PCO */
	testcase TC_pdp6_act_deact_pcodns() runs on GT_CT {
		f_init();

		var PdpContext ctx := valueof(t_DefinePDP(f_rnd_imsi('26242'H), '1234'O, c_ApnInet6, valueof(t_EuaIPv6Dyn)));
		ctx.pco_req := valueof(ts_PCO_IPv6_DNS);
		f_pdp_ctx_act(ctx);

		f_PCO_ensure_no_duplicates(ctx.pco_neg);
		/* verify PCO contains both primary and secondary DNS */
		var OCT4 ggsn_ip6_dns1 := f_inet6_addr(m_ggsn_ip6_dns1);
		if (not match(f_PCO_extract_proto(ctx.pco_neg, '0003'O, 1), ggsn_ip6_dns1)) {
				setverdict(fail, "Primary DNS IPv6 PCO option not found");
		}

		var OCT4 ggsn_ip6_dns2 := f_inet6_addr(m_ggsn_ip6_dns2);
		if (not match(f_PCO_extract_proto(ctx.pco_neg, '0003'O, 2), ggsn_ip6_dns2)) {
				setverdict(fail, "Secondary DNS IPv6 PCO option not found");
		}

		f_pdp_ctx_del(ctx, '1'B);
	}

	/* Test PDP context activation for dynamic IPv6 EUA with IPv6 DNS in PCO and router solicitation/advertisement */
	testcase TC_pdp6_act_deact_icmp6() runs on GT_CT {
		f_init();

		var PdpContext ctx := valueof(t_DefinePDP(f_rnd_imsi('26242'H), '1234'O, c_ApnInet6, valueof(t_EuaIPv6Dyn)));
		ctx.pco_req := valueof(ts_PCO_IPv6_DNS);
		f_pdp_ctx_act(ctx);

		f_PCO_ensure_no_duplicates(ctx.pco_neg);
		//f_send_gtpu(ctx, c_router_solicit);
		//f_send_gtpu(ctx, c_neigh_solicit);

		f_send_gtpu(ctx, f_icmpv6_rs_for_pdp(ctx));
		f_wait_rtr_adv(ctx);
		f_send_gtpu(ctx, f_gen_icmpv6_neigh_solicit_for_pdp(ctx));

		f_pdp_ctx_del(ctx, '1'B);
	}

	/* Test PDP context activation for dynamic IPv6 EUA with IPv6 DNS in PCO and router solicitation/advertisement.
	   Test we can send ICMPv6 ping over GTPU to DNS server. */
	testcase TC_pdp6_act_deact_gtpu_access() runs on GT_CT {
		f_init();
		var PdpContext ctx := valueof(t_DefinePDP(f_rnd_imsi('26242'H), '1234'O, c_ApnInet6, valueof(t_EuaIPv6Dyn)));
		ctx.pco_req := valueof(ts_PCO_IPv6_DNS);
		f_pdp_ctx_act(ctx);

		f_send_gtpu(ctx, f_icmpv6_rs_for_pdp(ctx));
		f_wait_rtr_adv(ctx);
		f_send_gtpu(ctx, f_gen_icmpv6_neigh_solicit_for_pdp(ctx));

		var OCT16 dns1_addr := f_PCO_extract_proto(ctx.pco_neg, '0003'O);

		/* Check if we can use valid link-local src addr.  */
		var OCT16 saddr_ll := f_ipv6_link_local(ctx.eua.endUserAddress.endUserAddressIPv6.ipv6_address);
		f_send_gtpu(ctx, f_gen_icmpv6_echo(saddr_ll, dns1_addr));
		f_wait_icmp6_echo_reply(ctx);

		/* Check that attempting RA with another ll src addr won't work, packet dropped: */
		var OCT16 saddr_ll_wrong := f_ipv6_mangle(saddr_ll, 8);
		f_send_gtpu(ctx, f_gen_icmpv6_router_solicitation(saddr_ll_wrong));
		f_wait_gtpu_fail(ctx);

		/* Check if we can use valid global src addr, should work */
		var OCT16 saddr_glob := f_ipv6_global(ctx.eua.endUserAddress.endUserAddressIPv6.ipv6_address);
		f_send_gtpu(ctx, f_gen_icmpv6_echo(saddr_glob, dns1_addr));
		f_wait_icmp6_echo_reply(ctx);

		/* Assert that packets with wrong global src addr are dropped by GGSN */
		var OCT16 saddr_wrong := f_ipv6_mangle(saddr_glob);
		f_send_gtpu(ctx, f_gen_icmpv6_echo(saddr_wrong, dns1_addr));
		f_wait_gtpu_fail(ctx);

		/* Send an IPv4 ICMP ECHO REQUEST to APN6, should fail (packet dropped) */
		var OCT4 saddr_v4 := f_inet_addr("192.168.10.2");
		var OCT4 daddr_v4 := f_inet_addr("8.8.8.8");
		f_send_gtpu(ctx, f_gen_icmpv4_echo(saddr_v4, daddr_v4));
		f_wait_gtpu_fail(ctx);

		f_pdp_ctx_del(ctx, '1'B);
	}

	/* Validate if different clients (pdp ctx) can reach one another through GGSN. */
	testcase TC_pdp6_clients_interact() runs on GT_CT {
		f_init();
		var PdpContext ctxA := valueof(t_DefinePDP(f_rnd_imsi('26242'H), '1234'O, c_ApnInet6, valueof(t_EuaIPv6Dyn)));
		var PdpContext ctxB := valueof(t_DefinePDP(f_rnd_imsi('26242'H), '1234'O, c_ApnInet6, valueof(t_EuaIPv6Dyn)));
		f_pdp_ctx_act(ctxA);
		f_send_gtpu(ctxA, f_icmpv6_rs_for_pdp(ctxA));
		f_wait_rtr_adv(ctxA);
		f_send_gtpu(ctxA, f_gen_icmpv6_neigh_solicit_for_pdp(ctxA));

		f_pdp_ctx_act(ctxB);
		f_send_gtpu(ctxB, f_icmpv6_rs_for_pdp(ctxB));
		f_wait_rtr_adv(ctxB);
		f_send_gtpu(ctxB, f_gen_icmpv6_neigh_solicit_for_pdp(ctxB));

		var OCT16 addrA_ll := f_ipv6_link_local(ctxA.eua.endUserAddress.endUserAddressIPv6.ipv6_address);
		var OCT16 addrB_ll := f_ipv6_link_local(ctxB.eua.endUserAddress.endUserAddressIPv6.ipv6_address);
		var OCT16 addrA_glob := f_ipv6_global(ctxA.eua.endUserAddress.endUserAddressIPv6.ipv6_address);
		var OCT16 addrB_glob := f_ipv6_global(ctxB.eua.endUserAddress.endUserAddressIPv6.ipv6_address);

		/* Validate if clients can interact using ll addr. */
		f_send_gtpu(ctxA, f_gen_icmpv6_echo(addrA_ll, addrB_ll));
		f_wait_gtpu_fail(ctxB);

		/* Validate if clients can interact using global addr. */
		f_send_gtpu(ctxA, f_gen_icmpv6_echo(addrA_glob, addrB_glob));
		f_wait_gtpu_fail(ctxB);

		f_pdp_ctx_del(ctxA, '1'B);
		f_pdp_ctx_del(ctxB, '1'B);
	}

	/* Test PDP context activation for dynamic IPv4 EUA without DNS request */
	testcase TC_pdp4_act_deact() runs on GT_CT {
		f_init();
		var PdpContext ctx := valueof(t_DefinePDP(f_rnd_imsi('26242'H), '1234'O, c_ApnInternet, valueof(t_EuaIPv4Dyn)));
		f_pdp_ctx_act(ctx);
		f_pdp_ctx_del(ctx, '1'B);
	}

	/* Test PDP context activation for dynamic IPv4 EUA with IPv4 DNS in IPCP */
	testcase TC_pdp4_act_deact_ipcp() runs on GT_CT {
		f_init();
		var OCT4 ggsn_ip4_dns1 := f_inet_addr(m_ggsn_ip4_dns1);
		var OCT4 ggsn_ip4_dns2 := f_inet_addr(m_ggsn_ip4_dns2);
		var PdpContext ctx := valueof(t_DefinePDP(f_rnd_imsi('26242'H), '1234'O, c_ApnInternet, valueof(t_EuaIPv4Dyn)));
		ctx.pco_req := valueof(ts_PCO_IPv4_DNS_IPCP);
		f_pdp_ctx_act(ctx);
		f_PCO_ensure_no_duplicates(ctx.pco_neg);
		/* verify IPCP is at all contained */
		if (not match(ctx.pco_neg, tr_PCO_Contains('8021'O))) {
			setverdict(fail, "IPCP not found in PCO");
		}
		/* verify IPCP contains both primary and secondary DNS */
		var IpcpPacket ipcp := dec_IpcpPacket(f_PCO_extract_proto(ctx.pco_neg, '8021'O));
		if (not match(ipcp, tr_IPCP_Ack_DNS(0, ggsn_ip4_dns1, ggsn_ip4_dns2))) {
			if (not match(ipcp, tr_IPCP_Ack_DNS(0))) {
				setverdict(fail, "Primary/Secondary DNS PCO IPCP option not found");
			} else {
				setverdict(fail, "Primary/Secondary DNS PCO IPCP option found but not matching expected values");
			}
		}
		f_pdp_ctx_del(ctx, '1'B);
	}

	/* Test PDP context activation for dynamic IPv4 EUA with IPv4 DNS in IPCP + PAP authentication (broken) */
	testcase TC_pdp4_act_deact_ipcp_pap_broken() runs on GT_CT {
		f_init();
		var OCT4 ggsn_ip4_dns1 := f_inet_addr(m_ggsn_ip4_dns1);
		var OCT4 ggsn_ip4_dns2 := f_inet_addr(m_ggsn_ip4_dns2);
		var PdpContext ctx := valueof(t_DefinePDP(f_rnd_imsi('26242'H), '1234'O, c_ApnInternet, valueof(t_EuaIPv4Dyn)));
		ctx.pco_req := valueof(ts_PCO_PAP_IPv4_DNS);
		f_pdp_ctx_act(ctx);
		f_PCO_ensure_no_duplicates(ctx.pco_neg);
		/* verify IPCP is at all contained */
		if (not match(ctx.pco_neg, tr_PCO_Contains('8021'O))) {
			setverdict(fail, "IPCP not found in PCO");
		}
		/* verify IPCP contains both primary and secondary DNS */
		var IpcpPacket ipcp := dec_IpcpPacket(f_PCO_extract_proto(ctx.pco_neg, '8021'O));
		if (not match(ipcp, tr_IPCP_Ack_DNS(0, ggsn_ip4_dns1, ggsn_ip4_dns2))) {
			if (not match(ipcp, tr_IPCP_Ack_DNS(0))) {
				setverdict(fail, "Primary/Secondary DNS PCO IPCP option not found");
			} else {
				setverdict(fail, "Primary/Secondary DNS PCO IPCP option found but not matching expected values");
			}
		}
		/* verify that PAP is contained */
		if (not match(ctx.pco_neg, tr_PCO_Contains('C023'O))) {
			setverdict(fail, "PAP not found in PCO");
		}
		var PapPacket pap := dec_PapPacket(f_PCO_extract_proto(ctx.pco_neg, 'C023'O));
		if (not match(pap, tr_PAP_AuthAck)) {
			setverdict(fail, "PAP isn't an AuthenticateAck: ", pap);
		}
		f_pdp_ctx_del(ctx, '1'B);
	}

	/* Test PDP context activation for dynamic IPv4 EUA with IPv4 DNS in PCO */
	testcase TC_pdp4_act_deact_pcodns() runs on GT_CT {
		f_init();
		var PdpContext ctx := valueof(t_DefinePDP(f_rnd_imsi('26242'H), '1234'O, c_ApnInternet, valueof(t_EuaIPv4Dyn)));
		ctx.pco_req := valueof(ts_PCO_IPv4_DNS_CONT);
		f_pdp_ctx_act(ctx);

		f_PCO_ensure_no_duplicates(ctx.pco_neg);
		/* verify PCO contains both primary and secondary DNS */
		var OCT4 ggsn_ip4_dns1 := f_inet_addr(m_ggsn_ip4_dns1);
		if (not match(f_PCO_extract_proto(ctx.pco_neg, '000d'O, 1), ggsn_ip4_dns1)) {
				setverdict(fail, "Primary DNS IPv4 PCO option not found");
		}

		var OCT4 ggsn_ip4_dns2 := f_inet_addr(m_ggsn_ip4_dns2);
		if (not match(f_PCO_extract_proto(ctx.pco_neg, '000d'O, 2), ggsn_ip4_dns2)) {
				setverdict(fail, "Secondary DNS IPv4 PCO option not found");
		}

		f_pdp_ctx_del(ctx, '1'B);
	}

	/* Test PDP context activation for dynamic IPv4 EUA.
	   Test we can send ICMPv6 ping over GTPU to DNS server. */
	testcase TC_pdp4_act_deact_gtpu_access() runs on GT_CT {
		f_init();
		var PdpContext ctx := valueof(t_DefinePDP(f_rnd_imsi('26242'H), '1234'O, c_ApnInternet, valueof(t_EuaIPv4Dyn)));
		ctx.pco_req := valueof(ts_PCO_IPv4_DNS_CONT);
		f_pdp_ctx_act(ctx);

		f_PCO_ensure_no_duplicates(ctx.pco_neg);
		var OCT4 dns1_addr := f_PCO_extract_proto(ctx.pco_neg, '000d'O);

		/* Check if we can use valid global src addr, should work */
		var OCT4 saddr := ctx.eua.endUserAddress.endUserAddressIPv4.ipv4_address;
		f_send_gtpu(ctx, f_gen_icmpv4_echo(saddr, dns1_addr));
		f_wait_icmp4_echo_reply(ctx);

		/* Assert that packets with wrong global src addr are dropped by GGSN */
		var OCT4 saddr_wrong := substr(saddr, 0, 3) & (saddr[3] xor4b '11'O);
		f_send_gtpu(ctx, f_gen_icmpv4_echo(saddr_wrong, dns1_addr));
		f_wait_gtpu_fail(ctx);

		/* Send an IPv6 RA to APN4, should fail (packet dropped) */
		var OCT16 saddr_v6 := f_inet6_addr("fde4:8dba:82e1:2000:1:2:3:4");
		f_send_gtpu(ctx, f_gen_icmpv6_router_solicitation(saddr_v6));
		f_wait_gtpu_fail(ctx);
		f_pdp_ctx_del(ctx, '1'B);
	}

	/* Helper function for tests below. */
	function f_pdp4_clients_interact() runs on GT_CT {
		f_init();
		var PdpContext ctxA := valueof(t_DefinePDP(f_rnd_imsi('26242'H), '1234'O, c_ApnInternet, valueof(t_EuaIPv4Dyn)));
		var PdpContext ctxB := valueof(t_DefinePDP(f_rnd_imsi('26242'H), '1234'O, c_ApnInternet, valueof(t_EuaIPv4Dyn)));
		f_pdp_ctx_act(ctxA);
		f_pdp_ctx_act(ctxB);
		var OCT4 addrA := ctxA.eua.endUserAddress.endUserAddressIPv4.ipv4_address;
		var OCT4 addrB := ctxB.eua.endUserAddress.endUserAddressIPv4.ipv4_address;
		f_send_gtpu(ctxA, f_gen_icmpv4_echo(addrA, addrB));
		f_wait_icmp4_echo_request(ctxB);

		f_pdp_ctx_del(ctxA, '1'B);
		f_pdp_ctx_del(ctxB, '1'B);
	}

	/* Validate if different clients (pdp ctx) can reach one another through GGSN. */
	testcase TC_pdp4_clients_interact_with_txseq() runs on GT_CT {
		use_gtpu_txseq := true;
		f_pdp4_clients_interact();
	}

	/* Validate if different clients (pdp ctx) can reach one another through GGSN (without Tx sequence number). */
	testcase TC_pdp4_clients_interact_without_txseq() runs on GT_CT {
		use_gtpu_txseq := false;
		f_pdp4_clients_interact();
	}

	testcase TC_echo_req_resp() runs on GT_CT {
		f_init();
		f_send_gtpc(ts_GTPC_PING(g_peer_c, g_c_seq_nr));
		T_default.start;
		alt {
			[] GTPC.receive(tr_GTPC_PONG(g_peer_c)) { setverdict(pass); };
			[] GTPC.receive { repeat; };
			[] T_default.timeout { setverdict(fail); }
		}
		T_default.stop;
	}

	/* Test if the parser can cope with PCO that only contain either a
	 * single primary DNS or a secondary DNS. */
	testcase TC_pdp4_act_deact_with_single_dns() runs on GT_CT {

		/* Note: an unpatched osmo-ggsn version will enter an endless-loop when
		 * the test is executed.
		 * see also: Change-Id Icffde89f9bc5d8fcadf6e2dd6c0b4de03440edd5 and OS#3288 */

		f_init();
		var PdpContext ctx := valueof(t_DefinePDP(f_rnd_imsi('26242'H), '1234'O, c_ApnInternet, valueof(t_EuaIPv4Dyn)));
		var OCT4 ggsn_ip4_dns1 := f_inet_addr(m_ggsn_ip4_dns1);
		var OCT4 ggsn_ip4_dns2 := f_inet_addr(m_ggsn_ip4_dns2);
		var octetstring pco_neg_dns;
		var octetstring pco_neg_dns_expected;

		/* PCO with primary DNS only */
		ctx.pco_req := valueof(ts_PCO_IPv4_PRI_DNS_IPCP);
		f_pdp_ctx_act(ctx);
		f_PCO_ensure_no_duplicates(ctx.pco_neg);
		pco_neg_dns := f_PCO_extract_proto(ctx.pco_neg, '8021'O, 1);
		pco_neg_dns_expected := '0200000A8106'O & ggsn_ip4_dns1
		/* Note: The prepended hex bytes encode the following information:
		 * 0x02   = Configuration ACK
		 * 0x00   = Identifier
		 * 0x000a = Length
		 * 0x81   = Type (Primary DNS Server Address)
		 * 0x06   = Length
		 * (4 byte IP-Address appended) */
		if (not match(pco_neg_dns, pco_neg_dns_expected)) {
			setverdict(fail, "Primary DNS IPv4 PCO option not found");
		}
		f_pdp_ctx_del(ctx, '1'B);

		/* PCO with secondary DNS only */
		ctx.pco_req := valueof(ts_PCO_IPv4_SEC_DNS_IPCP);
		f_pdp_ctx_act(ctx);
		pco_neg_dns := f_PCO_extract_proto(ctx.pco_neg, '8021'O, 1);
		pco_neg_dns_expected := '0200000A8306'O & ggsn_ip4_dns2
		if (not match(pco_neg_dns, pco_neg_dns_expected)) {
			setverdict(fail, "Secondary DNS IPv4 PCO option not found");
		}
		f_pdp_ctx_del(ctx, '1'B);
	}

	/* Test if the parser can cope with PCO that contains primary and secondary DNS in a separate IPCP container.
	 * Note: an unpatched osmo-ggsn version will enter an endless-loop when the test is run
	 * see Change-Id Icffde89f9bc5d8fcadf6e2dd6c0b4de03440edd5 and OS#3288. */
	testcase TC_pdp4_act_deact_with_separate_dns() runs on GT_CT {

		/* Note: an unpatched osmo-ggsn version will enter an endless-loop when
		 * the test is executed.
		 * see also: Change-Id Icffde89f9bc5d8fcadf6e2dd6c0b4de03440edd5 and OS#3288 */

		f_init();
		var PdpContext ctx := valueof(t_DefinePDP(f_rnd_imsi('26242'H), '1234'O, c_ApnInternet, valueof(t_EuaIPv4Dyn)));
		var OCT4 ggsn_ip4_dns1 := f_inet_addr(m_ggsn_ip4_dns1);
		var OCT4 ggsn_ip4_dns2 := f_inet_addr(m_ggsn_ip4_dns2);
		var octetstring pco_neg_dns;
		var octetstring pco_neg_dns_expected;

		ctx.pco_req := valueof(ts_PCO_IPv4_SEPARATE_DNS_IPCP);
		f_pdp_ctx_act(ctx);

		/* Check if primary DNS is contained */
		pco_neg_dns := f_PCO_extract_proto(ctx.pco_neg, '8021'O, 1);
		pco_neg_dns_expected := '0200000A8106'O & ggsn_ip4_dns1
		if (not match(pco_neg_dns, pco_neg_dns_expected)) {
			setverdict(fail, "Primary DNS IPv4 PCO option not found");
		}

		/* Check if secondary DNS is contained */
		/* This used to fail due to a bug in osmo-ggsn, see OS#3381 */
		pco_neg_dns := f_PCO_extract_proto(ctx.pco_neg, '8021'O, 2);
		pco_neg_dns_expected := '0200000A8306'O & ggsn_ip4_dns2
		if (not match(pco_neg_dns, pco_neg_dns_expected)) {
			setverdict(fail, "Secondary DNS IPv4 PCO option not found");
		}
		f_pdp_ctx_del(ctx, '1'B);
	}

	/* Test IPv4v6 context activation for dynamic IPv4v6 EUA without DNS request */
	testcase TC_pdp46_act_deact() runs on GT_CT {
		f_init();
		var PdpContext ctx := valueof(t_DefinePDP(f_rnd_imsi('26242'H), '1234'O, c_ApnInet46, valueof(t_EuaIPv4Dynv6Dyn)));
		f_pdp_ctx_act(ctx);
		f_pdp_ctx_del(ctx, '1'B);
	}

	/* Test PDP context activation for dynamic IPv4v6 EUA with IPv4 DNS in IPCP */
	testcase TC_pdp46_act_deact_ipcp() runs on GT_CT {
		f_init();
		var OCT4 ggsn_ip4_dns1 := f_inet_addr(m_ggsn_ip4_dns1);
		var OCT4 ggsn_ip4_dns2 := f_inet_addr(m_ggsn_ip4_dns2);
		var PdpContext ctx := valueof(t_DefinePDP(f_rnd_imsi('26242'H), '1234'O, c_ApnInet46, valueof(t_EuaIPv4Dynv6Dyn)));
		ctx.pco_req := valueof(ts_PCO_IPv4_DNS_IPCP);
		f_pdp_ctx_act(ctx);
		f_PCO_ensure_no_duplicates(ctx.pco_neg);
		/* verify IPCP is at all contained */
		if (not match(ctx.pco_neg, tr_PCO_Contains('8021'O))) {
			setverdict(fail, "IPCP not found in PCO");
		}
		f_PCO_ensure_no_duplicates(ctx.pco_neg);
		/* verify IPCP contains both primary and secondary IPv4 DNS */
		var IpcpPacket ipcp := dec_IpcpPacket(f_PCO_extract_proto(ctx.pco_neg, '8021'O));
		if (not match(ipcp, tr_IPCP_Ack_DNS(0, ggsn_ip4_dns1, ggsn_ip4_dns2))) {
			if (not match(ipcp, tr_IPCP_Ack_DNS(0))) {
				setverdict(fail, "Primary/Secondary DNS PCO IPCP option not found");
			} else {
				setverdict(fail, "Primary/Secondary DNS PCO IPCP option found but not matching expected values");
			}
		}
		f_pdp_ctx_del(ctx, '1'B);
	}

	/* Test PDP context activation for dynamic IPv4v6 EUA with IPv6 DNS in PCO and router solicitation/advertisement */
	testcase TC_pdp46_act_deact_icmp6() runs on GT_CT {
		f_init();
		var PdpContext ctx := valueof(t_DefinePDP(f_rnd_imsi('26242'H), '1234'O, c_ApnInet46, valueof(t_EuaIPv4Dynv6Dyn)));
		ctx.pco_req := valueof(ts_PCO_IPv6_DNS);
		f_pdp_ctx_act(ctx);

		f_send_gtpu(ctx, f_icmpv6_rs_for_pdp46(ctx));
		f_wait_rtr_adv(ctx);
		f_send_gtpu(ctx, f_gen_icmpv6_neigh_solicit_for_pdp46(ctx));

		f_pdp_ctx_del(ctx, '1'B);
	}

	/* Test IPv4v6 context activation for dynamic IPv4v6 EUA with request of IPv4 DNS in PCO */
	testcase TC_pdp46_act_deact_pcodns4() runs on GT_CT {
		f_init();

		var PdpContext ctx := valueof(t_DefinePDP(f_rnd_imsi('26242'H), '1234'O, c_ApnInet46, valueof(t_EuaIPv4Dynv6Dyn)));
		ctx.pco_req := valueof(ts_PCO_IPv4_DNS_CONT);
		f_pdp_ctx_act(ctx);

		f_PCO_ensure_no_duplicates(ctx.pco_neg);
		/* verify PCO contains both primary and secondary IPv4 DNS */
		var OCT4 ggsn_ip4_dns1 := f_inet_addr(m_ggsn_ip4_dns1);
		if (not match(f_PCO_extract_proto(ctx.pco_neg, '000d'O, 1), ggsn_ip4_dns1)) {
				setverdict(fail, "Primary DNS IPv4 PCO option not found");
		}

		var OCT4 ggsn_ip4_dns2 := f_inet_addr(m_ggsn_ip4_dns2);
		if (not match(f_PCO_extract_proto(ctx.pco_neg, '000d'O, 2), ggsn_ip4_dns2)) {
				setverdict(fail, "Secondary DNS IPv4 PCO option not found");
		}

		f_pdp_ctx_del(ctx, '1'B);
	}

	/* Test IPv4v6 context activation for dynamic IPv4v6 EUA with request of IPv6 DNS in PCO */
	testcase TC_pdp46_act_deact_pcodns6() runs on GT_CT {
		f_init();

		var PdpContext ctx := valueof(t_DefinePDP(f_rnd_imsi('26242'H), '1234'O, c_ApnInet46, valueof(t_EuaIPv4Dynv6Dyn)));
		ctx.pco_req := valueof(ts_PCO_IPv6_DNS);
		f_pdp_ctx_act(ctx);

		f_PCO_ensure_no_duplicates(ctx.pco_neg);
		/* verify PCO contains both primary and secondary IPv6 DNS */
		var OCT4 ggsn_ip6_dns1 := f_inet6_addr(m_ggsn_ip6_dns1);
		if (not match(f_PCO_extract_proto(ctx.pco_neg, '0003'O, 1), ggsn_ip6_dns1)) {
				setverdict(fail, "Primary DNS IPv6 PCO option not found");
		}

		var OCT4 ggsn_ip6_dns2 := f_inet6_addr(m_ggsn_ip6_dns2);
		if (not match(f_PCO_extract_proto(ctx.pco_neg, '0003'O, 2), ggsn_ip6_dns2)) {
				setverdict(fail, "Secondary DNS IPv6 PCO option not found");
		}

		f_pdp_ctx_del(ctx, '1'B);
	}

	/* Test PDP context activation for dynamic IPv4v6 EUA.
	   Test we can send ICMPv6 ping over GTPU to DNS server. */
	testcase TC_pdp46_act_deact_gtpu_access() runs on GT_CT {
		f_init();
		var PdpContext ctx := valueof(t_DefinePDP(f_rnd_imsi('26242'H), '1234'O, c_ApnInet46, valueof(t_EuaIPv4Dynv6Dyn)));
		ctx.pco_req := valueof(ts_PCO_IPv4_DNS_CONT);
		f_pdp_ctx_act(ctx);

		var OCT4 dns1_addr := f_PCO_extract_proto(ctx.pco_neg, '000d'O);

		/* Check if we can use valid global src addr, should work */
		var OCT4 saddr := ctx.eua.endUserAddress.endUserAddressIPv4andIPv6.ipv4_address;
		f_send_gtpu(ctx, f_gen_icmpv4_echo(saddr, dns1_addr));
		f_wait_icmp4_echo_reply(ctx);

		/* Assert that packets with wrong global src addr are dropped by GGSN */
		var OCT4 saddr_wrong := substr(saddr, 0, 3) & (saddr[3] xor4b '11'O);
		f_send_gtpu(ctx, f_gen_icmpv4_echo(saddr_wrong, dns1_addr));
		f_wait_gtpu_fail(ctx);

		/* Send an IPv6 RA to APN4, should fail (packet dropped) */
		var OCT16 saddr_v6 := f_inet6_addr("fde4:8dba:82e1:2000:1:2:3:4");
		f_send_gtpu(ctx, f_gen_icmpv6_router_solicitation(saddr_v6));
		f_wait_gtpu_fail(ctx);
		f_pdp_ctx_del(ctx, '1'B);
	}

	/* Validate if different clients (pdp ctx) can reach one another through GGSN. */
	testcase TC_pdp46_clients_interact() runs on GT_CT {
		f_init();
		var PdpContext ctxA := valueof(t_DefinePDP(f_rnd_imsi('26242'H), '1234'O, c_ApnInet46, valueof(t_EuaIPv4Dynv6Dyn)));
		var PdpContext ctxB := valueof(t_DefinePDP(f_rnd_imsi('26242'H), '1234'O, c_ApnInet46, valueof(t_EuaIPv4Dynv6Dyn)));
		f_pdp_ctx_act(ctxA);
		f_send_gtpu(ctxA, f_icmpv6_rs_for_pdp46(ctxA));
		f_wait_rtr_adv(ctxA);
		f_send_gtpu(ctxA, f_gen_icmpv6_neigh_solicit_for_pdp46(ctxA));

		f_pdp_ctx_act(ctxB);
		f_send_gtpu(ctxB, f_icmpv6_rs_for_pdp46(ctxB));
		f_wait_rtr_adv(ctxB);
		f_send_gtpu(ctxB, f_gen_icmpv6_neigh_solicit_for_pdp46(ctxB));

		var OCT16 addrA_ll := f_ipv6_link_local(ctxA.eua.endUserAddress.endUserAddressIPv4andIPv6.ipv6_address);
		var OCT16 addrB_ll := f_ipv6_link_local(ctxB.eua.endUserAddress.endUserAddressIPv4andIPv6.ipv6_address);
		var OCT16 addrA_glob := f_ipv6_global(ctxA.eua.endUserAddress.endUserAddressIPv4andIPv6.ipv6_address);
		var OCT16 addrB_glob := f_ipv6_global(ctxB.eua.endUserAddress.endUserAddressIPv4andIPv6.ipv6_address);

		/* Validate if clients can interact using ll addr. */
		f_send_gtpu(ctxA, f_gen_icmpv6_echo(addrA_ll, addrB_ll));
		f_wait_gtpu_fail(ctxB);

		/* Validate if clients can interact using global addr. */
		f_send_gtpu(ctxA, f_gen_icmpv6_echo(addrA_glob, addrB_glob));
		f_wait_gtpu_fail(ctxB);

		f_pdp_ctx_del(ctxA, '1'B);
		f_pdp_ctx_del(ctxB, '1'B);
	}

	/* Test IPv4v6 context activation for dynamic IPv4v6 EUA on a v4-only APN */
	testcase TC_pdp46_act_deact_apn4() runs on GT_CT {
		f_init();
		/* A typical MS first attempts v4v6, and if rejected, then tries v4 and v6 separetly */
		var PdpContext ctx46 := valueof(t_DefinePDP(f_rnd_imsi('26242'H), '1234'O, c_ApnInternet, valueof(t_EuaIPv4Dynv6Dyn)));
		f_pdp_ctx_act(ctx46, 'DC'O); /* Cause: Unknown PDP address or PDP type */

		var PdpContext ctx4 := valueof(t_DefinePDP(f_rnd_imsi('26242'H), '1234'O, c_ApnInternet, valueof(t_EuaIPv4Dyn)));
		f_pdp_ctx_act(ctx4, '80'O); /* Normal accept cause */

		var PdpContext ctx6 := valueof(t_DefinePDP(f_rnd_imsi('26242'H), '1234'O, c_ApnInternet, valueof(t_EuaIPv6Dyn)));
		f_pdp_ctx_act(ctx6, 'DC'O); /* Cause: Unknown PDP address or PDP type */

		f_pdp_ctx_del(ctx4, '1'B);
	}

	/* Validate if 2nd CtxCreateReq with increased Recovery IE causes ggsn to drop 1st one (while keeping 2nd one). */
	testcase TC_pdp_act2_recovery() runs on GT_CT {
		var Gtp1cUnitdata ud;
		var default d;
		var boolean ctxA_deleted := false;
		var boolean ctxB_created := false;

		f_init();
		var PdpContext ctxA := valueof(t_DefinePDP(f_rnd_imsi('26242'H), '1234'O, c_ApnInternet, valueof(t_EuaIPv4Dyn)));
		var PdpContext ctxB := valueof(t_DefinePDP(f_rnd_imsi('26242'H), '1234'O, c_ApnInternet, valueof(t_EuaIPv4Dyn)));
		f_pdp_ctx_act(ctxA);

		g_restart_ctr := int2oct(oct2int(g_restart_ctr) + 1, 1);

		log("sending 2nd CreatePDP (recovery increased)");
		f_send_gtpc(ts_GTPC_CreatePDP(g_peer_c, g_c_seq_nr, ctxB.imsi, g_restart_ctr,
						  ctxB.teid, ctxB.teic, ctxB.nsapi, ctxB.eua, ctxB.apn,
						  g_sgsn_ip_c, g_sgsn_ip_u, ctxB.msisdn, ctxB.pco_req));
		T_default.start;
		d := activate(pingpong());
		alt {
			[] GTPC.receive(tr_GTPC_MsgType(g_peer_c, createPDPContextResponse, ctxB.teic)) -> value ud {
				f_handle_create_req(ctxB, ud);
				if (not ctxB_created) {
					ctxB_created := true;
					setverdict(pass);
				} else {
					setverdict(fail, "Repeated createPDPContextResponse(ctxB)");
				}

				if (not ctxA_deleted) {
					repeat;
				}
			}
			[] GTPC.receive(tr_GTPC_MsgType(g_peer_c, deletePDPContextRequest, ctxA.teic)) -> value ud {
				if (ispresent(ud.gtpc.gtpc_pdu.deletePDPContextRequest.tearDownIndicator)) {
					setverdict(pass);
				} else {
					setverdict(fail);
				}

				if (not ctxA_deleted) {
					ctxA_deleted := true;
					setverdict(pass);
				} else {
					setverdict(fail, "Repeated deletePDPContextRequest(ctxA)");
				}

				if (not ctxB_created) {
					repeat;
				}
			}
			[] GTPC.receive(tr_GTPC_MsgType(g_peer_c, deletePDPContextRequest, ctxB.teic)) -> value ud {
				setverdict(fail, "GGSN dropping still valid pdp ctx");
			}
		}
		deactivate(d);
		T_default.stop;

		f_pdp_ctx_del(ctxB, '1'B);
	}


	/* Send a duplicate echo req. osmo-ggsn maintains a queue for sent
	   responses (60 seconds): If same delete req is sent and duplicate is
	   detected, saved duplicate response should be sent back. */
	testcase TC_act_deact_retrans_duplicate() runs on GT_CT {
		f_init();
		var PdpContext ctx := valueof(t_DefinePDP(f_rnd_imsi('26242'H), '1234'O, c_ApnInternet, valueof(t_EuaIPv4Dyn)));
		f_pdp_ctx_act(ctx);
		f_pdp_ctx_del(ctx, '1'B);
		/* leave some time in between to make sure retransmit response queue keeps packets for a while */
		f_sleep(1.0);
		/* g_c_seq_nr was increased during f_pdp_ctx_del(), we want a
		   duplicate. If it was not a duplicate, osmo-ggsn would answer
		   with a failure since that PDP ctx was already deleted. */
		g_c_seq_nr := g_c_seq_nr - 1;
		f_pdp_ctx_del(ctx, '1'B);

		/* Now send a new pdp ctx del (increased seqnum). It should fail with cause "non-existent": */
		var OCT1 cause_nonexistent := 'C0'O;
		f_pdp_ctx_del(ctx, '1'B, cause_nonexistent);
	}

	/* Activate PDP context + trigger Recovery procedure through EchoResp */
	testcase TC_pdp_act_restart_ctr_echo() runs on GT_CT {
		var Gtp1cUnitdata ud;
		g_use_echo := true;
		f_init();
		var PdpContext ctx := valueof(t_DefinePDP(f_rnd_imsi('26242'H), '1234'O, c_ApnInternet, valueof(t_EuaIPv4Dyn)));
		f_pdp_ctx_act(ctx);

		/* Wait to receive echo request and send initial Restart counter */
		GTPC.receive(tr_GTPC_PING(?)) -> value ud {
			var uint16_t seq := oct2int(ud.gtpc.opt_part.sequenceNumber);
			GTPC.send(ts_GTPC_PONG(ud.peer, seq, g_restart_ctr));
		};

		/* Wait to receive second echo request and send incremented Restart
		   counter. This will fake a restarted SGSN, and pdp ctx allocated
		   should be released by GGSN */
		g_restart_ctr := int2oct(oct2int(g_restart_ctr) + 1, 1);
		GTPC.receive(tr_GTPC_PING(?)) -> value ud {
			var uint16_t seq := oct2int(ud.gtpc.opt_part.sequenceNumber);
			GTPC.send(ts_GTPC_PONG(ud.peer, seq, g_restart_ctr));
		};
		f_pdp_ctx_exp_del_req(ctx, omit, true);
		setverdict(pass);
	}

	control {
		execute(TC_pdp4_act_deact());
		execute(TC_pdp4_act_deact_ipcp());
		execute(TC_pdp4_act_deact_ipcp_pap_broken());
		execute(TC_pdp4_act_deact_pcodns());
		execute(TC_pdp4_act_deact_gtpu_access());
		execute(TC_pdp4_clients_interact_with_txseq());
		execute(TC_pdp4_clients_interact_without_txseq());
		execute(TC_pdp4_act_deact_with_single_dns());
		execute(TC_pdp4_act_deact_with_separate_dns());

		execute(TC_pdp6_act_deact());
		execute(TC_pdp6_act_deact_pcodns());
		execute(TC_pdp6_act_deact_icmp6());
		execute(TC_pdp6_act_deact_gtpu_access());
		execute(TC_pdp6_clients_interact());

		execute(TC_pdp46_act_deact());
		execute(TC_pdp46_act_deact_ipcp());
		execute(TC_pdp46_act_deact_icmp6());
		execute(TC_pdp46_act_deact_pcodns4());
		execute(TC_pdp46_act_deact_pcodns6());
		execute(TC_pdp46_act_deact_gtpu_access());
		execute(TC_pdp46_clients_interact());
		execute(TC_pdp46_act_deact_apn4());

		execute(TC_echo_req_resp());
		execute(TC_pdp_act2_recovery());
		execute(TC_act_deact_retrans_duplicate());

		execute(TC_pdp_act_restart_ctr_echo());
	}
}
