module MSC_Tests {

/* Osmocom MSC test suite in in TTCN-3
 * (C) 2017-2019 Harald Welte <laforge@gnumonks.org>
 * (C) 2018-2019 sysmocom - s.f.m.c. GmbH
 * (C) 2018-2019 Vadim Yanitskiy <axilirator@gmail.com>
 * 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
 */

friend module MSC_Tests_Iu;
friend module MSC_Tests_ASCI;

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

import from M3UA_Types all;
import from M3UA_Emulation all;

import from MTP3asp_Types all;
import from MTP3asp_PortType all;

import from SCCPasp_Types all;
import from SCCP_Types all;
import from SCCP_Emulation all;
import from SCCP_Adapter all;

import from SCTPasp_Types all;
import from SCTPasp_PortType all;

import from Osmocom_CTRL_Functions all;
import from Osmocom_CTRL_Types all;
import from Osmocom_CTRL_Adapter all;

import from TELNETasp_PortType all;
import from Osmocom_VTY_Functions all;

import from MNCC_Emulation all;
import from MNCC_Types all;

import from MGCP_Emulation all;
import from MGCP_Types all;
import from MGCP_Templates all;
import from SDP_Types all;
import from SDP_Templates all;

import from GSUP_Types all;
import from GSUP_Templates all;
import from GSUP_Emulation all;
import from IPA_Emulation all;

import from BSSAP_Types all;
import from RAN_Adapter all;
import from BSSAP_CodecPort all;
import from BSSMAP_Templates all;
import from RAN_Emulation all;
import from BSC_ConnectionHandler all;
import from RANAP_Templates all;

import from SGsAP_Templates all;
import from SGsAP_Types all;
import from SGsAP_Emulation all;

import from MobileL3_Types all;
import from MobileL3_CommonIE_Types all;
import from MobileL3_SMS_Types all;
import from L3_Templates all;
import from L3_Common all;

import from SMPP_Types all;
import from SMPP_Templates all;
import from SMPP_Emulation all;

import from SCCP_Templates all;

import from StatsD_Types all;
import from StatsD_CodecPort all;
import from StatsD_CodecPort_CtrlFunct all;
import from StatsD_Checker all;

import from SS_Types all;
import from SS_Templates all;
import from USSD_Helpers all;
import from DNS_Helpers all;

import from TCCConversion_Functions all;

const integer NUM_BSC := 3;

/* Needed for SGsAP SMS */
import from MobileL3_SMS_Types all;

type component MTC_CT extends CTRL_Adapter_CT, StatsD_ConnHdlr {
	var boolean g_initialized := false;

	var RAN_Adapter g_bssap[NUM_BSC];

	/* no 'adapter_CT' for MNCC or GSUP */
	var MNCC_Emulation_CT vc_MNCC;
	var MGCP_Emulation_CT vc_MGCP;
	var GSUP_Emulation_CT vc_GSUP;
	var IPA_Emulation_CT vc_GSUP_IPA;
	var SMPP_Emulation_CT vc_SMPP;

	var SGsAP_Emulation_CT vc_SGsAP;
	port SGsAP_PT SGsAP_UNIT;

	/* only to get events from IPA underneath GSUP */
	port IPA_CTRL_PT GSUP_IPA_EVENT;
	/* VTY to MSC: */
	port TELNETasp_PT MSCVTY;
	/* VTY to STP: */
	port TELNETasp_PT STPVTY;

	/* StatsD */
	var StatsD_Checker_CT vc_STATSD;
	var float g_statd_timeout := 5.0;

	/* A port to directly send BSSAP messages. This port is used for
	 * tests that require low level access to sen arbitrary BSSAP
	 * messages. Run f_init_bssap_direct() to connect and initialize */
	port BSSAP_CODEC_PT BSSAP_DIRECT;

	/* When BSSAP messages are directly sent, then the connection
	 * handler is not active, which means that also no guard timer is
	 * set up. The following timer will serve as a replacement */
	timer Tguard_direct := 60.0;

	/* Configure T(tias) over VTY, seconds */
	var integer g_msc_sccp_timer_ias :=  7 * 60;
	/* Configure T(tiar) over VTY, seconds */
	var integer g_msc_sccp_timer_iar := 15 * 60;
}

modulepar {
	/* remote parameters of IUT */
	charstring mp_msc_ip := "127.0.0.1";
	integer mp_msc_ctrl_port := 4255;
	integer mp_msc_vty_port := 4254;
	/* port number to which to listen for STATSD metrics */
	integer mp_msc_statsd_port := 8125;

	/* local parameters of emulated HLR */
	boolean mp_mm_info := false;
	charstring mp_hlr_ip := "127.0.0.1";
	integer mp_hlr_port := 4222;
	charstring mp_mgw_ip := "127.0.0.1";
	integer mp_mgw_port := 2427;

	/* Address where we listen for STATSD metrics */
	charstring mp_local_statsd_ip := "127.0.0.1";
	charstring mp_statsd_prefix := "TTCN3.";


	charstring mp_msc_mncc := "/tmp/mncc";

	integer mp_msc_smpp_port := 2775;
	charstring mp_smpp_system_id := "msc_tester";
	charstring mp_smpp_password := "osmocom1";
	charstring mp_mme_name := "mmec01.mmegi0001.mme.epc.mnc070.mcc901.3gppnetwork.org";
	charstring mp_vlr_name := "vlr.example.net";
	integer mp_bssap_reset_retries := 1;

	RAN_Configurations mp_bssap_cfg := { /* Set in MSC_Tests.default */ };
}

/* altstep for the global guard timer (only used when BSSAP_DIRECT
 * is used for communication */
private altstep as_Tguard_direct() runs on MTC_CT {
	[] Tguard_direct.timeout {
		setverdict(fail, "Tguard timeout");
		mtc.stop;
	}
}

private altstep as_optional_cc_rel(CallParameters cpars, boolean respond := false) runs on BSC_ConnHdlr {
	[] RAN_CONN.receive(tr_PDU_DTAP_MT(tr_ML3_MT_CC_RELEASE(cpars.transaction_id))) {
		if (respond) {
			var BIT1 tid_remote := '1'B;
			if (cpars.mo_call) {
				tid_remote := '0'B;
			}
			RAN_CONN.send(ts_PDU_DTAP_MO(ts_ML3_MO_CC_REL_COMPL(cpars.transaction_id, tid_remote)));
		}
		repeat;
	}
}

function f_init_smpp(charstring id) runs on MTC_CT {
	id := id & "-SMPP";
	var EsmePars pars := {
		mode := MODE_TRANSCEIVER,
		bind := {
			system_id := mp_smpp_system_id,
			password := mp_smpp_password,
			system_type := "MSC_Tests",
			interface_version := hex2int('34'H),
			addr_ton := unknown,
			addr_npi := unknown,
			address_range := ""
		},
		esme_role := true
	}

	vc_SMPP := SMPP_Emulation_CT.create(id);
	map(vc_SMPP:SMPP_PORT, system:SMPP_PORT);
	vc_SMPP.start(SMPP_Emulation.main_client(pars, mp_msc_ip, mp_msc_smpp_port, "", 0));
}


function f_init_mncc(charstring id) runs on MTC_CT {
	id := id & "-MNCC";
	var MnccOps ops := {
		create_cb := refers(MNCC_Emulation.ExpectedCreateCallback),
		unitdata_cb := refers(MNCC_Emulation.DummyUnitdataCallback)
	}

	vc_MNCC := MNCC_Emulation_CT.create(id);
	map(vc_MNCC:MNCC, system:MNCC_CODEC_PT);
	vc_MNCC.start(MNCC_Emulation.main(ops, id, mp_msc_mncc));
}

function f_init_mgcp(charstring id) runs on MTC_CT {
	id := id & "-MGCP";
	var MGCPOps ops := {
		create_cb := refers(MGCP_Emulation.ExpectedCreateCallback),
		unitdata_cb := refers(MGCP_Emulation.DummyUnitdataCallback)
	}
	var MGCP_conn_parameters pars := {
		callagent_ip := mp_msc_ip,
		callagent_udp_port := -1,
		mgw_ip := mp_mgw_ip,
		mgw_udp_port := mp_mgw_port,
		multi_conn_mode := false
	}

	vc_MGCP := MGCP_Emulation_CT.create(id);
	map(vc_MGCP:MGCP, system:MGCP_CODEC_PT);
	vc_MGCP.start(MGCP_Emulation.main(ops, pars, id));
}

function ForwardUnitdataCallback(PDU_SGsAP msg)
runs on SGsAP_Emulation_CT return template PDU_SGsAP {
	SGsAP_CLIENT.send(msg);
	return omit;
}

function f_init_sgsap(charstring id) runs on MTC_CT {
	id := id & "-SGsAP";
	var SGsAPOps ops := {
		create_cb := refers(SGsAP_Emulation.ExpectedCreateCallback),
		unitdata_cb := refers(ForwardUnitdataCallback)
	}
	var SGsAP_conn_parameters pars := {
		remote_ip := mp_msc_ip,
		remote_sctp_port := 29118,
		local_ip := "",
		local_sctp_port := -1
	}

	vc_SGsAP := SGsAP_Emulation_CT.create(id);
	map(vc_SGsAP:SGsAP, system:SGsAP_CODEC_PT);
	connect(vc_SGsAP:SGsAP_UNIT, self:SGsAP_UNIT);
	vc_SGsAP.start(SGsAP_Emulation.main(ops, pars, id));

	SGsAP_UNIT.receive(SGsAPEM_Event:{up_down:=SGsAPEM_EVENT_UP});
}


function f_init_gsup(charstring id) runs on MTC_CT {
	id := id & "-GSUP";
	var GsupOps ops := {
		create_cb := refers(GSUP_Emulation.ExpectedCreateCallback)
	}

	vc_GSUP_IPA := IPA_Emulation_CT.create(id & "-IPA");
	vc_GSUP := GSUP_Emulation_CT.create(id);

	map(vc_GSUP_IPA:IPA_PORT, system:IPA_CODEC_PT);
	connect(vc_GSUP:GSUP, vc_GSUP_IPA:IPA_GSUP_PORT);
	/* we use this hack to get events like ASP_IPA_EVENT_UP */
	connect(vc_GSUP_IPA:IPA_CTRL_PORT, self:GSUP_IPA_EVENT);

	vc_GSUP.start(GSUP_Emulation.main(ops, id));
	vc_GSUP_IPA.start(IPA_Emulation.main_server(mp_hlr_ip, mp_hlr_port));

	/* wait for incoming connection to GSUP port before proceeding */
	timer T := 10.0;
	T.start;
	alt {
		[] GSUP_IPA_EVENT.receive(tr_ASP_IPA_EV(ASP_IPA_EVENT_UP)) { }
		[] T.timeout {
			setverdict(fail, "No connection to GSUP Port");
			mtc.stop
		}
	}
}

friend function f_init_vty_stp() runs on MTC_CT {
	if (STPVTY.checkstate("Mapped")) {
		/* skip initialization if already executed once */
		return;
	}
	map(self:STPVTY, system:STPVTY);
	f_vty_set_prompts(STPVTY, prompt_prefix := "OsmoSTP");
	f_vty_transceive(STPVTY, "enable");
}

friend function f_vty_stp_msc_asp_cmd(charstring cmd) runs on MTC_CT
{
	var charstring asp_name;
	var charstring loc_port;
	var charstring rem_port;
	var charstring asp_proto;
	if (mp_bssap_cfg[0].transport == BSSAP_TRANSPORT_AoIP) {
		asp_name := "msc0-0";
		loc_port := int2str(1905);
		rem_port := int2str(2905);
		asp_proto := "m3ua";
	} else {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail, "osmo-stp not used in SCCPLite!");
	}
	var charstring asp_node := "asp " & asp_name & " " & loc_port & " " & rem_port & " " & asp_proto;
	f_vty_config2(STPVTY, {"cs7 instance 0", asp_node}, cmd);
}

function f_init(integer num_bsc := 1, boolean sgsap := false, boolean gsup := true, boolean osmux := false) runs on MTC_CT {

	if (g_initialized == true) {
		return;
	}
	g_initialized := true;

	if (num_bsc > NUM_BSC) {
		testcase.stop("excess number of BSC instances requested");
	}

	f_ipa_ctrl_start_client(mp_msc_ip, mp_msc_ctrl_port);

	map(self:MSCVTY, system:MSCVTY);
	f_vty_set_prompts(MSCVTY);
	f_vty_transceive(MSCVTY, "enable");

	/* set some defaults */
	f_vty_config(MSCVTY, "network", "authentication optional");
	f_vty_config(MSCVTY, "msc", "assign-tmsi");
	f_vty_config(MSCVTY, "msc", "check-imei-rqd 0");
	f_vty_config(MSCVTY, "network", "encryption a5 0");
	f_vty_config(MSCVTY, "cs7 instance 0", "sccp-timer ias " & int2str(g_msc_sccp_timer_ias));
	f_vty_config(MSCVTY, "cs7 instance 0", "sccp-timer iar " & int2str(g_msc_sccp_timer_iar));
	if (osmux) {
		f_vty_config(MSCVTY, "msc", "osmux on");
	} else {
		f_vty_config(MSCVTY, "msc", "osmux off");
	}

	/* Configure the MGCP timeout so that a failure to set up all RTP streams triggers within the time that we keep
	 * an otherwise established call open. */
	f_vty_config(MSCVTY, "msc", "timer mgw X2 3");

	for (var integer i := 0; i < num_bsc; i := i + 1) {
		if (isbound(mp_bssap_cfg[i])) {
			var RanOps ranops := BSC_RanOps;
			ranops.use_osmux := osmux;
			ranops.bssap_reset_retries := mp_bssap_reset_retries;
			f_ran_adapter_init(g_bssap[i], mp_bssap_cfg[i], "MSC_Test_" & int2str(i), ranops);
			f_ran_adapter_start(g_bssap[i]);
		} else {
			testcase.stop("missing BSSAP configuration");
		}
	}

	f_init_mncc("MSC_Test");
	f_init_mgcp("MSC_Test");

	if (gsup == true) {
		f_init_gsup("MSC_Test");
	}
	f_init_smpp("MSC_Test");

	if (sgsap == true) {
		f_init_sgsap("MSC_Test");
	}

	f_init_statsd("MSC_Test", vc_STATSD, mp_local_statsd_ip, mp_msc_statsd_port, g_statd_timeout);

}

/* Initialize for a direct connection to BSSAP. This function is an alternative
 * to f_init() when the high level functions of the BSC_ConnectionHandler are
 * not needed. */
function f_init_bssap_direct() runs on MTC_CT {
	f_sccp_adapter_init(g_bssap[0].sccpa, mp_bssap_cfg[0].sccp, "MSC_Test");
	connect(g_bssap[0].sccpa.vc_SCCP:SCCP_SP_PORT, self:BSSAP_DIRECT);

	/* Start guard timer and activate it as default */
	Tguard_direct.start
	activate(as_Tguard_direct());
}

type function void_fn(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr;

/* FIXME: move into BSC_ConnectionHandler? */
function f_init_pars(integer imsi_suffix, boolean sgsap := false, boolean gsup := true, integer ran_idx := 0,
		     boolean ran_is_geran := true, boolean use_osmux := false, OCT4 gsup_sid := '20000101'O,
		     boolean verify_cell_id := true)
runs on MTC_CT return BSC_ConnHdlrPars {
	var BSC_ConnHdlrNetworkPars net_pars := {
		kc_support := '0A'O,	/* A5/1 and A5/3 enabled */
		net_config := { "authentication optional", "encryption a5 0" },
		expect_attach_success := true,
		expect_tmsi := true,
		expect_auth_attempt := false,
		hlr_has_auth_info := true,
		expect_auth := false,
		expect_ciph := false,
		expect_imei := false,
		expect_imei_early := false,
		check_imei_result := OSMO_GSUP_IMEI_RESULT_ACK,
		check_imei_error := false
	};
	var BSC_ConnHdlrPars pars := {
		sccp_addr_own := g_bssap[ran_idx].sccpa.sccp_addr_own,
		sccp_addr_peer := g_bssap[ran_idx].sccpa.sccp_addr_peer,
		cell_id := valueof(ts_CellId_CGI('262'H, '42'H, 23, 42)),
		imei := f_gen_imei(imsi_suffix),
		imsi := f_gen_imsi(imsi_suffix),
		msisdn := f_gen_msisdn(imsi_suffix),
		tmsi := omit,
		cm1 := valueof(ts_CM1),
		cm2 := valueof(ts_CM2_default),
		cm3 := omit,
		vec := omit,
		vec_keep := false,
		net := net_pars,
		send_early_cm := true,
		ipa_ctrl_ip := mp_msc_ip,
		ipa_ctrl_port := mp_msc_ctrl_port,
		ipa_ctrl_enable := true,
		mm_info := mp_mm_info,
		sgsap_enable := sgsap,
		gsup_enable := gsup,
		gsup_sid := gsup_sid,
		ran_idx := ran_idx,
		use_umts_aka := false,
		ran_is_geran := ran_is_geran,
		use_osmux := use_osmux,
		use_ipv6 := false,
		use_csd := false,
		verify_cell_id := verify_cell_id,
		common_id_last_eutran_plmn := omit
	};
	if (not ran_is_geran) {
		pars.use_umts_aka := true;
		pars.net.expect_auth := true;
	}
	return pars;
}

function f_start_handler_create(BSC_ConnHdlrPars pars) runs on MTC_CT return BSC_ConnHdlr {
	var BSC_ConnHdlr vc_conn;
	var charstring id := testcasename() & int2str(pars.ran_idx);

	vc_conn := BSC_ConnHdlr.create(id);

	/* BSSMAP part / A interface */
	connect(vc_conn:RAN_CONN, g_bssap[pars.ran_idx].vc_RAN:CLIENT);
	connect(vc_conn:RAN_CONN_PROC, g_bssap[pars.ran_idx].vc_RAN:PROC);
	/* MNCC part */
	connect(vc_conn:MNCC, vc_MNCC:MNCC_CLIENT);
	connect(vc_conn:MNCC_PROC, vc_MNCC:MNCC_PROC);
	/* MGCP part */
	connect(vc_conn:MGCP, vc_MGCP:MGCP_CLIENT);
	connect(vc_conn:MGCP_PROC, vc_MGCP:MGCP_PROC);
	/* GSUP part */
	if (pars.gsup_enable == true) {
		connect(vc_conn:GSUP, vc_GSUP:GSUP_CLIENT);
		connect(vc_conn:GSUP_PROC, vc_GSUP:GSUP_PROC);
	}
	/* SMPP part */
	connect(vc_conn:SMPP, vc_SMPP:SMPP_CLIENT);
	connect(vc_conn:SMPP_PROC, vc_SMPP:SMPP_PROC);
	/* SGs part */
	if (pars.sgsap_enable == true) {
		connect(vc_conn:SGsAP, vc_SGsAP:SGsAP_CLIENT);
		connect(vc_conn:SGsAP_PROC, vc_SGsAP:SGsAP_PROC);
	}
	return vc_conn;
}

function f_start_handler_run(BSC_ConnHdlr vc_conn, void_fn fn, BSC_ConnHdlrPars pars) runs on MTC_CT {
	var charstring id := testcasename() & int2str(pars.ran_idx);
	/* We cannot use vc_conn.start(f_init_handler(fn, id, pars)); as we cannot have
	 * a stand-alone 'derefers()' call, see https://www.eclipse.org/forums/index.php/t/1091364/ */
	vc_conn.start(derefers(fn)(id, pars));
}

function f_start_handler_with_pars(void_fn fn, BSC_ConnHdlrPars pars) runs on MTC_CT return BSC_ConnHdlr {
	var BSC_ConnHdlr vc_conn;
	vc_conn := f_start_handler_create(pars);
	f_start_handler_run(vc_conn, fn, pars);
	return vc_conn;
}

function f_start_handler(void_fn fn, integer imsi_suffix, integer ran_idx := 0, boolean ran_is_geran := true, boolean use_osmux := false,
		         boolean verify_cell_id := true)
runs on MTC_CT return BSC_ConnHdlr {
	return f_start_handler_with_pars(fn, f_init_pars(imsi_suffix, ran_idx := ran_idx, ran_is_geran := ran_is_geran, use_osmux := use_osmux, verify_cell_id := verify_cell_id));
}

friend function f_msc_stats_prefix() return charstring
{
	return mp_statsd_prefix & "net.0.msc.";
}


private function f_tc_lu_imsi_noauth_tmsi(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);
	f_perform_lu();
}
testcase TC_lu_imsi_noauth_tmsi() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_lu_imsi_noauth_tmsi), 1);
	vc_conn.done;
}

private function f_tc_lu_imsi_noauth_notmsi(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	pars.net.expect_tmsi := false;
	f_init_handler(pars);
	f_perform_lu();
}
testcase TC_lu_imsi_noauth_notmsi() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "msc", "no assign-tmsi");

	vc_conn := f_start_handler(refers(f_tc_lu_imsi_noauth_notmsi), 2);
	vc_conn.done;
}

/* Do LU by IMSI, refuse it on GSUP and expect LU REJ back to MS */
friend function f_tc_lu_imsi_reject(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);
	var PDU_ML3_MS_NW l3_lu := f_build_lu_imsi(g_pars.imsi);

	f_create_gsup_expect(hex2str(g_pars.imsi));
	f_cl3_or_initial_ue(l3_lu);
	f_mm_common();
	GSUP.receive(tr_GSUP_UL_REQ(g_pars.imsi));
	GSUP.send(ts_GSUP_UL_ERR(g_pars.imsi, 23));
	alt {
		[] RAN_CONN.receive(tr_PDU_DTAP_MT(tr_ML3_MT_LU_Rej(int2oct(23,1)))) {
			f_expect_clear();
			}
		[] RAN_CONN.receive(tr_PDU_DTAP_MT(tr_ML3_MT_LU_Acc)) {
			setverdict(fail, "Expecting LU REJ, but got ACCEPT");
			mtc.stop;
		}
	}
}
testcase TC_lu_imsi_reject() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_lu_imsi_reject), 3, verify_cell_id := false);
	vc_conn.done;
}



/* Do LU by IMSI, timeout on GSUP */
friend function f_tc_lu_imsi_timeout_gsup(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);
	var PDU_ML3_MS_NW l3_lu := f_build_lu_imsi(g_pars.imsi);

	f_create_gsup_expect(hex2str(g_pars.imsi));
	f_cl3_or_initial_ue(l3_lu);
	f_mm_common();
	GSUP.receive(tr_GSUP_UL_REQ(g_pars.imsi));
	/* Normally the HLR would need to respond here, but we decide to force a timeout here */
	alt {
		/* FIXME: Expect specific reject cause */
		[] RAN_CONN.receive(tr_PDU_DTAP_MT(tr_ML3_MT_LU_Rej)) {
			f_expect_clear();
			}
		[] RAN_CONN.receive(tr_PDU_DTAP_MT(tr_ML3_MT_LU_Acc)) {
			setverdict(fail, "Expecting LU REJ, but got ACCEPT");
			mtc.stop;
		}
	}
}
testcase TC_lu_imsi_timeout_gsup() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_lu_imsi_timeout_gsup), 4, verify_cell_id := false);
	vc_conn.done;
}


private function f_tc_lu_imsi_auth_tmsi(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	pars.net.expect_auth := true;
	f_init_handler(pars);
	f_perform_lu();
}
testcase TC_lu_imsi_auth_tmsi() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "network", "authentication required");

	vc_conn := f_start_handler(refers(f_tc_lu_imsi_auth_tmsi), 5);
	vc_conn.done;
}


friend function f_tc_lu_imsi_auth3g_tmsi(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	pars.net.expect_auth := true;
	pars.use_umts_aka := true;
	f_init_handler(pars);
	f_perform_lu();
}
testcase TC_lu_imsi_auth3g_tmsi() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "network", "authentication required");

	vc_conn := f_start_handler(refers(f_tc_lu_imsi_auth3g_tmsi), 1005);
	vc_conn.done;
}

/* Proceed with LU but never receive an TMSI Realloc from MS after LU Accept (OS#4337).
 * TS 24.008 sec 4.3.1.5 states MSC should simply release all MM connections.
 */
friend function f_tc_lu_imsi_timeout_tmsi_realloc(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {

	f_init_handler(pars);

	var PDU_ML3_MS_NW l3_lu := f_build_lu_imsi(g_pars.imsi);
	var PDU_DTAP_MT dtap_mt;

	/* tell GSUP dispatcher to send this IMSI to us */
	f_create_gsup_expect(hex2str(g_pars.imsi));

	/* Send BSSAP_Conn_Req with COMPL L3 INFO to MSC */
	if (g_pars.ran_is_geran) {
		f_bssap_compl_l3(l3_lu);
		if (g_pars.send_early_cm) {
			RAN_CONN.send(ts_BSSMAP_ClassmarkUpd(g_pars.cm2, g_pars.cm3));
		}
	} else {
		f_ranap_initial_ue(l3_lu);
	}

	f_mm_imei_early();
	f_mm_common();
	f_msc_lu_hlr();
	f_mm_imei();

	alt {
	[] RAN_CONN.receive(tr_PDU_DTAP_MT(tr_ML3_MT_LU_Acc)) -> value dtap_mt {}
	[] RAN_CONN.receive(tr_PDU_DTAP_MT(tr_ML3_MT_LU_Rej)) {
		setverdict(fail, "Expected LU ACK, but received LU REJ");
		mtc.stop;
		}
	}

	/* currently (due to bug OS#4337), an extra LU reject is received before
	   terminating the connection. Enabling following line makes the test
	   pass: */
	//f_expect_lu_reject('16'O); /* Cause: congestion */

	/* f_expect_lu_reject() already waits for T"-1" (X1, 5 seconds), but give some
	   extra time to avoid race conditons... */
	f_expect_clear(7.0, verify_vlr_cell_id := false);

	setverdict(pass);
}
testcase TC_lu_imsi_timeout_tmsi_realloc() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_lu_imsi_timeout_tmsi_realloc), 5);
	vc_conn.done;
}


/* Send CM SERVICE REQ for IMSI that has never performed LU before */
friend function f_tc_cmserv_imsi_unknown(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	f_init_handler(pars);

	var MobileIdentityLV mi := valueof(ts_MI_IMSI_LV(g_pars.imsi));
	var BSSMAP_IE_CellIdentifier cell_id := valueof(ts_CellId_CGI('262'H, '42'H, 23, 42));
	var PDU_ML3_MS_NW l3_info := valueof(ts_CM_SERV_REQ(CM_TYPE_MO_CALL, mi));

	f_create_gsup_expect(hex2str(g_pars.imsi));

	/* Send BSSAP_Conn_Req with COMPL L3 INFO to MSC */
	f_cl3_or_initial_ue(l3_info);
	f_mm_auth();

	timer T := 10.0;
	T.start;
	alt {
	[] RAN_CONN.receive(tr_PDU_DTAP_MT(tr_CM_SERV_REJ)) { }
	//[] RAN_CONN.receive(tr_PDU_DTAP_MT(tr_CM_SERV_ACC)) { }
	[] GSUP.receive(tr_GSUP_UL_REQ(g_pars.imsi)) {
		setverdict(fail, "Unexpected GSUP UL REQ");
		mtc.stop;
		}
	[] as_unexp_bssap_msg();
	[] T.timeout {
		setverdict(fail, "Timeout waiting for CM SERV REJ");
		mtc.stop;
		}
	}

	f_expect_clear();
}
testcase TC_cmserv_imsi_unknown() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_tc_cmserv_imsi_unknown), 6, verify_cell_id := false);
	vc_conn.done;
}


/* Send CM SERVICE REQ for TMSI that has never performed LU before */
friend function f_tc_cmserv_tmsi_unknown(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	f_init_handler(pars);

	var MobileIdentityLV mi := valueof(ts_MI_TMSI_LV('57111111'O));
	var BSSMAP_IE_CellIdentifier cell_id := valueof(ts_CellId_CGI('262'H, '42'H, 23, 42));
	var PDU_ML3_MS_NW l3_info := valueof(ts_CM_SERV_REQ(CM_TYPE_MO_CALL, mi));

	/* Send BSSAP_Conn_Req with COMPL L3 INFO to MSC */
	f_cl3_or_initial_ue(l3_info);
	f_mm_auth();

	timer T := 10.0;
	T.start;
	alt {
	[] RAN_CONN.receive(tr_PDU_DTAP_MT(tr_CM_SERV_REJ)) { }
	[] as_unexp_bssap_msg();
	[] T.timeout {
		setverdict(fail, "Timeout waiting for CM SERV REJ");
		mtc.stop;
		}
	}

	f_expect_clear();
}
testcase TC_cmserv_tmsi_unknown() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_tc_cmserv_tmsi_unknown), 57, verify_cell_id := false);
	vc_conn.done;
}

/* Send Paging Response for IMSI that has never performed LU before */
friend function f_tc_paging_response_imsi_unknown(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	f_init_handler(pars);

	var MobileIdentityLV mi := valueof(ts_MI_IMSI_LV(g_pars.imsi));
	var BSSMAP_IE_CellIdentifier cell_id := valueof(ts_CellId_CGI('262'H, '42'H, 23, 42));
	var PDU_ML3_MS_NW l3_info := valueof(ts_PAG_RESP(mi));

	/* Send BSSAP_Conn_Req with COMPL L3 INFO to MSC */
	f_cl3_or_initial_ue(l3_info);

	/* The Paging Response gets rejected by a direct Clear Command */
	f_expect_clear();
}
testcase TC_paging_response_imsi_unknown() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_tc_paging_response_imsi_unknown), 58, verify_cell_id := false);
	vc_conn.done;
}

/* Send Paging Response for TMSI that has never performed LU before */
friend function f_tc_paging_response_tmsi_unknown(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	f_init_handler(pars);

	var MobileIdentityLV mi := valueof(ts_MI_TMSI_LV('59111111'O));
	var BSSMAP_IE_CellIdentifier cell_id := valueof(ts_CellId_CGI('262'H, '42'H, 23, 42));
	var PDU_ML3_MS_NW l3_info := valueof(ts_PAG_RESP(mi));

	/* Send BSSAP_Conn_Req with COMPL L3 INFO to MSC */
	f_cl3_or_initial_ue(l3_info);

	/* The Paging Response gets rejected by a direct Clear Command */
	f_expect_clear();
}
testcase TC_paging_response_tmsi_unknown() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_tc_paging_response_tmsi_unknown), 59, verify_cell_id := false);
	vc_conn.done;
}


friend function f_tc_lu_and_mo_call(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);
	var CallParameters cpars := valueof(t_CallParams);
	f_perform_lu();
	f_mo_call(cpars);
}
testcase TC_lu_and_mo_call() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_lu_and_mo_call), 7);
	vc_conn.done;
}
friend function f_tc_lu_and_mo_call_ipv6(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);
	var CallParameters cpars := valueof(t_CallParams);
	cpars.mgw_conn_1.mgw_rtp_ip := "::1";
	cpars.mgw_conn_2.mgw_rtp_ip := "::2";
	cpars.bss_rtp_ip := "::3";
	f_perform_lu();
	f_mo_call(cpars);
}
testcase TC_lu_and_mo_call_ipv6() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_lu_and_mo_call_ipv6), 7);
	vc_conn.done;
}

/* Verify T(iar) triggers and releases the channel */
friend function f_lu_and_mo_call_sccp_tiar_timeout(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	timer T_wait_iar := int2float(5 + 1); /* g_msc_sccp_timer_iar + Give extra time (+1 sec) */
	f_init_handler(pars);
	var CallParameters cpars := valueof(t_CallParams);
	f_perform_lu();
	f_mo_call_establish(cpars);

	/* Expect the channel cleared upon T(iar) triggered: */
	T_wait_iar.start;
	alt {
	[] RAN_CONN.receive(tr_MSC_CONN_PRIM_DISC_IND) {
				T_wait_iar.stop
				setverdict(pass);
		}
	[] T_wait_iar.timeout {
		setverdict(fail, "Timeout waiting for T(iar) triggered SCCP RSLD");
		mtc.stop;
		}
	}
	/* DLCX for both directions; if we don't do this, we might receive either of the two during
	 * shutdown causing race conditions */
	MGCP.receive(tr_DLCX(?));
	MGCP.receive(tr_DLCX(?));

	setverdict(pass);
}
testcase TC_lu_and_mo_call_sccp_tiar_timeout() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;

	/* Set T(iar) in MSC low enough that it will trigger before other side
	   has time to keep alive with a T(ias). Keep recommended ratio of
	   T(iar) >= T(ias)*2 */
	g_msc_sccp_timer_ias := 2;
	g_msc_sccp_timer_iar := 5;

	f_init();

	vc_conn := f_start_handler(refers(f_lu_and_mo_call_sccp_tiar_timeout), 89);
	vc_conn.done;
}


/* Test LU (with authentication enabled), where HLR times out sending SAI response */
friend function f_tc_lu_auth_sai_timeout(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);

	var PDU_ML3_MS_NW l3_lu := f_build_lu_imsi(g_pars.imsi)
	var PDU_DTAP_MT dtap_mt;

	/* tell GSUP dispatcher to send this IMSI to us */
	f_create_gsup_expect(hex2str(g_pars.imsi));

	/* Send BSSAP_Conn_Req with COMPL L3 INFO to MSC */
	f_cl3_or_initial_ue(l3_lu);

	/* Send Early Classmark, just for the fun of it */
	if (pars.ran_is_geran) {
		RAN_CONN.send(ts_BSSMAP_ClassmarkUpd(g_pars.cm2, g_pars.cm3));
	}

	GSUP.receive(tr_GSUP_SAI_REQ(g_pars.imsi));
	/* The HLR would normally return an auth vector here, but we fail to do so. */

	RAN_CONN.receive(tr_PDU_DTAP_MT(tr_ML3_MT_LU_Rej));
	f_expect_clear();
}
testcase TC_lu_auth_sai_timeout() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "network", "authentication required");

	vc_conn := f_start_handler(refers(f_tc_lu_auth_sai_timeout), 8, verify_cell_id := false);
	vc_conn.done;
}


/* Test LU (with authentication enabled), where HLR rejects sending SAI error */
friend function f_tc_lu_auth_sai_err(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);

	var PDU_ML3_MS_NW l3_lu := f_build_lu_imsi(g_pars.imsi)
	var PDU_DTAP_MT dtap_mt;

	/* tell GSUP dispatcher to send this IMSI to us */
	f_create_gsup_expect(hex2str(g_pars.imsi));

	/* Send BSSAP_Conn_Req with COMPL L3 INFO to MSC */
	f_cl3_or_initial_ue(l3_lu);

	/* Send Early Classmark, just for the fun of it */
	if (pars.ran_is_geran) {
		RAN_CONN.send(ts_BSSMAP_ClassmarkUpd(g_pars.cm2, g_pars.cm3));
	}

	GSUP.receive(tr_GSUP_SAI_REQ(g_pars.imsi));
	GSUP.send(ts_GSUP_SAI_ERR(g_pars.imsi, 13));

	RAN_CONN.receive(tr_PDU_DTAP_MT(tr_ML3_MT_LU_Rej));
	f_expect_clear();
}
testcase TC_lu_auth_sai_err() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "network", "authentication required");

	vc_conn := f_start_handler(refers(f_tc_lu_auth_sai_err), 9, verify_cell_id := false);
	vc_conn.done;
}


/* Test LU but BSC will send a clear request in the middle */
private function f_tc_lu_clear_request(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);

	var PDU_ML3_MS_NW l3_lu := f_build_lu_imsi(g_pars.imsi)
	var PDU_DTAP_MT dtap_mt;

	/* tell GSUP dispatcher to send this IMSI to us */
	f_create_gsup_expect(hex2str(g_pars.imsi));

	/* Send BSSAP_Conn_Req with COMPL L3 INFO to MSC */
	f_cl3_or_initial_ue(l3_lu);
	f_expect_common_id();

	/* Send Early Classmark, just for the fun of it */
	RAN_CONN.send(ts_BSSMAP_ClassmarkUpd(g_pars.cm2, g_pars.cm3));

	f_sleep(1.0);
	/* send clear request in the middle of the LU */
	RAN_CONN.send(ts_BSSMAP_ClearRequest(0));
	alt {
	[] RAN_CONN.receive(tr_PDU_DTAP_MT(tr_ML3_MT_LU_Rej)) { repeat; }
	[] RAN_CONN.receive(tr_BSSMAP_ClearCommand) {}
	}
	RAN_CONN.send(ts_BSSMAP_ClearComplete);
	alt {
	/* See https://osmocom.org/issues/2862 */
	[] RAN_CONN.receive(tr_BSSMAP_ClearCommand) {
			setverdict(fail, "Got a second Clear Command, only one expected");
			mtc.stop;
			repeat;
		}
	[] RAN_CONN.receive(tr_MSC_CONN_PRIM_DISC_IND) {}
	}
	setverdict(pass);
}
testcase TC_lu_clear_request() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_lu_clear_request), 10);
	vc_conn.done;
}

/* Test reaction on Clear Request during a MO Call */
friend function f_TC_mo_mt_call_clear_request(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	var CallParameters cpars := valueof(t_CallParams);
	var MNCC_PDU mncc_pdu;
	timer T := 2.0;

	f_init_handler(pars);

	f_perform_lu();

	/* HACK: reducing code duplication ('66'H - MO, '68'H - MT) */
	if (pars.imsi == '262420002532766'H)
		{ f_mo_call_establish(cpars); }
	else
		{ f_mt_call_establish(cpars); }

	/* Hold the line for a while... */
	f_sleep(2.0);

	/* BSC sends BSSMAP Clear Request (e.g. due to RR failure) */
	RAN_CONN.send(ts_BSSMAP_ClearRequest(1));

	/* Expect (optional) CC RELEASE and Clear Command */
	var default ccrel := activate(as_optional_cc_rel(cpars));
	f_expect_clear();
	deactivate(ccrel);

	/* Expect RELease indication on the MNCC socket */
	T.start;
	alt {
	[] MNCC.receive(tr_MNCC_REL_ind(cpars.mncc_callref)) -> value mncc_pdu {
		log("Rx MNCC REL.ind, cause := ", mncc_pdu.u.signal.cause);
		setverdict(pass);
		}
	[] MNCC.receive(MNCC_PDU:?) -> value mncc_pdu {
		setverdict(fail, "Rx unexpected MNCC PDU: ", mncc_pdu);
		}
	[] T.timeout {
		setverdict(fail, "Timeout waiting for MNCC REL.ind");
		}
	}
}
testcase TC_mo_call_clear_request() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;

	f_init();

	vc_conn := f_start_handler(refers(f_TC_mo_mt_call_clear_request), 2532766); // '66'H - MO
	vc_conn.done;
}
testcase TC_mt_call_clear_request() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;

	f_init();

	vc_conn := f_start_handler(refers(f_TC_mo_mt_call_clear_request), 2532768); // '68'H - MT
	vc_conn.done;
}

/* Test LU but BSC will send a clear request in the middle */
friend function f_tc_lu_disconnect(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);

	var PDU_ML3_MS_NW l3_lu := f_build_lu_imsi(g_pars.imsi)
	var PDU_DTAP_MT dtap_mt;

	/* tell GSUP dispatcher to send this IMSI to us */
	f_create_gsup_expect(hex2str(g_pars.imsi));

	/* Send BSSAP_Conn_Req with COMPL L3 INFO to MSC */
	f_cl3_or_initial_ue(l3_lu);

	/* Send Early Classmark, just for the fun of it */
	if (pars.ran_is_geran) {
		RAN_CONN.send(ts_BSSMAP_ClassmarkUpd(g_pars.cm2, g_pars.cm3));
	}

	f_sleep(1.0);
	/* send clear request in the middle of the LU */
	RAN_CONN.send(ts_MSC_CONN_PRIM_DISC_REQ);
	setverdict(pass);
	f_sleep(1.0);
}
testcase TC_lu_disconnect() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_lu_disconnect), 11);
	vc_conn.done;
}

/* Test LU but with illegal mobile identity type = IMEI */
friend function f_tc_lu_by_imei(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);

	var PDU_ML3_MS_NW l3_lu := f_build_lu_imei(g_pars.imei)
	var PDU_DTAP_MT dtap_mt;

	/* tell GSUP dispatcher to send this IMSI to us */
	f_create_gsup_expect(hex2str(g_pars.imsi));

	/* Send BSSAP_Conn_Req with COMPL L3 INFO to MSC */
	f_cl3_or_initial_ue(l3_lu);

	/* Send Early Classmark, just for the fun of it */
	if (pars.ran_is_geran) {
		RAN_CONN.send(ts_BSSMAP_ClassmarkUpd(g_pars.cm2, g_pars.cm3));
	}
	/* wait for LU reject, ignore any ID REQ */
	alt {
	[] RAN_CONN.receive(tr_PDU_DTAP_MT(tr_ML3_MT_LU_Rej)) { }
	[] RAN_CONN.receive(tr_PDU_DTAP_MT(tr_ML3_MT_MM_ID_Req)) { repeat; }
	}
	/* wait for normal teardown */
	f_expect_clear();
}
testcase TC_lu_by_imei() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_lu_by_imei), 12, verify_cell_id := false);
	vc_conn.done;
}


/* Test LU by TMSI with unknown TMSI, expect (and answer) ID REQ. */
private function f_tc_lu_tmsi_noauth_unknown(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	/* We piggyback a test for an MSC crash on overlong IMSI (OS#2864) onto this test. */
	var hexstring overlong_imsi := '012345789ABCDEF0123456789ABCDEF'H;
	f_init_handler(pars);

	var PDU_ML3_MS_NW l3_lu := f_build_lu_tmsi('01020304'O); /* FIXME: Random */
	var PDU_DTAP_MT dtap_mt;

	/* tell GSUP dispatcher to send this IMSI to us */
	f_create_gsup_expect(hex2str(g_pars.imsi));

	/* Send BSSAP_Conn_Req with COMPL L3 INFO to MSC */
	f_cl3_or_initial_ue(l3_lu);

	/* Send Early Classmark, just for the fun of it */
	RAN_CONN.send(ts_BSSMAP_ClassmarkUpd(g_pars.cm2, g_pars.cm3));

	/* Wait for + respond to ID REQ (IMSI) */
	RAN_CONN.receive(tr_PDU_DTAP_MT(tr_ML3_MT_MM_ID_Req(CM_ID_TYPE_IMSI)));
	RAN_CONN.send(ts_PDU_DTAP_MO(ts_ML3_MO_MM_ID_Rsp_IMSI(overlong_imsi))); /* test for OS#2864 */
	RAN_CONN.send(ts_PDU_DTAP_MO(ts_ML3_MO_MM_ID_Rsp_IMSI(g_pars.imsi)));
	f_expect_common_id();

	/* Expect MSC to do UpdateLocation to HLR; respond to it */
	GSUP.receive(tr_GSUP_UL_REQ(g_pars.imsi));
	GSUP.send(ts_GSUP_ISD_REQ(g_pars.imsi, g_pars.msisdn));
	GSUP.receive(tr_GSUP_ISD_RES(g_pars.imsi));
	GSUP.send(ts_GSUP_UL_RES(g_pars.imsi));

	alt {
	[] RAN_CONN.receive(tr_PDU_DTAP_MT(tr_ML3_MT_LU_Acc)) {
		RAN_CONN.send(ts_PDU_DTAP_MO(ts_ML3_MO_TmsiRealloc_Cmpl));
		}
	[] RAN_CONN.receive(tr_PDU_DTAP_MT(tr_ML3_MT_LU_Rej)) {
		setverdict(fail, "Expected LU ACK, but received REJ");
		mtc.stop;
		}
	}

	/* Wait for MM-Information (if enabled) */
	f_expect_mm_info();

	/* wait for normal teardown */
	f_expect_clear();
}
testcase TC_lu_by_tmsi_noauth_unknown() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_lu_tmsi_noauth_unknown), 13);
	vc_conn.done;
}

/* Test LU by unknown TMSI, while the IMSI is already attached: osmo-msc should switch to the attached vlr_subscr. */
private function f_tc_attached_imsi_lu_unknown_tmsi(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);

	var PDU_ML3_MS_NW l3_lu := f_build_lu_tmsi('56111111'O);
	var PDU_DTAP_MT dtap_mt;

	/* tell GSUP dispatcher to send this IMSI to us */
	f_create_gsup_expect(hex2str(g_pars.imsi));

	/* Send BSSAP_Conn_Req with COMPL L3 INFO to MSC */
	f_cl3_or_initial_ue(l3_lu);

	/* Send Early Classmark, just for the fun of it */
	RAN_CONN.send(ts_BSSMAP_ClassmarkUpd(g_pars.cm2, g_pars.cm3));

	/* Wait for + respond to ID REQ (IMSI) */
	RAN_CONN.receive(tr_PDU_DTAP_MT(tr_ML3_MT_MM_ID_Req(CM_ID_TYPE_IMSI)));
	RAN_CONN.send(ts_PDU_DTAP_MO(ts_ML3_MO_MM_ID_Rsp_IMSI(g_pars.imsi)));
	f_expect_common_id();

	/* Expect MSC to do UpdateLocation to HLR; respond to it */
	GSUP.receive(tr_GSUP_UL_REQ(g_pars.imsi));
	GSUP.send(ts_GSUP_ISD_REQ(g_pars.imsi, g_pars.msisdn));
	GSUP.receive(tr_GSUP_ISD_RES(g_pars.imsi));
	GSUP.send(ts_GSUP_UL_RES(g_pars.imsi));

	alt {
	[] RAN_CONN.receive(tr_PDU_DTAP_MT(tr_ML3_MT_LU_Acc)) {
		RAN_CONN.send(ts_PDU_DTAP_MO(ts_ML3_MO_TmsiRealloc_Cmpl));
		}
	[] RAN_CONN.receive(tr_PDU_DTAP_MT(tr_ML3_MT_LU_Rej)) {
		setverdict(fail, "Expected LU ACK, but received REJ");
		mtc.stop;
		}
	}

	/* Wait for MM-Information (if enabled) */
	f_expect_mm_info();

	/* wait for normal teardown */
	f_expect_clear(verify_vlr_cell_id := false);

	/* Now the same IMSI is still attached in the VLR, and a LU with an unknown TMSI reveals the same IMSI only
	 * later during ID Response.  osmo-msc first creates a new vlr_subscr for the unknown TMSI, and as soon as the
	 * IMSI becomes known, must notice that this IMSI is still regarded as attached, and must not create evil twins.
	 */

	/* (since the TMSI Reallocation happened, we could do this with exactly the same TMSI as above, but for test
	 * readability just use a different one.) */
	l3_lu := f_build_lu_tmsi('56222222'O);
	f_cl3_or_initial_ue(l3_lu);

	/* Wait for + respond to ID REQ (IMSI) */
	RAN_CONN.receive(tr_PDU_DTAP_MT(tr_ML3_MT_MM_ID_Req(CM_ID_TYPE_IMSI)));
	RAN_CONN.send(ts_PDU_DTAP_MO(ts_ML3_MO_MM_ID_Rsp_IMSI(g_pars.imsi)));
	f_expect_common_id();

	/* Expect MSC to do UpdateLocation to HLR; respond to it */
	GSUP.receive(tr_GSUP_UL_REQ(g_pars.imsi));
	GSUP.send(ts_GSUP_ISD_REQ(g_pars.imsi, g_pars.msisdn));
	GSUP.receive(tr_GSUP_ISD_RES(g_pars.imsi));
	GSUP.send(ts_GSUP_UL_RES(g_pars.imsi));

	alt {
	[] RAN_CONN.receive(tr_PDU_DTAP_MT(tr_ML3_MT_LU_Acc)) {
		RAN_CONN.send(ts_PDU_DTAP_MO(ts_ML3_MO_TmsiRealloc_Cmpl));
		}
	[] RAN_CONN.receive(tr_PDU_DTAP_MT(tr_ML3_MT_LU_Rej)) {
		setverdict(fail, "Expected LU ACK, but received REJ");
		mtc.stop;
		}
	}

	/* Wait for MM-Information (if enabled) */
	f_expect_mm_info();

	/* wait for normal teardown */
	f_expect_clear(verify_vlr_cell_id := false);
}
testcase TC_attached_imsi_lu_unknown_tmsi() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_attached_imsi_lu_unknown_tmsi), 56);
	vc_conn.done;
}

friend function f_imsi_detach_by_imsi() runs on BSC_ConnHdlr {
	var MobileIdentityLV mi := valueof(ts_MI_IMSI_LV(g_pars.imsi));

	/* Send BSSAP_Conn_Req with COMPL L3 INFO to MSC */
	f_cl3_or_initial_ue(valueof(ts_ML3_MO_MM_IMSI_DET_Ind(mi)));

	/* Send Early Classmark, just for the fun of it? */
	if (g_pars.ran_is_geran) {
		RAN_CONN.send(ts_BSSMAP_ClassmarkUpd(g_pars.cm2, g_pars.cm3));
	}

	/* wait for normal teardown */
	f_expect_clear(verify_vlr_cell_id := false);
}


/* Test IMSI DETACH (MI=IMSI) */
friend function f_tc_imsi_detach_by_imsi(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);

	f_imsi_detach_by_imsi();
}
testcase TC_imsi_detach_by_imsi() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_imsi_detach_by_imsi), 14, verify_cell_id := false);
	vc_conn.done;
}


/* Test IMSI DETACH (MI=TMSI) */
friend function f_tc_imsi_detach_by_tmsi(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);

	var MobileIdentityLV mi := valueof(ts_MI_TMSI_LV('01020304'O));

	/* Send BSSAP_Conn_Req with COMPL L3 INFO to MSC */
	f_cl3_or_initial_ue(valueof(ts_ML3_MO_MM_IMSI_DET_Ind(mi)));

	/* Send Early Classmark, just for the fun of it? */
	if (pars.ran_is_geran) {
		RAN_CONN.send(ts_BSSMAP_ClassmarkUpd(g_pars.cm2, g_pars.cm3));
	}

	/* wait for normal teardown */
	f_expect_clear();
}
testcase TC_imsi_detach_by_tmsi() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_imsi_detach_by_tmsi), 15, verify_cell_id := false);
	vc_conn.done;
}


/* Test IMSI DETACH (MI=IMEI), which is illegal */
friend function f_tc_imsi_detach_by_imei(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);

	var MobileIdentityLV mi := valueof(ts_MI_IMEI_LV(g_pars.imei));

	/* Send BSSAP_Conn_Req with COMPL L3 INFO to MSC */
	f_cl3_or_initial_ue(valueof(ts_ML3_MO_MM_IMSI_DET_Ind(mi)));

	/* Send Early Classmark, just for the fun of it? */
	if (pars.ran_is_geran) {
		RAN_CONN.send(ts_BSSMAP_ClassmarkUpd(g_pars.cm2, g_pars.cm3));
	}

	/* wait for normal teardown */
	f_expect_clear();
}
testcase TC_imsi_detach_by_imei() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_imsi_detach_by_imei), 16, verify_cell_id := false);
	vc_conn.done;
}


/* helper function for an emergency call. caller passes in mobile identity to use */
private function f_emerg_call(MobileIdentityLV mi) runs on BSC_ConnHdlr {
	var CallParameters cpars := valueof(t_CallParams('112'H, 0));
	cpars.emergency := true;

	f_mo_call(cpars);
}

/* establish an emergency call by IMEI, no SIM inserted (and hence no IMSI) */
friend function f_tc_emerg_call_imei_reject(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);

	var MobileIdentityLV mi := valueof(ts_MI_IMEI_LV(g_pars.imei));
	var PDU_ML3_MS_NW l3_info := valueof(ts_CM_SERV_REQ(CM_TYPE_EMERG_CALL, mi));
	f_cl3_or_initial_ue(l3_info);
	RAN_CONN.receive(tr_PDU_DTAP_MT(tr_CM_SERV_REJ('05'O)));
	f_expect_clear();
}
testcase TC_emerg_call_imei_reject() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_emerg_call_imei_reject), 17, verify_cell_id := false);
	vc_conn.done;
}


/* establish an emergency call by IMSI, SIM inserted (and hence IMSI) */
friend function f_tc_emerg_call_imsi(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);
	/* First perform location update to ensure subscriber is known */
	f_perform_lu();
	/* Then issue emergency call identified by IMSI */
	f_emerg_call(valueof(ts_MI_IMSI_LV(g_pars.imsi)));
}
testcase TC_emerg_call_imsi() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_emerg_call_imsi), 18);
	vc_conn.done;
}


/* CM Service Request for VGCS -> reject */
private function f_tc_cm_serv_req_vgcs_reject(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);

	/* First perform location update to ensure subscriber is known */
	f_perform_lu();

	var MobileIdentityLV mi := valueof(ts_MI_IMSI_LV(g_pars.imsi));
	var PDU_ML3_MS_NW l3_info := valueof(ts_CM_SERV_REQ(CM_TYPE_VGCS, mi));
	f_cl3_or_initial_ue(l3_info);
	RAN_CONN.receive(tr_PDU_DTAP_MT(tr_CM_SERV_REJ(int2oct(32,1))));
	f_expect_clear();
}
testcase TC_cm_serv_req_vgcs_reject() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_cm_serv_req_vgcs_reject), 19);
	vc_conn.done;
}

/* CM Service Request for VBS -> reject */
private function f_tc_cm_serv_req_vbs_reject(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);

	/* First perform location update to ensure subscriber is known */
	f_perform_lu();

	var MobileIdentityLV mi := valueof(ts_MI_IMSI_LV(g_pars.imsi));
	var PDU_ML3_MS_NW l3_info := valueof(ts_CM_SERV_REQ(CM_TYPE_VBS, mi));
	f_cl3_or_initial_ue(l3_info);
	RAN_CONN.receive(tr_PDU_DTAP_MT(tr_CM_SERV_REJ(int2oct(32,1))));
	f_expect_clear();
}
testcase TC_cm_serv_req_vbs_reject() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_cm_serv_req_vbs_reject), 20);
	vc_conn.done;
}

/* CM Service Request for LCS -> reject */
private function f_tc_cm_serv_req_lcs_reject(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);

	/* First perform location update to ensure subscriber is known */
	f_perform_lu();

	var MobileIdentityLV mi := valueof(ts_MI_IMSI_LV(g_pars.imsi));
	var PDU_ML3_MS_NW l3_info := valueof(ts_CM_SERV_REQ(CM_TYPE_LCS, mi));
	f_cl3_or_initial_ue(l3_info);
	RAN_CONN.receive(tr_PDU_DTAP_MT(tr_CM_SERV_REJ(int2oct(32,1))));
	f_expect_clear();
}
testcase TC_cm_serv_req_lcs_reject() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_cm_serv_req_lcs_reject), 21);
	vc_conn.done;
}

/* CM Re-Establishment Request */
private function f_tc_cm_reest_req_reject(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);

	/* First perform location update to ensure subscriber is known */
	f_perform_lu();

	var MobileIdentityLV mi := valueof(ts_MI_IMSI_LV(g_pars.imsi));
	var PDU_ML3_MS_NW l3_info := valueof(ts_CM_REEST_REQ(0, mi));
	f_cl3_or_initial_ue(l3_info);
	/* Older osmo-msc returns: GSM48_REJECT_SRV_OPT_NOT_SUPPORTED = 32,
	 * newer osmo-msc with CM Re-Establish support returns: GSM48_REJECT_CALL_CAN_NOT_BE_IDENTIFIED	= 38 */
	RAN_CONN.receive(tr_PDU_DTAP_MT(tr_CM_SERV_REJ( (int2oct(32,1), int2oct(38,1)) )));
	f_expect_clear();
}
testcase TC_cm_reest_req_reject() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_cm_reest_req_reject), 22);
	vc_conn.done;
}

/* Test LU (with authentication enabled), with wrong response from MS */
private function f_tc_lu_auth_2G_fail(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);

	var PDU_ML3_MS_NW l3_lu := f_build_lu_imsi(g_pars.imsi)

	/* tell GSUP dispatcher to send this IMSI to us */
	f_create_gsup_expect(hex2str(g_pars.imsi));

	/* Send BSSAP_Conn_Req with COMPL L3 INFO to MSC */
	f_cl3_or_initial_ue(l3_lu);

	/* Send Early Classmark, just for the fun of it */
	RAN_CONN.send(ts_BSSMAP_ClassmarkUpd(g_pars.cm2, g_pars.cm3));

	var AuthVector vec := f_gen_auth_vec_2g();
	var GSUP_IE auth_tuple := valueof(ts_GSUP_IE_AuthTuple2G(vec.rand, vec.sres, vec.kc));
	GSUP.receive(tr_GSUP_SAI_REQ(g_pars.imsi));
	GSUP.send(ts_GSUP_SAI_RES(g_pars.imsi, auth_tuple));

	RAN_CONN.receive(tr_PDU_DTAP_MT(tr_ML3_MT_MM_AUTH_REQ(vec.rand)));
	/* Send back wrong auth response */
	RAN_CONN.send(ts_PDU_DTAP_MO(ts_ML3_MT_MM_AUTH_RESP_2G('00000000'O)));

	/* Expect GSUP AUTH FAIL REP to HLR */
	GSUP.receive(tr_GSUP_AUTH_FAIL_IND(g_pars.imsi));

	/* Expect LU REJECT with Cause == Illegal MS */
	RAN_CONN.receive(tr_PDU_DTAP_MT(tr_ML3_MT_LU_Rej('03'O)));
	f_expect_clear();
}
testcase TC_lu_auth_2G_fail() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "network", "authentication required");

	vc_conn := f_start_handler(refers(f_tc_lu_auth_2G_fail), 23, verify_cell_id := false);
	vc_conn.done;
}

/* A5/1 + A5/3 permitted on network side, and MS capable to do it */
private function f_tc_lu_imsi_auth_tmsi_encr_13_13(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	pars.net.expect_auth := true;
	pars.net.expect_ciph := true;
	f_init_handler(pars);
	f_perform_lu();
}
testcase TC_lu_imsi_auth_tmsi_encr_13_13() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "network", "authentication required");
	f_vty_config(MSCVTY, "network", "encryption a5 1 3");

	vc_conn := f_start_handler(refers(f_tc_lu_imsi_auth_tmsi_encr_13_13), 24);
	vc_conn.done;
}

/* Test Complete L3 without payload */
private function f_tc_cl3_no_payload(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);

	/* Send Complete L3 Info with empty L3 frame */
	RAN_CONN.send(ts_BSSAP_Conn_Req(g_pars.sccp_addr_peer, g_pars.sccp_addr_own,
					valueof(ts_BSSMAP_ComplL3(g_pars.cell_id, ''O))));

	timer T := 5.0;
	T.start;
	alt {
	[] RAN_CONN.receive(tr_MSC_CONN_PRIM_DISC_IND) {}
	/* Expect LU REJECT with Cause == Illegal MS */
	[] RAN_CONN.receive(tr_PDU_DTAP_MT(?)) { repeat; }
	[] RAN_CONN.receive(tr_MSC_CONN_PRIM_CONF_IND) { repeat; }
	[] as_clear_cmd_compl_disc();
	[] T.timeout {
		setverdict(fail, "Timeout waiting for ClearCommand or SCCP Release");
		mtc.stop;
		}
	}
	setverdict(pass);
}
testcase TC_cl3_no_payload() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_cl3_no_payload), 25);
	vc_conn.done;
}

/* Test Complete L3 with random payload */
private function f_tc_cl3_rnd_payload(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);

	/* length is limited by PDU_BSSAP length field which includes some
	 * other fields beside l3info payload. So payl can only be 240 bytes
	 * Since rnd() returns values < 1 multiply with 241
	 */
	var integer len := float2int(rnd() * 241.0);
	var octetstring payl := f_rnd_octstring(len);

	/* Send Complete L3 Info with empty L3 frame */
	RAN_CONN.send(ts_BSSAP_Conn_Req(g_pars.sccp_addr_peer, g_pars.sccp_addr_own,
					valueof(ts_BSSMAP_ComplL3(g_pars.cell_id, payl))));

	timer T := 5.0;
	T.start;
	alt {
	/* Immediate disconnect */
	[] RAN_CONN.receive(tr_MSC_CONN_PRIM_DISC_IND) {}
	[] RAN_CONN.receive(tr_PDU_DTAP_MT(?)) { repeat; }
	[] RAN_CONN.receive(tr_MSC_CONN_PRIM_CONF_IND) { repeat; }
	[] as_clear_cmd_compl_disc();
	[] T.timeout {
		setverdict(fail, "Timeout waiting for ClearCommand or SCCP Release");
		mtc.stop;
		}
	}
	setverdict(pass);
}
testcase TC_cl3_rnd_payload() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_cl3_rnd_payload), 26);
	vc_conn.done;
}

/* Test Complete L3 with random payload */
friend function f_tc_establish_and_nothing(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);

	f_perform_lu();

	f_establish_fully();
	f_expect_clear(10.0);
}
testcase TC_establish_and_nothing() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_establish_and_nothing), 27);
	vc_conn.done;
}


/* Test MO Call SETUP with no response from MNCC */
friend function f_tc_mo_setup_and_nothing(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars, 190.0);

	var CallParameters cpars := valueof(t_CallParams('12345'H, 0));
	cpars.mgw_conn_2.resp := 0;
	cpars.stop_after_cc_setup := true;

	f_vty_config(MSCVTY, "msc", "mncc guard-timeout 20");

	f_perform_lu();

	f_mo_call_establish(cpars);

	var default ccrel := activate(as_optional_cc_rel(cpars));

	f_expect_clear(185.0);

	deactivate(ccrel);

	f_sleep(1.0);
}
testcase TC_mo_setup_and_nothing() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_mo_setup_and_nothing), 28);
	vc_conn.done;
}


/* Test MO Call with no response to RAN-side CRCX */
friend function f_tc_mo_crcx_ran_timeout(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);
	var CallParameters cpars := valueof(t_CallParams('12345'H, 0));
	var MNCC_PDU mncc;
	var MgcpCommand mgcp_cmd;

	f_perform_lu();
	/* Do not respond to the second CRCX */
	cpars.mgw_conn_2.resp := 0;
	f_mo_call_establish(cpars);

	var default ccrel := activate(as_optional_cc_rel(cpars));

	f_expect_clear(60.0);

	deactivate(ccrel);
}
testcase TC_mo_crcx_ran_timeout() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_mo_crcx_ran_timeout), 29);
	vc_conn.done;
}


/* Test MO Call with reject to RAN-side CRCX */
friend function f_tc_mo_crcx_ran_reject(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);

	var CallParameters cpars := valueof(t_CallParams('12345'H, 0));

	/* Respond with error for the first CRCX */
	cpars.mgw_conn_1.resp := -1;

	f_perform_lu();
	f_mo_call_establish(cpars);

	var default ccrel := activate(as_optional_cc_rel(cpars));
	f_expect_clear(60.0);
	deactivate(ccrel);
}
testcase TC_mo_crcx_ran_reject() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_mo_crcx_ran_reject), 30);
	vc_conn.done;
}


/* helper function to start a MT call: MNCC SETUP; Paging; DChan est.; DTAP SETUP */
private function f_mt_call_start(inout CallParameters cpars) runs on BSC_ConnHdlr {
	var MNCC_PDU mncc;
	var MgcpCommand mgcp_cmd;

	f_perform_lu();
	f_ran_register_imsi(g_pars.imsi, g_pars.tmsi);

	/* Allocate call reference and send SETUP via MNCC to MSC */
	cpars.mncc_callref := f_rnd_int(2147483648);
	MNCC.send(ts_MNCC_SETUP_req(cpars.mncc_callref, hex2str(g_pars.msisdn),
				    hex2str(cpars.called_party), hex2str(g_pars.imsi)));

	/* MSC->BSC: expect PAGING from MSC */
	f_expect_paging();

	/* MS -> MSC: PAGING RESPONSE */
	f_establish_fully(EST_TYPE_PAG_RESP);

	f_create_mgcp_expect(ExpectCriteria:{omit,omit,omit});

	/* MSC->MS: SETUP */
	RAN_CONN.receive(tr_PDU_DTAP_MT(tr_ML3_MT_CC_SETUP(cpars.transaction_id, *, cpars.called_party)));
}

/* Test MT Call */
friend function f_tc_mt_crcx_ran_reject(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);
	var CallParameters cpars := valueof(t_CallParams('123456'H, 0));
	var MNCC_PDU mncc;
	var MgcpCommand mgcp_cmd;

	f_mt_call_start(cpars);

	/* MS->MSC: CALL CONFIRMED */
	RAN_CONN.send(ts_PDU_DTAP_MO(ts_ML3_MO_CC_CALL_CONF(cpars.transaction_id)));

	MNCC.receive(tr_MNCC_CALL_CONF_ind(cpars.mncc_callref));

	MGCP.receive(tr_CRCX) -> value mgcp_cmd;
	cpars.mgcp_call_id := f_MgcpCmd_extract_call_id(mgcp_cmd);

	/* Detect if the received CRCX is a wildcarded CRCX request. If yes,
	 * set an endpoint name that fits the pattern. If not, just use the
	 * endpoint name from the request */
	if (match(mgcp_cmd.line.ep, t_MGCP_EP_wildcard)) {
		cpars.mgcp_ep := "rtpbridge/1@mgw";
	} else {
		cpars.mgcp_ep := mgcp_cmd.line.ep;
	}

	/* Respond to CRCX with error */
	var MgcpResponse mgcp_rsp := {
		line := {
			code := "542",
			trans_id := mgcp_cmd.line.trans_id,
			string := "FORCED_FAIL"
		},
		sdp := omit
	}
	var MgcpParameter mgcp_rsp_param := {
		code := "Z",
		val := cpars.mgcp_ep
	};
	mgcp_rsp.params[0] := mgcp_rsp_param;
	MGCP.send(mgcp_rsp);

	timer T := 30.0;
	T.start;
	alt {
	[] T.timeout {
		setverdict(fail, "Timeout waiting for channel release");
		mtc.stop;
		}
	[] MNCC.receive { repeat; }
	[] GSUP.receive { repeat; }
	[] MGCP.receive(tr_DLCX(?)) -> value mgcp_cmd {
		MGCP.send(ts_DLCX_ACK2(mgcp_cmd.line.trans_id));
		f_create_mgcp_delete_ep(cpars.mgcp_ep);
		repeat;
		}
	[] MGCP.receive { repeat; }
	[] as_optional_cc_rel(cpars); /* repeats internally */
	[] as_expect_clear() { setverdict(pass); }
	}
}
testcase TC_mt_crcx_ran_reject() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_mt_crcx_ran_reject), 31);
	vc_conn.done;
}



/* Test MT Call T310 timer */
friend function f_tc_mt_t310(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	var CallParameters cpars := valueof(t_CallParams('123456'H, 0));
	var MgcpCommand mgcp_cmd;
	var PDU_BSSAP bssap;
	timer T310;

	f_init_handler(pars);

	/* Make sure X2 does not fire in this test. This test does not send a CN RTP port to osmo-msc, which will
	 * trigger X2 timeout. We want to test T310, so make X2 significantly longer than T310=30s. */
	f_vty_config(MSCVTY, "msc", "timer mgw X2 40");

	/* Initiate a MT call, establish connection */
	f_mt_call_start(cpars);

	/* MS->MSC: CALL CONFIRMED */
	RAN_CONN.send(ts_PDU_DTAP_MO(ts_ML3_MO_CC_CALL_CONF(cpars.transaction_id)));
	MNCC.receive(tr_MNCC_CALL_CONF_ind(cpars.mncc_callref));

	/* NOTE: MSC is expected to start T310 here */

	interleave {
	/* MSC->MGW: CRCX (first) */
	[] MGCP.receive(tr_CRCX) -> value mgcp_cmd {
		f_handle_crcx(cpars, mgcp_cmd); /* MSC<-MGW: OK */
		}

	/* BSC->BSC: BSSMAP ASSIGNMENT REQ */
	[] RAN_CONN.receive(tr_BSSMAP_AssignmentReq(omit, ?)) -> value bssap {
		RAN_CONN.send(ts_BSSMAP_AssignmentComplete(omit,
			aoip := f_ts_BSSMAP_IE_AoIP_TLA(cpars.bss_rtp_ip, cpars.bss_rtp_port),
			speechCodec := ts_BSSMAP_IE_SpeechCodec({ ts_CodecFR })));
		}

	/* MSC->MGW: MDCX */
	[] MGCP.receive(tr_MDCX) -> value mgcp_cmd {
		MGCP.send(ts_MDCX_ACK(mgcp_cmd.line.trans_id, cpars.mgw_conn_1.mgcp_connection_id,
			sdp := omit));
		}

	/* MSC->MGW: CRCX (second) */
	[] MGCP.receive(tr_CRCX) -> value mgcp_cmd {
		f_handle_crcx(cpars, mgcp_cmd); /* MSC<-MGW: OK */
		}

	[] MNCC.receive(tr_MNCC_RTP_CREATE(cpars.mncc_callref));
	}

	/* Reschedule the guard timeout */
	g_Tguard.start(30.0 + 10.0);

	/* NOTE: the BSC is expected to respond with CC ALERTING at this state, so
	 * the MSC would stop T310.  However, the idea is to verify T310 expiration
	 * here, so grab some popcorn and wait for MNCC DISC.ind. */
	T310.start(30.0 + 2.0);
	var MNCC_PDU mncc_rx;
	alt {
	[] T310.timeout {
		setverdict(fail, "Timeout waiting for MNCC DISC.ind due to T310");
		mtc.stop;
		}
	[] MNCC.receive(tr_MNCC_DISC_ind(cpars.mncc_callref)) {
		MNCC.send(ts_MNCC_REL_req(cpars.mncc_callref, valueof(ts_MNCC_cause(23))));
		log("Rx MNCC DISC.ind, T310.read yields ", T310.read);
		setverdict(pass);
		}
	[] MNCC.receive(MNCC_PDU:?) -> value mncc_rx {
		log("Rx ", mncc_rx);
		setverdict(fail, "Expected MNCC DISC.ind, got some other MNCC message instead");
		mtc.stop;
	}
	}

	RAN_CONN.receive(tr_PDU_DTAP_MT(tr_ML3_MT_CC_DISC(cpars.transaction_id)));
	RAN_CONN.receive(tr_PDU_DTAP_MT(tr_ML3_MT_CC_RELEASE(cpars.transaction_id)));
	RAN_CONN.send(ts_PDU_DTAP_MO(ts_ML3_MO_CC_REL_COMPL(cpars.transaction_id, '1'B)));

	alt {
	[] MGCP.receive(tr_DLCX(?)) -> value mgcp_cmd {
		MGCP.send(ts_DLCX_ACK2(mgcp_cmd.line.trans_id));
		// FIXME: f_create_mgcp_delete_ep(cpars.mgcp_ep);
		repeat;
		}
	[] as_expect_clear() { setverdict(pass); }
	}
}
testcase TC_mt_t310() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_mt_t310), 32);
	vc_conn.done;
}


/* Perform successful LU + MO call, then GSUP LocationCancel. Subscriber must be denied CM SERV */
friend function f_tc_gsup_cancel(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);
	var CallParameters cpars := valueof(t_CallParams('12345'H, 0));

	/* Location Update to make subscriber known */
	f_perform_lu();

	/* First MO call should succeed */
	f_mo_call(cpars);

	/* Cancel the subscriber in the VLR */
	GSUP.send(ts_GSUP_CL_REQ(g_pars.imsi, OSMO_GSUP_CANCEL_TYPE_WITHDRAW));
	alt {
	[] GSUP.receive(tr_GSUP_CL_RES(g_pars.imsi)) { }
	[] GSUP.receive(tr_GSUP_CL_ERR(g_pars.imsi)) {
		setverdict(fail, "Received GSUP Location Cancel Error");
		mtc.stop;
		}
	}

	/* Follow-up transactions should fail */
	var MobileIdentityLV mi := valueof(ts_MI_IMSI_LV(g_pars.imsi));
	var PDU_ML3_MS_NW l3_info := valueof(ts_CM_SERV_REQ(CM_TYPE_MO_CALL, mi));
	f_cl3_or_initial_ue(l3_info);
	alt {
	[] RAN_CONN.receive(tr_PDU_DTAP_MT(tr_CM_SERV_REJ)) { }
	[] as_unexp_bssap_msg();
	}

	f_expect_clear();
	setverdict(pass);
}
testcase TC_gsup_cancel() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_gsup_cancel), 33, verify_cell_id := false);
	vc_conn.done;
}


/* A5/1 only permitted on network side, and MS capable to do it */
private function f_tc_lu_imsi_auth_tmsi_encr_1_13(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	pars.net.expect_auth := true;
	pars.net.expect_ciph := true;
	pars.net.kc_support := '02'O;	/* A5/1 only */
	f_init_handler(pars);
	f_perform_lu();
}
testcase TC_lu_imsi_auth_tmsi_encr_1_13() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "network", "authentication required");
	f_vty_config(MSCVTY, "network", "encryption a5 1");

	vc_conn := f_start_handler(refers(f_tc_lu_imsi_auth_tmsi_encr_1_13), 34);
	vc_conn.done;
}

/* A5/3 only permitted on network side, and MS capable to do it */
private function f_tc_lu_imsi_auth_tmsi_encr_3_13(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	pars.net.expect_auth := true;
	pars.net.expect_ciph := true;
	pars.net.kc_support := '08'O;	/* A5/3 only */
	f_init_handler(pars);
	f_perform_lu();
}
testcase TC_lu_imsi_auth_tmsi_encr_3_13() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "network", "authentication required");
	f_vty_config(MSCVTY, "network", "encryption a5 3");

	vc_conn := f_start_handler(refers(f_tc_lu_imsi_auth_tmsi_encr_3_13), 35);
	vc_conn.done;
}

/* A5/3 only permitted on network side, and MS with only A5/1 support */
private function f_tc_lu_imsi_auth_tmsi_encr_3_1(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	pars.net.expect_auth := true;
	pars.net.expect_ciph := true;
	pars.net.kc_support := '08'O;	/* A5/3 only */
	pars.cm2.classmarkInformationType2_oct5.a5_3 := '0'B;
	f_init_handler(pars, 15.0);

	/* cannot use f_perform_lu() as we expect a reject */
	var PDU_ML3_MS_NW l3_lu := f_build_lu_imsi(g_pars.imsi);
	f_create_gsup_expect(hex2str(g_pars.imsi));
	f_cl3_or_initial_ue(l3_lu);
	if (pars.send_early_cm) {
		RAN_CONN.send(ts_BSSMAP_ClassmarkUpd(g_pars.cm2, g_pars.cm3));
	} else {
		pars.cm1.esind := '0'B;
	}
	f_mm_auth();
	alt {
	[] RAN_CONN.receive(tr_BSSMAP_ClassmarkReq) {
		RAN_CONN.send(ts_BSSMAP_ClassmarkUpd(g_pars.cm2, g_pars.cm3));
		repeat;
		}
	[] RAN_CONN.receive(tr_PDU_DTAP_MT(tr_ML3_MT_LU_Rej)) {
		f_expect_clear();
		}
	[] RAN_CONN.receive(tr_BSSMAP_CipherModeCmd(?,?)) {
		setverdict(fail, "CipherModeCommand despite no A5 intersection");
		mtc.stop;
		}
	[] as_unexp_bssap_msg();
	}
	setverdict(pass);
}
testcase TC_lu_imsi_auth_tmsi_encr_3_1() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "network", "authentication required");
	f_vty_config(MSCVTY, "network", "encryption a5 3");

	vc_conn := f_start_handler(refers(f_tc_lu_imsi_auth_tmsi_encr_3_1), 360, verify_cell_id := false);
	vc_conn.done;
}
testcase TC_lu_imsi_auth_tmsi_encr_3_1_no_cm() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "network", "authentication required");
	f_vty_config(MSCVTY, "network", "encryption a5 3");

	pars := f_init_pars(361, verify_cell_id := false);
	pars.send_early_cm := false;
	vc_conn := f_start_handler_with_pars(refers(f_tc_lu_imsi_auth_tmsi_encr_3_1), pars);
	vc_conn.done;
}
testcase TC_lu_imsi_auth_tmsi_encr_3_1_log_msc_debug() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "network", "authentication required");
	f_vty_config(MSCVTY, "network", "encryption a5 3");

	/* Make sure the MSC category is on DEBUG level to trigger the log
	 * message that is reported in OS#2947 to trigger the segfault */
	f_vty_config(MSCVTY, "log stderr", "logging level msc debug");

	vc_conn := f_start_handler(refers(f_tc_lu_imsi_auth_tmsi_encr_3_1), 362, verify_cell_id := false);
	vc_conn.done;
}

/* A5/1 + A5/3 only permitted on network side, and MS with only A5/2 support */
private function f_tc_lu_imsi_auth_tmsi_encr_13_2(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	pars.net.expect_auth := true;
	pars.net.expect_ciph := true;
	pars.net.kc_support := '0A'O;	/* A5/1 + A5/3 */
	pars.cm1.a5_1 := '1'B;
	pars.cm2.a5_1 := '1'B;
	pars.cm2.classmarkInformationType2_oct5.a5_3 := '0'B;
	pars.cm2.classmarkInformationType2_oct5.a5_2 := '1'B;
	f_init_handler(pars, 15.0);

	/* cannot use f_perform_lu() as we expect a reject */
	var PDU_ML3_MS_NW l3_lu := f_build_lu_imsi(g_pars.imsi);
	f_create_gsup_expect(hex2str(g_pars.imsi));
	f_cl3_or_initial_ue(l3_lu);
	RAN_CONN.send(ts_BSSMAP_ClassmarkUpd(g_pars.cm2, g_pars.cm3));
	f_mm_auth();
	alt {
	[] RAN_CONN.receive(tr_PDU_DTAP_MT(tr_ML3_MT_LU_Rej)) {
		f_expect_clear();
		}
	[] RAN_CONN.receive(tr_BSSMAP_CipherModeCmd(?,?)) {
		setverdict(fail, "CipherModeCommand despite no A5 intersection");
		mtc.stop;
		}
	[] as_unexp_bssap_msg();
	}
	setverdict(pass);
}
testcase TC_lu_imsi_auth_tmsi_encr_13_2() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "network", "authentication required");
	f_vty_config(MSCVTY, "network", "encryption a5 1 3");

	vc_conn := f_start_handler(refers(f_tc_lu_imsi_auth_tmsi_encr_13_2), 37, verify_cell_id := false);
	vc_conn.done;
}

/* A5/0 + A5/1 + A5/3 + a5/4 only permitted on network side, and MS with only A5/1 support */
private function f_tc_lu_imsi_auth_tmsi_encr_0134_1(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	pars.net.expect_auth := true;
	pars.net.expect_ciph := true;
	pars.net.kc_support := '03'O;	/*  A5/0 + A5/1 */
	pars.cm1.a5_1 := '0'B;
	pars.cm2.a5_1 := '0'B;
	pars.cm2.classmarkInformationType2_oct5.a5_3 := '0'B;
	pars.cm2.classmarkInformationType2_oct5.a5_2 := '0'B;
	pars.cm2.classmarkInformationType2_oct5.cm3 := '0'B;
	pars.cm3 := omit;
	pars.use_umts_aka := true;

	f_init_handler(pars, 15.0);
	f_perform_lu();
}
testcase TC_lu_imsi_auth_tmsi_encr_0134_1() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "network", "authentication required");
	f_vty_config(MSCVTY, "network", "encryption a5 0 1 3 4");

	vc_conn := f_start_handler(refers(f_tc_lu_imsi_auth_tmsi_encr_0134_1), 39);
	vc_conn.done;
}

/* A5/0 + A5/1 + A5/3 + a5/4 only permitted on network side, and MS with A5/3 + A5/4 support */
private function f_tc_lu_imsi_auth_tmsi_encr_0134_34(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	pars.net.expect_auth := true;
	pars.net.expect_ciph := true;
	pars.net.kc_support := '19'O;	/* A5/3 + A5/4 */
	pars.cm1.a5_1 := '1'B;
	pars.cm2.a5_1 := '1'B;
	pars.cm2.classmarkInformationType2_oct5.a5_3 := '1'B;
	pars.cm2.classmarkInformationType2_oct5.a5_2 := '0'B;
	pars.cm2.classmarkInformationType2_oct5.cm3 := '1'B;
	pars.cm3 := valueof(ts_CM3_default);
	pars.use_umts_aka := true;

	f_init_handler(pars, 15.0);
	f_perform_lu();
}
testcase TC_lu_imsi_auth_tmsi_encr_0134_34() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "network", "authentication required");
	f_vty_config(MSCVTY, "network", "encryption a5 0 1 3 4");

	vc_conn := f_start_handler(refers(f_tc_lu_imsi_auth_tmsi_encr_0134_34), 40);
	vc_conn.done;
}

/* A5/0 + A5/1 + A5/3 + a5/4 only permitted on network side, and MS with A5/3 support but no CM3 */
private function f_tc_lu_imsi_auth_tmsi_encr_0134_34_no_cm3(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	pars.net.expect_auth := true;
	pars.net.expect_ciph := true;
	pars.net.kc_support := '19'O;	/* A5/3 + A5/4 */
	pars.cm1.a5_1 := '1'B;
	pars.cm2.a5_1 := '1'B;
	pars.cm2.classmarkInformationType2_oct5.a5_3 := '1'B;
	pars.cm2.classmarkInformationType2_oct5.a5_2 := '0'B;
	pars.cm2.classmarkInformationType2_oct5.cm3 := '0'B;
	pars.cm3 := omit;
	pars.use_umts_aka := true;

	f_init_handler(pars, 15.0);
	f_perform_lu();
}
testcase TC_lu_imsi_auth_tmsi_encr_0134_34_no_cm3() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "network", "authentication required");
	f_vty_config(MSCVTY, "network", "encryption a5 0 1 3 4");

	vc_conn := f_start_handler(refers(f_tc_lu_imsi_auth_tmsi_encr_0134_34_no_cm3), 41);
	vc_conn.done;
}

/* A5/0 + A5/1 + A5/3 only permitted on network side, and MS with only A5/2 support */
private function f_tc_lu_imsi_auth_tmsi_encr_013_2(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	pars.net.expect_auth := true;
	pars.net.expect_ciph := true;
	pars.net.kc_support := '0B'O;	/* A5/1 + A5/3 */
	pars.cm1.a5_1 := '1'B;
	pars.cm2.a5_1 := '1'B;
	pars.cm2.classmarkInformationType2_oct5.a5_3 := '0'B;
	pars.cm2.classmarkInformationType2_oct5.a5_2 := '1'B;
	f_init_handler(pars, 15.0);
	f_perform_lu();
}
testcase TC_lu_imsi_auth_tmsi_encr_013_2() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "network", "authentication required");
	f_vty_config(MSCVTY, "network", "encryption a5 0 1 3");

	vc_conn := f_start_handler(refers(f_tc_lu_imsi_auth_tmsi_encr_013_2), 38);
	vc_conn.done;
}

/* LU followed by MT call (including paging) */
friend function f_tc_lu_and_mt_call(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);
	var CallParameters cpars := valueof(t_CallParams('12345'H, 0));
	cpars.use_osmux := pars.use_osmux;

	f_perform_lu();
	f_mt_call(cpars);
}
testcase TC_lu_and_mt_call() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_lu_and_mt_call), 39);
	vc_conn.done;
}

testcase TC_lu_and_mt_call_osmux() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init(1, false, true, true);

	vc_conn := f_start_handler(refers(f_tc_lu_and_mt_call), 39, 0, true, true);
	vc_conn.done;
}

/* LU followed by MT call (including paging) */
friend function f_tc_lu_and_mt_call_ipv6(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);
	var CallParameters cpars := valueof(t_CallParams('12345'H, 0));
	cpars.mgw_conn_1.mgw_rtp_ip := "::1";
	cpars.mgw_conn_2.mgw_rtp_ip := "::2";
	cpars.bss_rtp_ip := "::3";
	cpars.mncc_rtp_ip := "::9";
	f_perform_lu();
	f_mt_call(cpars);
}
testcase TC_lu_and_mt_call_ipv6() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_lu_and_mt_call_ipv6), 39);
	vc_conn.done;
}

/* MT call while already Paging */
friend function f_tc_lu_and_mt_call_already_paging(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	var CallParameters cpars := valueof(t_CallParams('123456'H, 0));
	var SmsParameters spars := valueof(t_SmsPars);
	var OCT4 tmsi;

	f_init_handler(pars);

	/* Perform location update */
	f_perform_lu();

	/* register an 'expect' for given IMSI (+TMSI) */
	if (isvalue(g_pars.tmsi)) {
		tmsi := g_pars.tmsi;
	} else {
		tmsi := 'FFFFFFFF'O;
	}
	f_ran_register_imsi(g_pars.imsi, tmsi);

	log("start Paging by an SMS");
	f_vty_sms_send(hex2str(pars.imsi), "2342", "Hello SMS");

	/* MSC->BSC: expect PAGING from MSC */
	f_expect_paging();

	log("MNCC signals MT call, before Paging Response");
	f_mt_call_initiate(cpars);
	f_ran_register_imsi(g_pars.imsi, g_pars.tmsi);

	f_sleep(0.5);
	log("phone answers Paging, expecting both SMS and MT call to be established");
	f_establish_fully(EST_TYPE_PAG_RESP);
	spars.tp.ud := 'C8329BFD064D9B53'O;
	interleave {
	[] RAN_CONN.receive(f_mt_sms_deliver_pdu(spars)) {
			log("Got SMS-DELIVER");
		};
	[] RAN_CONN.receive(tr_PDU_DTAP_MT(tr_ML3_MT_CC_SETUP(cpars.transaction_id, *, cpars.called_party))) {
			log("Got CC Setup");
		};
	}
	setverdict(pass);
	log("success, tear down");
	var default ccrel := activate(as_optional_cc_rel(cpars));
	if (g_pars.ran_is_geran) {
		RAN_CONN.send(ts_BSSMAP_ClearRequest(0));
	} else {
		RAN_CONN.send(ts_RANAP_IuReleaseRequest(ts_RanapCause_om_intervention));
	}
	f_expect_clear();
	deactivate(ccrel);
	f_vty_sms_clear(hex2str(g_pars.imsi));
}
testcase TC_lu_and_mt_call_already_paging() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init();
	pars := f_init_pars(391);
	vc_conn := f_start_handler_with_pars(refers(f_tc_lu_and_mt_call_already_paging), pars);
	vc_conn.done;
}

/* Test MO Call SETUP with DTMF */
private function f_tc_mo_setup_dtmf_dup(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);
	var CallParameters cpars := valueof(t_CallParams('12345'H, 0));

	f_perform_lu();
	f_mo_seq_dtmf_dup(cpars);
}
testcase TC_mo_setup_and_dtmf_dup() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_mo_setup_dtmf_dup), 39);
	vc_conn.done;
}

testcase TC_cr_before_reset() runs on MTC_CT {
	timer T := 4.0;
	var boolean reset_ack_seen := false;
	f_init_bssap_direct();

	f_sccp_adapter_start(g_bssap[0].sccpa);

	f_sleep(3.0);

	/* Make a blind connection attemt, to trigger the deadlock condition */
	BSSAP_DIRECT.send(ts_BSSAP_CONNECT_req(g_bssap[0].sccpa.sccp_addr_peer, g_bssap[0].sccpa.sccp_addr_own, 1, omit));

	/* Send a BSSMAP reset */
	BSSAP_DIRECT.send(ts_BSSAP_UNITDATA_req(g_bssap[0].sccpa.sccp_addr_peer, g_bssap[0].sccpa.sccp_addr_own, ts_BSSMAP_Reset(0)));
	T.start
	alt {
	[] BSSAP_DIRECT.receive(tr_BSSAP_UNITDATA_ind(?, ?, tr_BSSMAP_ResetAck)) {
		reset_ack_seen := true;
		repeat;
	}

	/* Acknowledge MSC sided reset requests */
	[] BSSAP_DIRECT.receive(tr_BSSAP_UNITDATA_ind(?, ?, tr_BSSMAP_Reset)) {
		BSSAP_DIRECT.send(ts_BSSAP_UNITDATA_req(g_bssap[0].sccpa.sccp_addr_peer, g_bssap[0].sccpa.sccp_addr_own, ts_BSSMAP_ResetAck));
		repeat;
	}

	/* Ignore all other messages (e.g CR from the connection request) */
	[] BSSAP_DIRECT.receive { repeat }

	/* If we got no BSSMAP RESET ACK back, then the MSC entered the
	 * deadlock situation. The MSC is then unable to respond to any
	 * further BSSMAP RESET or any other sort of traffic. */
	[reset_ack_seen == true] T.timeout { setverdict(pass) }
	[reset_ack_seen == false] T.timeout {
		setverdict(fail, "no BSSMAP RESET ACK seen!");
		mtc.stop;
	}
	}
}

/* Test MO Call with no response to RAN-side CRCX or DTAP Release */
friend function f_tc_mo_release_timeout(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);
	var CallParameters cpars := valueof(t_CallParams('12345'H, 0));
	var MNCC_PDU mncc;
	var MgcpCommand mgcp_cmd;

	/* Do not respond to the second CRCX */
	cpars.mgw_conn_2.resp := 0;

	f_perform_lu();
	f_mo_call_establish(cpars);

	var default ccrel := activate(as_optional_cc_rel(cpars));

	f_expect_clear(60.0);

	deactivate(ccrel);
}
testcase TC_mo_release_timeout() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_mo_release_timeout), 40);
	vc_conn.done;
}


/* LU followed by MT call (including paging) */
private function f_tc_lu_and_mt_call_no_dlcx_resp(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);
	var CallParameters cpars := valueof(t_CallParams('12345'H, 0));

	/* Intentionally disable the CRCX response */
	cpars.mgw_drop_dlcx := true;

	/* Perform location update and call */
	f_perform_lu();
	f_mt_call(cpars);
}
testcase TC_lu_and_mt_call_no_dlcx_resp() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	/* Perform an almost normal looking locationupdate + mt-call, but do
	 * not respond to the DLCX at the end of the call */
	vc_conn := f_start_handler(refers(f_tc_lu_and_mt_call_no_dlcx_resp), 41);
	vc_conn.done;

	/* Wait a guard period until the MGCP layer in the MSC times out,
	 * if the MSC is vulnerable to the use-after-free situation that is
	 * fixed by I78f1b6a9149488a4ad3f120c1e190a83c07d4b89 then it should
	 * segfault now */
	f_sleep(6.0);

	/* Run the init procedures once more. If the MSC has crashed, this
	 * this will fail */
	f_init();
}

/* Two BSSMAP resets from two different BSCs */
testcase TC_reset_two() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init(2);
	f_sleep(2.0);
	setverdict(pass);
}

/* Two BSSMAP resets from two different BSCs plus one IuCS RANAP Reset */
testcase TC_reset_two_1iu() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init(3);
	f_sleep(2.0);
	setverdict(pass);
}

/***********************************************************************
 * SMS Testing
 ***********************************************************************/

/* LU followed by MO SMS */
friend function f_tc_lu_and_mo_sms(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	var SmsParameters spars := valueof(t_SmsPars);

	f_init_handler(pars);

	/* Perform location update and call */
	f_perform_lu();

	f_establish_fully(EST_TYPE_MO_SMS);

	//spars.exp_rp_err := 96; /* invalid mandatory information */
	f_mo_sms(spars);

	f_expect_clear();
}
testcase TC_lu_and_mo_sms() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_tc_lu_and_mo_sms), 42);
	vc_conn.done;
}


private function f_vty_sms_send(charstring imsi, charstring msisdn, charstring text)
runs on BSC_ConnHdlr {
	f_vty_transceive(MSCVTY, "subscriber imsi "&imsi&" sms sender msisdn "&msisdn&" send "&text);
}

/* Remove still pending SMS */
private function f_vty_sms_clear(charstring imsi)
runs on BSC_ConnHdlr {
	f_vty_transceive(MSCVTY, "subscriber imsi " & imsi & " sms delete-all");
	f_vty_transceive(MSCVTY, "sms-queue clear");
}

/* LU followed by MT SMS */
friend function f_tc_lu_and_mt_sms(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	var SmsParameters spars := valueof(t_SmsPars);

	f_init_handler(pars);

	/* Perform location update and call */
	f_perform_lu();

	/* register an 'expect' for given IMSI (+TMSI) */
	f_ran_register_imsi(g_pars.imsi, g_pars.tmsi);

	f_vty_sms_send(hex2str(pars.imsi), "2342", "Hello SMS");

	/* MSC->BSC: expect PAGING from MSC */
	f_expect_paging();

	/* Establish DTAP / BSSAP / SCCP connection */
	f_establish_fully(EST_TYPE_PAG_RESP);

	spars.tp.ud := 'C8329BFD064D9B53'O;
	f_mt_sms(spars);

	f_expect_clear();
	f_ran_unregister_imsi(g_pars.imsi);
}
testcase TC_lu_and_mt_sms() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init();
	pars := f_init_pars(43);
	vc_conn := f_start_handler_with_pars(refers(f_tc_lu_and_mt_sms), pars);
	vc_conn.done;
}

/* SMS added while already Paging */
friend function f_tc_lu_and_mt_sms_already_paging(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	var SmsParameters spars := valueof(t_SmsPars);
	var OCT4 tmsi;

	f_init_handler(pars);

	f_perform_lu();

	/* register an 'expect' for given IMSI (+TMSI) */
	if (isvalue(g_pars.tmsi)) {
		tmsi := g_pars.tmsi;
	} else {
		tmsi := 'FFFFFFFF'O;
	}
	f_ran_register_imsi(g_pars.imsi, tmsi);

	log("first SMS");
	f_vty_sms_send(hex2str(pars.imsi), "2342", "Hello SMS");

	/* MSC->BSC: expect PAGING from MSC */
	f_expect_paging();

	log("second SMS");
	/* Now osmo-msc is in state "Paging pending", make sure that another SMS to be sent at this time just joins in
	 * with the pending paging. Another SMS: */
	f_vty_sms_send(hex2str(pars.imsi), "2342", "Another SMS");

	/* Establish DTAP / BSSAP / SCCP connection */
	f_establish_fully(EST_TYPE_PAG_RESP);

	spars.tp.ud := 'C8329BFD064D9B53'O;
	f_mt_sms(spars);

	spars.tp.ud := '41F79B8E2ECB41D3E614'O;
	f_mt_sms(spars);

	f_expect_clear();
}
testcase TC_lu_and_mt_sms_already_paging() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init();
	pars := f_init_pars(44);
	vc_conn := f_start_handler_with_pars(refers(f_tc_lu_and_mt_sms_already_paging), pars);
	vc_conn.done;
}

/* Paging for MT SMS but no response */
friend function f_tc_lu_and_mt_sms_paging_and_nothing(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	var SmsParameters spars := valueof(t_SmsPars);

	f_init_handler(pars, 150.0);

	/* Perform location update */
	f_perform_lu();

	/* register an 'expect' for given IMSI (+TMSI) */
	f_ran_register_imsi(g_pars.imsi, g_pars.tmsi);

	f_vty_sms_send(hex2str(pars.imsi), "2342", "Hello SMS");

	/* Expect the MSC to page exactly once */
	f_expect_paging();

	/* Wait some time to make sure the MSC is not delivering any further
	 * paging messages or anything else that could be unexpected. */
	timer T := 20.0;
	T.start
	alt {
	[] as_paging_any() {
		setverdict(fail, "paging seems not to stop!");
		mtc.stop;
		}
	[] as_unexp_bssap_msg();
	[] T.timeout {
		setverdict(pass);
		}
	}

	f_vty_sms_clear(hex2str(g_pars.imsi));

	setverdict(pass);
}
testcase TC_lu_and_mt_sms_paging_and_nothing() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init();
	pars := f_init_pars(1843);
	vc_conn := f_start_handler_with_pars(refers(f_tc_lu_and_mt_sms_paging_and_nothing), pars);
	vc_conn.done;
}

/* LU followed by MT SMS with repeated paging */
friend function f_tc_lu_and_mt_sms_paging_repeated(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	var SmsParameters spars := valueof(t_SmsPars);

	f_init_handler(pars);

	/* Perform location update and call */
	f_perform_lu();

	/* register an 'expect' for given IMSI (+TMSI) */
	f_ran_register_imsi(g_pars.imsi, g_pars.tmsi);

	f_vty_sms_send(hex2str(pars.imsi), "2342", "Hello SMS");

	log("Expecting first Paging");
	/* MSC->BSC: expect PAGING from MSC */
	f_expect_paging();

	if (g_pars.ran_is_geran) {
		log("GERAN: expect no further Paging");
	} else {
		log("UTRAN: expect more Paging");
	}

	timer T := 5.0;
	T.start;
	alt {
	[] as_paging() {
		if (g_pars.ran_is_geran) {
			setverdict(fail, "GERAN should not repeat Paging, but received a second Paging");
			mtc.stop;
		} else {
			log("UTRAN: second Paging received, as expected");
			setverdict(pass);
		}
		}
	[] as_paging_any() {
		setverdict(fail, "Rx unexpected BSSMAP/RANAP Paging");
		mtc.stop;
		}
	[] T.timeout {
		if (g_pars.ran_is_geran) {
			log("GERAN: No further Paging received, as expected");
			setverdict(pass);
		} else {
			setverdict(fail, "UTRAN: Expected a second Paging");
			mtc.stop;
		}
		}
	}

	/* Establish DTAP / BSSAP / SCCP connection */
	f_establish_fully(EST_TYPE_PAG_RESP);

	spars.tp.ud := 'C8329BFD064D9B53'O;
	f_mt_sms(spars);

	f_expect_clear();
}
testcase TC_lu_and_mt_sms_paging_repeated() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init();
	pars := f_init_pars(1844);
	vc_conn := f_start_handler_with_pars(refers(f_tc_lu_and_mt_sms_paging_repeated), pars);
	vc_conn.done;
}

/* mobile originated SMS from MS/BTS/BSC side to SMPP */
friend function f_tc_smpp_mo_sms(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	var SmsParameters spars := valueof(t_SmsPars);

	f_init_handler(pars);

	/* Perform location update so IMSI is known + registered in MSC/VLR */
	f_perform_lu();

	/* MS/UE submits a MO SMS */
	f_establish_fully(EST_TYPE_MO_SMS);
	f_mo_sms_submit(spars);

	var SMPP_PDU smpp;
	var template SMPP_PDU tr_smpp := tr_SMPP(c_SMPP_command_id_deliver_sm, ESME_ROK);
	tr_smpp.body.deliver_sm := {
		service_type := "CMT",
		source_addr_ton := network_specific,
		source_addr_npi := isdn,
		source_addr := hex2str(pars.msisdn),
		dest_addr_ton := f_sm_ton_from_gsm(spars.tp.da.tP_DA_NoPad.tP_TypeOfNumber),
		dest_addr_npi := f_sm_npi_from_gsm(spars.tp.da.tP_DA_NoPad.tP_NumberingPlanID),
		destination_addr := hex2str(spars.tp.da.tP_DA_NoPad.tP_DAValue),
		esm_class := '00000001'B,
		protocol_id := 0,
		priority_flag := 0,
		schedule_delivery_time := "",
		replace_if_present := 0,
		data_coding := '00000001'B,
		sm_default_msg_id := 0,
		sm_length := ?,
		short_message := spars.tp.ud,
		opt_pars := {
			{
				tag := user_message_reference,
				len := 2,
				opt_value := {
					int2_val := oct2int(spars.tp.msg_ref)
				}
			}
		}
	};
	alt {
	[] SMPP.receive(tr_smpp) -> value smpp {
		SMPP.send(ts_SMPP_DELIVER_SM_resp(ESME_ROK, smpp.header.seq_num));
		}
	[] SMPP.receive(tr_SMPP(c_SMPP_command_id_alert_notification, ESME_ROK)) { repeat; }
	}

	/* MSC terminates the SMS transaction with RP-ACK */
	f_mo_sms_wait_rp_ack(spars);

	f_expect_clear();
}
testcase TC_smpp_mo_sms() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config2(MSCVTY, { "smpp", "esme msc_tester"}, "default-route");
	vc_conn := f_start_handler(refers(f_tc_smpp_mo_sms), 44);
	vc_conn.done;
	f_vty_config2(MSCVTY, { "smpp", "esme msc_tester"}, "no default-route");
}

/* Test case for OS#4351: make sure that RP-ERROR from ESME is properly sent to the MS/UE */
friend function f_tc_smpp_mo_sms_rp_error(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	var SmsParameters spars := valueof(t_SmsPars);
	var SMPP_PDU smpp_pdu;
	timer T := 3.0;

	f_init_handler(pars);

	/* Perform location update */
	f_perform_lu();

	/* MS/UE submits a MO SMS */
	f_establish_fully(EST_TYPE_MO_SMS);
	f_mo_sms_submit(spars);

	/* ESME responds with an error (Invalid Destination Address) */
	T.start;
	alt {
	[] SMPP.receive(tr_SMPP(c_SMPP_command_id_deliver_sm, ESME_ROK, body := ?)) -> value smpp_pdu {
		SMPP.send(ts_SMPP_DELIVER_SM_resp(ESME_RINVDSTADR, smpp_pdu.header.seq_num));
		}
	[] SMPP.receive(tr_SMPP(c_SMPP_command_id_alert_notification, ESME_ROK)) { repeat; }
	[] T.timeout {
		setverdict(fail, "Timeout waiting for SMPP DELIVER-SM");
		mtc.stop;
		}
	}

	/* Expect RP-ERROR on BSSAP interface */
	spars.exp_rp_err := 1; /* FIXME: GSM411_RP_CAUSE_MO_NUM_UNASSIGNED */
	f_mo_sms_wait_rp_ack(spars);

	f_expect_clear();
}
testcase TC_smpp_mo_sms_rp_error() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config2(MSCVTY, { "smpp", "esme msc_tester"}, "default-route");
	vc_conn := f_start_handler(refers(f_tc_smpp_mo_sms_rp_error), 45);
	vc_conn.done;
	f_vty_config2(MSCVTY, { "smpp", "esme msc_tester"}, "no default-route");
}


/* Test MO-SMS from MS/BTS/BSC towards HLR (via GSUP) */
friend function f_tc_gsup_mo_sms(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	var SmsParameters spars := valueof(t_SmsPars);
	var GSUP_PDU gsup_msg_rx;
	var octetstring sm_tpdu;

	f_init_handler(pars);

	/* We need to inspect GSUP activity */
	f_create_gsup_expect(hex2str(g_pars.imsi));

	/* Perform location update */
	f_perform_lu();

	/* Send CM Service Request for SMS */
	f_establish_fully(EST_TYPE_MO_SMS);

	/* Prepare expected SM-RP-UI (SM TPDU) */
	enc_TPDU_RP_DATA_MS_SGSN_fast(
		valueof(ts_SMS_SUBMIT(spars.tp.msg_ref,
			spars.tp.da, spars.tp.pid, spars.tp.dcs,
			spars.tp.udl, spars.tp.ud)),
		sm_tpdu);

	var template GSUP_PDU mo_forwardSM := tr_GSUP_MO_FORWARD_SM_REQ(
		imsi := g_pars.imsi,
		sm_rp_mr := spars.rp.msg_ref,
		/* SM-RP-DA: SMSC address */
		sm_rp_da := tr_GSUP_SM_RP_DA_SMSC_ADDR(t_GSUP_SM_RP_Addr(
			number := spars.rp.smsc_addr.rP_NumberDigits,
			npi := spars.rp.smsc_addr.rP_NumberingPlanIdentification,
			ton := spars.rp.smsc_addr.rP_TypeOfNumber,
			ext := spars.rp.smsc_addr.rP_Ext)),
		/* SM-RP-OA: subscriber's MSISDN (filled in by MSC) */
		sm_rp_oa := tr_GSUP_SM_RP_OA_MSISDN(t_GSUP_SM_RP_Addr(
			number := g_pars.msisdn,
			/* NOTE: MSISDN in g_pars lacks this info, assuming defaults */
			npi := '0001'B, ton := '001'B, ext := '1'B)),
		/* TODO: can we use decmatch here? */
		sm_rp_ui := sm_tpdu
	);

	/* Submit an SMS on DTAP and expect MO-forwardSM-Req on GSUP */
	f_mo_sms_submit(spars);
	alt {
	[] GSUP.receive(mo_forwardSM) -> value gsup_msg_rx {
		log("RX MO-forwardSM-Req: ", gsup_msg_rx);
		setverdict(pass);
		}
	[] as_unexp_gsup_msg();
	}

	/* Trigger RP-ACK by sending MO-forwardSM-Res */
	GSUP.send(valueof(ts_GSUP_MO_FORWARD_SM_RES(
		imsi := g_pars.imsi,
		sm_rp_mr := spars.rp.msg_ref)));
	/* Expect RP-ACK on DTAP */
	f_mo_sms_wait_rp_ack(spars);

	f_expect_clear();
}
testcase TC_gsup_mo_sms() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "msc", "sms-over-gsup");
	vc_conn := f_start_handler(refers(f_tc_gsup_mo_sms), 88);
	vc_conn.done;
	f_vty_config(MSCVTY, "msc", "no sms-over-gsup");
}


/* Test MO-SMMA from MS/BTS/BSC towards HLR (via GSUP) */
friend function f_tc_gsup_mo_smma(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	var SmsParameters spars := valueof(t_SmsPars);
	var GSUP_PDU gsup_msg_rx;

	f_init_handler(pars);

	/* We need to inspect GSUP activity */
	f_create_gsup_expect(hex2str(g_pars.imsi));

	/* Perform location update */
	f_perform_lu();

	/* Send CM Service Request for SMS */
	f_establish_fully(EST_TYPE_MO_SMS);

	var template GSUP_PDU mo_ReadyForSM := tr_GSUP_MO_READY_FOR_SM_REQ(
		imsi := g_pars.imsi,
		sm_rp_mr := spars.rp.msg_ref,
		sm_alert_rsn := GSUP_SM_ALERT_RSN_TYPE_MEM_AVAIL
	);

	/* Submit an SMS on DTAP and expect MO-forwardSM-Req on GSUP */
	f_mo_smma(spars);
	alt {
	[] GSUP.receive(mo_ReadyForSM) -> value gsup_msg_rx {
		log("RX MO-ReadyForSM-Req: ", gsup_msg_rx);
		setverdict(pass);
		}
	[] as_unexp_gsup_msg();
	}

	/* Trigger RP-ACK by sending MO-forwardSM-Res */
	GSUP.send(valueof(ts_GSUP_MO_READY_FOR_SM_RES(
		imsi := g_pars.imsi,
		sm_rp_mr := spars.rp.msg_ref)));
	/* Expect RP-ACK on DTAP */
	f_mo_sms_wait_rp_ack(spars);

	f_expect_clear();
}
testcase TC_gsup_mo_smma() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "msc", "sms-over-gsup");
	vc_conn := f_start_handler(refers(f_tc_gsup_mo_smma), 89);
	vc_conn.done;
	f_vty_config(MSCVTY, "msc", "no sms-over-gsup");
}


/* Helper for sending MT SMS over GSUP */
private function f_gsup_forwardSM_req(SmsParameters spars, OCT1 mms := '00'O)
runs on BSC_ConnHdlr {
	var GSUP_SM_RP_Addr msisdn := valueof(t_GSUP_SM_RP_Addr(g_pars.msisdn));
	var GSUP_SM_RP_Addr smsc := valueof(t_GSUP_SM_RP_Addr(
		number := spars.rp.smsc_addr.rP_NumberDigits,
		npi := spars.rp.smsc_addr.rP_NumberingPlanIdentification,
		ton := spars.rp.smsc_addr.rP_TypeOfNumber,
		ext := spars.rp.smsc_addr.rP_Ext));

	GSUP.send(ts_GSUP_MT_FORWARD_SM_REQ(
		imsi := g_pars.imsi,
		/* NOTE: MSC should assign RP-MR itself */
		sm_rp_mr := 'FF'O,
		sm_rp_da := valueof(ts_GSUP_SM_RP_DA_MSISDN(msisdn)),
		sm_rp_oa := valueof(ts_GSUP_SM_RP_OA_SMSC_ADDR(smsc)),
		/* Encoded SMS TPDU (taken from Wireshark)
		 * FIXME: we should encode spars somehow */
		sm_rp_ui := '00068021436500008111328130858200'O,
		sm_rp_mms := mms
	));
}

/* Test successful MT-SMS (RP-ACK) over GSUP */
friend function f_tc_gsup_mt_sms_ack(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	var SmsParameters spars := valueof(t_SmsPars);

	f_init_handler(pars);

	/* We need to inspect GSUP activity */
	f_create_gsup_expect(hex2str(g_pars.imsi));

	/* Perform location update */
	f_perform_lu();

	/* Register an 'expect' for given IMSI (+TMSI) */
	f_ran_register_imsi(g_pars.imsi, g_pars.tmsi);

	var template GSUP_PDU mt_forwardSM_res := tr_GSUP_MT_FORWARD_SM_RES(
		imsi := g_pars.imsi,
		/* NOTE: MSC should assign RP-MR itself */
		sm_rp_mr := ?
	);

	/* Submit a MT SMS on GSUP */
	f_gsup_forwardSM_req(spars);

	/* Expect Paging Request and Establish DTAP / BSSAP / SCCP connection */
	f_expect_paging();
	f_establish_fully(EST_TYPE_PAG_RESP);

	/* Wait for MT SMS on DTAP */
	f_mt_sms_expect(spars);

	/* Send RP-ACK and expect MT-forwardSM-Res on GSUP */
	f_mt_sms_send_rp_ack(spars);
	alt {
	[] GSUP.receive(mt_forwardSM_res) {
		log("RX MT-forwardSM-Res (RP-ACK)");
		setverdict(pass);
		}
	[] as_unexp_gsup_msg();
	}

	f_expect_clear();
}
testcase TC_gsup_mt_sms_ack() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init();
	pars := f_init_pars(90);
	f_vty_config(MSCVTY, "msc", "sms-over-gsup");
	vc_conn := f_start_handler_with_pars(refers(f_tc_gsup_mt_sms_ack), pars);
	vc_conn.done;
	f_vty_config(MSCVTY, "msc", "no sms-over-gsup");
}


/* Test rejected MT-SMS (RP-ERROR) over GSUP */
friend function f_tc_gsup_mt_sms_err(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	var SmsParameters spars := valueof(t_SmsPars);
	var OCT1 sm_rp_cause := '78'O; /* dummy RP-Cause value */

	f_init_handler(pars);

	/* We need to inspect GSUP activity */
	f_create_gsup_expect(hex2str(g_pars.imsi));

	/* Perform location update */
	f_perform_lu();

	/* Register an 'expect' for given IMSI (+TMSI) */
	f_ran_register_imsi(g_pars.imsi, g_pars.tmsi);

	var template GSUP_PDU mt_forwardSM_err := tr_GSUP_MT_FORWARD_SM_ERR_MS(
		imsi := g_pars.imsi,
		/* NOTE: MSC should assign RP-MR itself */
		sm_rp_mr := ?,
		sm_rp_cause := sm_rp_cause
	);

	/* Submit a MT SMS on GSUP */
	f_gsup_forwardSM_req(spars);

	/* Expect Paging Request and Establish DTAP / BSSAP / SCCP connection */
	f_expect_paging();
	f_establish_fully(EST_TYPE_PAG_RESP);

	/* Wait for MT SMS on DTAP */
	f_mt_sms_expect(spars);

	/* Send RP-ERROR and expect MT-forwardSM-Err on GSUP */
	f_mt_sms_send_rp_error(spars, oct2int(sm_rp_cause));
	alt {
	[] GSUP.receive(mt_forwardSM_err) {
		log("RX MT-forwardSM-Err (RP-ERROR)");
		setverdict(pass);
		mtc.stop;
		}
	[] as_unexp_gsup_msg();
	}

	f_expect_clear();
}
testcase TC_gsup_mt_sms_err() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init();
	pars := f_init_pars(91);
	f_vty_config(MSCVTY, "msc", "sms-over-gsup");
	vc_conn := f_start_handler_with_pars(refers(f_tc_gsup_mt_sms_err), pars);
	vc_conn.done;
	f_vty_config(MSCVTY, "msc", "no sms-over-gsup");
}


/* Test SM-RP-MR assignment for MT-SMS over GSUP */
friend function f_tc_gsup_mt_sms_rp_mr(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	var SmsParameters spars1 := valueof(t_SmsPars); /* 1st SMS */
	var SmsParameters spars2 := valueof(t_SmsPars); /* 2nd SMS */

	f_init_handler(pars);

	/* We need to inspect GSUP activity */
	f_create_gsup_expect(hex2str(g_pars.imsi));

	/* Perform location update */
	f_perform_lu();

	/* Register an 'expect' for given IMSI (+TMSI) */
	f_ran_register_imsi(g_pars.imsi, g_pars.tmsi);

	/* Submit the 1st MT SMS on GSUP */
	log("TX MT-forwardSM-Req for the 1st SMS");
	f_gsup_forwardSM_req(spars1);

	/* Expect Paging Request and Establish DTAP / BSSAP / SCCP connection */
	f_expect_paging();
	f_establish_fully(EST_TYPE_PAG_RESP);

	/* Wait for 1st MT SMS on DTAP */
	f_mt_sms_expect(spars1);
	log("RX the 1st SMS on DTAP, DTAP TID is ", spars1.tid,
		", SM-RP-MR is ", spars1.rp.msg_ref);

	/* Submit the 2nd MT SMS on GSUP */
	log("TX MT-forwardSM-Req for the 2nd SMS");
	f_gsup_forwardSM_req(spars2);

	/* Wait for 2nd MT SMS on DTAP */
	f_mt_sms_expect(spars2);
	log("RX the 2nd SMS on DTAP, DTAP TID is ", spars2.tid,
		", SM-RP-MR is ", spars2.rp.msg_ref);

	/* Both transaction IDs shall be different */
	if (spars1.tid == spars2.tid) {
		setverdict(fail, "Both DTAP transaction IDs shall be different");
	}

	/* Both SM-RP-MR values shall be different */
	if (spars1.rp.msg_ref == spars2.rp.msg_ref) {
		setverdict(fail, "Both SM-RP-MR values shall be different");
	}

	/* Both SM-RP-MR values shall be assigned */
	if (spars1.rp.msg_ref == 'FF'O) {
		setverdict(fail, "Unassigned SM-RP-MR value for the 1st SMS");
	}
	if (spars2.rp.msg_ref == 'FF'O) {
		setverdict(fail, "Unassigned SM-RP-MR value for the 2nd SMS");
	}

	/* Send the 1st RP-ACK and expect MT-forwardSM-Res on GSUP */
	f_mt_sms_send_rp_ack(spars1);
	alt {
	[] GSUP.receive(tr_GSUP_MT_FORWARD_SM_RES(
		imsi := g_pars.imsi,
		sm_rp_mr := spars1.rp.msg_ref
	)) {
		log("RX MT-forwardSM-Res (RP-ACK)");
		setverdict(pass);
		}
	[] as_unexp_gsup_msg();
	}

	/* Send the 2nd RP-ACK and expect MT-forwardSM-Res on GSUP */
	f_mt_sms_send_rp_ack(spars2);
	alt {
	[] GSUP.receive(tr_GSUP_MT_FORWARD_SM_RES(
		imsi := g_pars.imsi,
		sm_rp_mr := spars2.rp.msg_ref
	)) {
		log("RX MT-forwardSM-Res (RP-ACK)");
		setverdict(pass);
		}
	[] as_unexp_gsup_msg();
	}

	f_expect_clear();
}
testcase TC_gsup_mt_sms_rp_mr() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init();
	pars := f_init_pars(92);
	f_vty_config(MSCVTY, "msc", "sms-over-gsup");
	vc_conn := f_start_handler_with_pars(refers(f_tc_gsup_mt_sms_rp_mr), pars);
	vc_conn.done;
	f_vty_config(MSCVTY, "msc", "no sms-over-gsup");
}


/* Test SM-RP-MR assignment for MT-SMS over GSUP */
friend function f_tc_gsup_mo_mt_sms_rp_mr(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	var SmsParameters spars_mo := valueof(t_SmsPars); /* MO SMMA */
	var SmsParameters spars_mt := valueof(t_SmsPars); /* MT SMS */

	f_init_handler(pars);

	/* We need to inspect GSUP activity */
	f_create_gsup_expect(hex2str(g_pars.imsi));

	/* Perform location update */
	f_perform_lu();

	/* Register an 'expect' for given IMSI (+TMSI) */
	f_ran_register_imsi(g_pars.imsi, g_pars.tmsi);

	/* Send CM Service Request for MO SMMA */
	f_establish_fully(EST_TYPE_MO_SMS);

	/* Submit MO SMMA on DTAP */
	log("Submit MO SMMA on DTAP, SM-RP-MR is '00'O");
	spars_mo.rp.msg_ref := '00'O;
	f_mo_smma(spars_mo);

	/* Expect MO-forwardSM-Req for MO SMMA on GSUP */
	alt {
	[] GSUP.receive(tr_GSUP_MO_READY_FOR_SM_REQ(
		imsi := g_pars.imsi,
		sm_rp_mr := spars_mo.rp.msg_ref,
		sm_alert_rsn := GSUP_SM_ALERT_RSN_TYPE_MEM_AVAIL
	)) {
		log("RX MO-ReadyForSM-Req, SM-RP-MR is '00'O");
		setverdict(pass);
		}
	[] as_unexp_gsup_msg();
	}

	/* Submit MT SMS on GSUP */
	log("TX MT-forwardSM-Req for the MT SMS");
	f_gsup_forwardSM_req(spars_mt);

	/* Wait for MT SMS on DTAP */
	f_mt_sms_expect(spars_mt);
	log("RX MT SMS on DTAP, DTAP TID is ", spars_mt.tid,
		", SM-RP-MR is ", spars_mt.rp.msg_ref);

	/* Both SM-RP-MR values shall be different */
	if (spars_mo.rp.msg_ref == spars_mt.rp.msg_ref) {
		setverdict(fail, "Both SM-RP-MR values shall be different");
	}

	/* SM-RP-MR value for MT SMS shall be assigned */
	if (spars_mt.rp.msg_ref == 'FF'O) {
		setverdict(fail, "Unassigned SM-RP-MR value for the MT SMS");
	}

	/* Trigger RP-ACK for MO SMMA by sending MO-forwardSM-Res */
	GSUP.send(valueof(ts_GSUP_MO_READY_FOR_SM_RES(
		imsi := g_pars.imsi,
		sm_rp_mr := spars_mo.rp.msg_ref)));
	/* Expect RP-ACK for MO SMMA on DTAP */
	f_mo_sms_wait_rp_ack(spars_mo);

	/* Send RP-ACK for MT SMS and expect MT-forwardSM-Res on GSUP */
	f_mt_sms_send_rp_ack(spars_mt);
	alt {
	[] GSUP.receive(tr_GSUP_MT_FORWARD_SM_RES(
		imsi := g_pars.imsi,
		sm_rp_mr := spars_mt.rp.msg_ref
	)) {
		log("RX MT-forwardSM-Res (RP-ACK)");
		setverdict(pass);
		}
	[] as_unexp_gsup_msg();
	}

	f_expect_clear();
}
testcase TC_gsup_mo_mt_sms_rp_mr() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init();
	pars := f_init_pars(93);
	f_vty_config(MSCVTY, "msc", "sms-over-gsup");
	vc_conn := f_start_handler_with_pars(refers(f_tc_gsup_mo_mt_sms_rp_mr), pars);
	vc_conn.done;
	f_vty_config(MSCVTY, "msc", "no sms-over-gsup");
}


/* Test multi-part MT-SMS over GSUP */
friend function f_tc_gsup_mt_multi_part_sms(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	var SmsParameters spars := valueof(t_SmsPars);

	f_init_handler(pars);

	/* We need to inspect GSUP activity */
	f_create_gsup_expect(hex2str(g_pars.imsi));

	/* Perform location update */
	f_perform_lu();

	/* Register an 'expect' for given IMSI (+TMSI) */
	f_ran_register_imsi(g_pars.imsi, g_pars.tmsi);

	var template GSUP_PDU mt_forwardSM_res := tr_GSUP_MT_FORWARD_SM_RES(
		imsi := g_pars.imsi,
		/* NOTE: MSC should assign RP-MR itself */
		sm_rp_mr := ?
	);

	/* Send 4 messages (NOTE: SM-RP-UI remains unchanged) */
	for (var integer i := 3; i >= 0; i := i-1) {
		/* Submit a MT SMS on GSUP (MMS is decremented) */
		f_gsup_forwardSM_req(spars, int2oct(i, 1));

		/* Expect Paging Request and Establish connection */
		if (i == 3) { /* ... only once! */
			f_expect_paging();
			f_establish_fully(EST_TYPE_PAG_RESP);
		}

		/* Wait for MT SMS on DTAP */
		f_mt_sms_expect(spars);

		/* Send RP-ACK and expect MT-forwardSM-Res on GSUP */
		f_mt_sms_send_rp_ack(spars);
		alt {
		[] GSUP.receive(mt_forwardSM_res) {
			log("RX MT-forwardSM-Res (RP-ACK)");
			setverdict(pass);
			}
		[] as_unexp_gsup_msg();
		}

		/* Keep some 'distance' between transmissions */
		f_sleep(1.5);
	}

	f_expect_clear();
}
testcase TC_gsup_mt_multi_part_sms() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init();
	pars := f_init_pars(91);
	f_vty_config(MSCVTY, "msc", "sms-over-gsup");
	vc_conn := f_start_handler_with_pars(refers(f_tc_gsup_mt_multi_part_sms), pars);
	vc_conn.done;
	f_vty_config(MSCVTY, "msc", "no sms-over-gsup");
}

/* Test X36 (LU delay) timer allowing to deliver MT SMS over the same connection */
friend function f_TC_gsup_mt_sms_lu_delay(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	var SmsParameters spars := valueof(t_SmsPars);

	f_init_handler(pars);

	/* We need to inspect GSUP activity */
	f_create_gsup_expect(hex2str(g_pars.imsi));

	/* Perform location update */
	f_perform_lu(expect_clear := false);

	/* Register an 'expect' for given IMSI (+TMSI) */
	f_ran_register_imsi(g_pars.imsi, g_pars.tmsi);

	var template GSUP_PDU mt_forwardSM_res := tr_GSUP_MT_FORWARD_SM_RES(
		imsi := g_pars.imsi,
		/* NOTE: MSC should assign RP-MR itself */
		sm_rp_mr := ?
	);

	/* Some delay to make sure the connection remains alive */
	f_sleep(0.5);

	/* Submit a MT SMS on GSUP */
	f_gsup_forwardSM_req(spars);

	/* Wait for MT SMS on DTAP */
	f_mt_sms_expect(spars);

	/* Send RP-ACK and expect MT-forwardSM-Res on GSUP */
	f_mt_sms_send_rp_ack(spars);
	alt {
	[] GSUP.receive(mt_forwardSM_res) {
		log("RX MT-forwardSM-Res (RP-ACK)");
		setverdict(pass);
		}
	[] as_unexp_gsup_msg();
	}

	f_expect_clear();
}
testcase TC_gsup_mt_sms_lu_delay() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init();
	pars := f_init_pars(92);
	f_vty_config(MSCVTY, "msc", "sms-over-gsup");
	f_vty_config(MSCVTY, "msc", "timer geran X36 2500"); /* 2.5s */
	vc_conn := f_start_handler_with_pars(refers(f_TC_gsup_mt_sms_lu_delay), pars);
	vc_conn.done;
	f_vty_config(MSCVTY, "msc", "timer geran X36 0");
	f_vty_config(MSCVTY, "msc", "no sms-over-gsup");
}

/* Test sending of GSUP MT-forwardSM-Err if MS does not respond to paging */
friend function f_TC_gsup_mt_sms_paging_timeout(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	const integer cause := 17; /* GMM_CAUSE_NET_FAIL */
	var SmsParameters spars := valueof(t_SmsPars);
	var boolean released := false;
	timer T;

	f_init_handler(pars);

	/* We need to inspect GSUP activity */
	f_create_gsup_expect(hex2str(g_pars.imsi));

	/* Perform location update */
	f_perform_lu();

	/* Register an 'expect' for given IMSI (+TMSI) */
	f_ran_register_imsi(g_pars.imsi, g_pars.tmsi);

	/* Submit a MT SMS on GSUP, expect paging */
	f_gsup_forwardSM_req(spars);
	f_expect_paging();

	/* ... MS does not respond to paging ... */

	T.start(10.0 + 2.0); /* X4 + 2 seconds */
	alt {
	/* Expect the MSC to indicate an error after paging timeout
	 * XXX: should we expect SM-RP-REF to be 'FF'O? */
	[] GSUP.receive(tr_GSUP_MT_FORWARD_SM_ERR_NET(g_pars.imsi, ?, cause));
	[] as_unexp_gsup_msg();
	[] as_unexp_bssap_msg();
	[] T.timeout {
		setverdict(fail, "Timeout waiting for GSUP MT-forwardSM-Err");
		}
	}
}
testcase TC_gsup_mt_sms_paging_timeout() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "msc", "sms-over-gsup");
	vc_conn := f_start_handler(refers(f_TC_gsup_mt_sms_paging_timeout), 93);
	vc_conn.done;
	f_vty_config(MSCVTY, "msc", "no sms-over-gsup");
}

/* Test sending of GSUP MT-forwardSM-Err if MS does not send RP-ACK */
friend function f_TC_gsup_mt_sms_conn_timeout(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	const integer cause := 17; /* GMM_CAUSE_NET_FAIL */
	var SmsParameters spars := valueof(t_SmsPars);
	var boolean released := false;
	timer T;

	f_init_handler(pars);

	/* We need to inspect GSUP activity */
	f_create_gsup_expect(hex2str(g_pars.imsi));

	/* Perform location update */
	f_perform_lu();

	/* Register an 'expect' for given IMSI (+TMSI) */
	f_ran_register_imsi(g_pars.imsi, g_pars.tmsi);

	/* Submit a MT SMS on GSUP, expect paging */
	f_gsup_forwardSM_req(spars);
	f_expect_paging();

	f_establish_fully(EST_TYPE_PAG_RESP);

	/* expect a MT SMS on DTAP */
	RAN_CONN.receive(f_mt_sms_deliver_pdu(spars));

	/* ... MS does not send RP-ACK ... */

	T.start(5.0 + 2.0); /* X1 + 2 seconds */
	alt {
	/* Expect the MSC to indicate an error after connection timeout
	 * XXX: should we expect SM-RP-REF to be 'FF'O? */
	[] GSUP.receive(tr_GSUP_MT_FORWARD_SM_ERR_NET(g_pars.imsi, ?, cause));
	/* Timeout of X1 (5s) will trigger connection release */
	[not released] as_expect_clear() {
		released := true;
		repeat;
		}
	[] as_unexp_gsup_msg();
	[] as_unexp_bssap_msg();
	[] T.timeout {
		setverdict(fail, "Timeout waiting for GSUP MT-forwardSM-Err");
		}
	}

	if (not released) {
		f_expect_clear();
	}
}
testcase TC_gsup_mt_sms_conn_timeout() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "msc", "sms-over-gsup");
	vc_conn := f_start_handler(refers(f_TC_gsup_mt_sms_conn_timeout), 94);
	vc_conn.done;
	f_vty_config(MSCVTY, "msc", "no sms-over-gsup");
}

/* LU followed by detach and will trigger a Purge MS */
friend function f_tc_gsup_lu_and_det(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars, t_guard := 8.0);
	f_perform_lu();

	f_imsi_detach_by_imsi();

	GSUP.receive(tr_GSUP_PURGE_MS_REQ(g_pars.imsi, OSMO_GSUP_CN_DOMAIN_CS));
	GSUP.send(ts_GSUP_PURGE_MS_RES(g_pars.imsi));
}
testcase TC_gsup_lu_and_det() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_gsup_lu_and_det), 103);
	vc_conn.done;
}

/* convert GSM L3 TON to SMPP_TON enum */
function f_sm_ton_from_gsm(BIT3 ton) return SMPP_TON {
	select (ton) {
	case ('000'B) { return unknown; }
	case ('001'B) { return international; }
	case ('010'B) { return national; }
	case ('011'B) { return network_specific; }
	case ('100'B) { return subscriber_number; }
	case ('101'B) { return alphanumeric; }
	case ('110'B) { return abbreviated; }
	}
	setverdict(fail, "Unknown TON ", ton);
	mtc.stop;
}
/* convert GSM L3 NPI to SMPP_NPI enum */
function f_sm_npi_from_gsm(BIT4 npi) return SMPP_NPI {
	select (npi) {
	case ('0000'B) { return unknown; }
	case ('0001'B) { return isdn; }
	case ('0011'B) { return data; }
	case ('0100'B) { return telex; }
	case ('0110'B) { return land_mobile; }
	case ('1000'B) { return national; }
	case ('1001'B) { return private_; }
	case ('1010'B) { return ermes; }
	}
	setverdict(fail, "Unknown NPI ", npi);
	mtc.stop;
}

/* build a SMPP_SM from SmsParameters */
function f_mt_sm_from_spars(SmsParameters spars)
runs on BSC_ConnHdlr return SMPP_SM {
	var SMPP_SM sm := {
		service_type := "CMT",
		source_addr_ton := f_sm_ton_from_gsm(spars.tp.da.tP_DA_NoPad.tP_TypeOfNumber),
		source_addr_npi := f_sm_npi_from_gsm(spars.tp.da.tP_DA_NoPad.tP_NumberingPlanID),
		source_addr := hex2str(spars.tp.da.tP_DA_NoPad.tP_DAValue),
		dest_addr_ton := international,
		dest_addr_npi := isdn,
		destination_addr := hex2str(g_pars.msisdn),
		esm_class := '00000001'B,
		protocol_id := 0,
		priority_flag := 0,
		schedule_delivery_time := "",
		validity_period := "",
		registered_delivery := '00000000'B,
		replace_if_present := 0,
		data_coding := '00000001'B,
		sm_default_msg_id := 0,
		sm_length := spars.tp.udl,
		short_message := spars.tp.ud,
		opt_pars := {}
	};
	return sm;
}

/* helper function to encode SMS from 'spars', send it via SMPP to MSC; receive it on MS side */
private function f_smpp_mt_sms(SmsParameters spars, boolean trans_mode) runs on BSC_ConnHdlr {
	var SMPP_SM sm := f_mt_sm_from_spars(spars);
	if (trans_mode) {
		sm.esm_class := '00000010'B;
	}

	/* actually cause MSC to send a SMS via SUBMIT-SM from SMPP side */
	SMPP.send(ts_SMPP_SUBMIT_SM(sm));
	if (not match(sm.esm_class, tr_ESM_CLASS_TRANSACTION)) {
		/* if we're not in SMPP transaction mode, we expect the SMPP-level ACK
		 * before we expect the SMS delivery on the BSC/radio side */
		SMPP.receive(tr_SMPP(c_SMPP_command_id_submit_sm_resp, ESME_ROK));
	}

	/* MSC->BSC: expect PAGING from MSC */
	f_expect_paging();
	/* Establish DTAP / BSSAP / SCCP connection */
	f_establish_fully(EST_TYPE_PAG_RESP);
	SMPP.receive(tr_SMPP(c_SMPP_command_id_alert_notification, ESME_ROK));

	f_mt_sms(spars);

	if (match(sm.esm_class, tr_ESM_CLASS_TRANSACTION)) {
		SMPP.receive(tr_SMPP(c_SMPP_command_id_submit_sm_resp, ESME_ROK));
	}
	f_expect_clear();
}

/* mobile terminated SMS, from SMPP to BSC/BTS/MS */
private function f_tc_smpp_mt_sms(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);

	/* Perform location update so IMSI is known + registered in MSC/VLR */
	f_perform_lu();
	SMPP.receive(tr_SMPP(c_SMPP_command_id_alert_notification, ESME_ROK));

	/* register an 'expect' for given IMSI (+TMSI) */
	f_ran_register_imsi(g_pars.imsi, g_pars.tmsi);

	var SmsParameters spars := valueof(t_SmsPars);
	/* TODO: test with more intelligent user data; test different coding schemes */
	spars.tp.ud := '00'O;
	spars.tp.udl := 1;

	/* first test the non-transaction store+forward mode */
	f_smpp_mt_sms(spars, false);

	/* then test the transaction mode */
	f_smpp_mt_sms(spars, true);

	f_ran_unregister_imsi(g_pars.imsi);
}
testcase TC_smpp_mt_sms() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_tc_smpp_mt_sms), 45);
	vc_conn.done;
}

/***********************************************************************
 * USSD Testing
 ***********************************************************************/

private altstep as_unexp_gsup_msg()
runs on BSC_ConnHdlr {
	var GSUP_PDU pdu;

	[] GSUP.receive(GSUP_PDU:?) -> value pdu {
		setverdict(fail, "Unknown/unexpected GSUP received: ", pdu);
		self.stop;
	}
}

private altstep as_unexp_bssap_msg()
runs on BSC_ConnHdlr {
	var PDU_DTAP_MT dtap;
	var PDU_BSSAP bssap;

	[] RAN_CONN.receive(PDU_DTAP_MT:?) -> value dtap {
		setverdict(fail, "Unknown/unexpected BSSAP/DTAP received: ", dtap);
		self.stop;
	}
	[] RAN_CONN.receive(PDU_BSSAP:?) -> value bssap {
		setverdict(fail, "Unknown/unexpected BSSAP received: ", bssap);
		self.stop;
	}
	[] RAN_CONN.receive {
		setverdict(fail, "Unknown/unexpected BSSAP received");
		self.stop;
	}
}

private function f_expect_gsup_msg(template GSUP_PDU msg,
				   float T_val := 2.0)
runs on BSC_ConnHdlr return GSUP_PDU {
	var GSUP_PDU gsup_msg_complete;
	timer T := T_val;

	T.start;
	alt {
	[] GSUP.receive(msg) -> value gsup_msg_complete {
		setverdict(pass);
		}
	/* We don't expect anything else */
	[] as_unexp_gsup_msg();
	[] as_unexp_bssap_msg();
	[] T.timeout {
		setverdict(fail, "Timeout waiting for GSUP message: ", msg);
		}
	}

	return gsup_msg_complete;
}

private function f_expect_mt_dtap_msg(template PDU_ML3_NW_MS msg,
				      float T_val := 2.0)
runs on BSC_ConnHdlr return PDU_ML3_NW_MS {
	var PDU_DTAP_MT bssap_msg_complete;
	timer T := T_val;

	T.start;
	alt {
	[] RAN_CONN.receive(tr_PDU_DTAP_MT(msg)) -> value bssap_msg_complete {
		setverdict(pass);
		}
	/* We don't expect anything else */
	[] as_unexp_gsup_msg();
	[] as_unexp_bssap_msg();
	[] T.timeout {
		setverdict(fail, "Timeout waiting for BSSAP message: ", msg);
		}
	}

	return bssap_msg_complete.dtap;
}

/* LU followed by MO USSD request */
friend function f_tc_lu_and_mo_ussd_single_request(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	f_init_handler(pars);

	/* Perform location update */
	f_perform_lu();

	/* Send CM Service Request for SS/USSD */
	f_establish_fully(EST_TYPE_SS_ACT);

	/* We need to inspect GSUP activity */
	f_create_gsup_expect(hex2str(g_pars.imsi));

	var template OCTN facility_req := f_USSD_FACILITY_IE_INVOKE(
		invoke_id := 5, /* Phone may not start from 0 or 1 */
		op_code := SS_OP_CODE_PROCESS_USS_REQ,
		ussd_string := "*#100#"
	);

	var template OCTN facility_rsp := f_USSD_FACILITY_IE_RETURN_RESULT(
		invoke_id := 5, /* InvokeID shall be the same for both REQ and RSP */
		op_code := SS_OP_CODE_PROCESS_USS_REQ,
		ussd_string := "Your extension is " & hex2str(g_pars.msisdn) & "\r"
	)

	/* Compose a new SS/REGISTER message with request */
	var template (value) PDU_ML3_MS_NW ussd_req := ts_ML3_MO_SS_REGISTER(
		tid := 1, /* We just need a single transaction */
		ti_flag := c_TIF_ORIG, /* Sent from the side that originates the TI */
		facility := valueof(facility_req)
	);

	/* Compose SS/RELEASE_COMPLETE template with expected response */
	var template PDU_ML3_NW_MS ussd_rsp := tr_ML3_MT_SS_RELEASE_COMPLETE(
		tid := 1, /* Response should arrive within the same transaction */
		ti_flag := c_TIF_REPL, /* Sent to the side that originates the TI */
		facility := valueof(facility_rsp)
	);

	/* Compose expected MSC -> HLR message */
	var template GSUP_PDU gsup_req := tr_GSUP_PROC_SS_REQ(
		imsi := g_pars.imsi,
		state := OSMO_GSUP_SESSION_STATE_BEGIN,
		ss := valueof(facility_req)
	);

	/* To be used for sending response with correct session ID */
	var GSUP_PDU gsup_req_complete;

	/* Request own number */
	RAN_CONN.send(ts_PDU_DTAP_MO(ussd_req));
	/* Expect GSUP message containing the SS payload */
	gsup_req_complete := f_expect_gsup_msg(gsup_req);

	/* Compose the response from HLR using received session ID */
	var template GSUP_PDU gsup_rsp := ts_GSUP_PROC_SS_REQ(
		imsi := g_pars.imsi,
		sid := gsup_req_complete.ies[1].val.session_id,
		state := OSMO_GSUP_SESSION_STATE_END,
		ss := valueof(facility_rsp)
	);

	/* Finally, HLR terminates the session */
	GSUP.send(gsup_rsp);
	/* Expect RELEASE_COMPLETE message with the response */
	f_expect_mt_dtap_msg(ussd_rsp);

	f_expect_clear();
}
testcase TC_lu_and_mo_ussd_single_request() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_tc_lu_and_mo_ussd_single_request), 46);
	vc_conn.done;
}


/* LU followed by MT USSD notification */
friend function f_tc_lu_and_mt_ussd_notification(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	f_init_handler(pars);

	/* Perform location update */
	f_perform_lu();

	f_ran_register_imsi(g_pars.imsi, g_pars.tmsi);

	/* We need to inspect GSUP activity */
	f_create_gsup_expect(hex2str(g_pars.imsi));

	/* Facility IE with network-originated USSD notification */
	var template OCTN facility_req := f_USSD_FACILITY_IE_INVOKE(
		op_code := SS_OP_CODE_USS_NOTIFY,
		ussd_string := "Mahlzeit!"
	);

	/* Facility IE with acknowledgment to the USSD notification */
	var template OCTN facility_rsp := enc_SS_FacilityInformation(
		/* In case of USSD notification, Return Result is empty */
		valueof(ts_SS_USSD_FACILITY_RETURN_RESULT_EMPTY())
	);

	/* Compose a new MT SS/REGISTER message with USSD notification */
	var template PDU_ML3_NW_MS ussd_ntf := tr_ML3_MT_SS_REGISTER(
		tid := 0, /* FIXME: most likely, it should be 0 */
		ti_flag := c_TIF_ORIG, /* Sent from the side that originates the TI */
		facility := valueof(facility_req)
	);

	/* Compose HLR -> MSC GSUP message */
	var template (value) GSUP_PDU gsup_req := ts_GSUP_PROC_SS_REQ(
		imsi := g_pars.imsi,
		sid := g_pars.gsup_sid,
		state := OSMO_GSUP_SESSION_STATE_BEGIN,
		ss := valueof(facility_req)
	);

	/* Send it to MSC and expect Paging Request */
	GSUP.send(gsup_req);
	f_expect_paging();

	/* Send Paging Response and expect USSD notification */
	f_establish_fully(EST_TYPE_PAG_RESP);
	/* Expect MT REGISTER message with USSD notification */
	f_expect_mt_dtap_msg(ussd_ntf);

	/* Compose a new MO SS/FACILITY message with empty response */
	var template (value) PDU_ML3_MS_NW ussd_rsp := ts_ML3_MO_SS_FACILITY(
		tid := 0, /* FIXME: it shall match the request tid */
		ti_flag := c_TIF_REPL, /* Sent to the side that originates the TI */
		facility := valueof(facility_rsp)
	);

	/* Compose expected MSC -> HLR GSUP message */
	var template GSUP_PDU gsup_rsp := tr_GSUP_PROC_SS_REQ(
		imsi := g_pars.imsi,
		sid := g_pars.gsup_sid,
		state := OSMO_GSUP_SESSION_STATE_CONTINUE,
		ss := valueof(facility_rsp)
	);

	/* MS sends response to the notification */
	RAN_CONN.send(ts_PDU_DTAP_MO(ussd_rsp));
	/* Expect GSUP message containing the SS payload */
	f_expect_gsup_msg(gsup_rsp);

	/* Compose expected MT SS/RELEASE COMPLETE message */
	var template PDU_ML3_NW_MS ussd_term := tr_ML3_MT_SS_RELEASE_COMPLETE(
		tid := 0, /* FIXME: it shall match the request tid */
		ti_flag := c_TIF_ORIG, /* Sent from the side that originates the TI */
		facility := omit
	);

	/* Compose MSC -> HLR GSUP message */
	var template GSUP_PDU gsup_term := ts_GSUP_PROC_SS_REQ(
		imsi := g_pars.imsi,
		sid := g_pars.gsup_sid,
		state := OSMO_GSUP_SESSION_STATE_END
	);

	/* Finally, HLR terminates the session */
	GSUP.send(gsup_term)
	/* Expect MT RELEASE COMPLETE without Facility IE */
	f_expect_mt_dtap_msg(ussd_term);

	f_expect_clear();
}
testcase TC_lu_and_mt_ussd_notification() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_tc_lu_and_mt_ussd_notification), 47);
	vc_conn.done;
}


/* LU followed by MT call and MO USSD request during this call */
friend function f_tc_lu_and_mo_ussd_during_mt_call(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	f_init_handler(pars);

	/* Call parameters taken from f_tc_lu_and_mt_call */
	var CallParameters cpars := valueof(t_CallParams('123456'H, 0));

	/* Perform location update */
	f_perform_lu();

	/* Establish a MT call */
	f_mt_call_establish(cpars);

	/* Hold the call for some time */
	f_sleep(1.0);

	var template OCTN facility_req := f_USSD_FACILITY_IE_INVOKE(
		op_code := SS_OP_CODE_PROCESS_USS_REQ,
		ussd_string := "*#100#"
	);

	var template OCTN facility_rsp := f_USSD_FACILITY_IE_RETURN_RESULT(
		op_code := SS_OP_CODE_PROCESS_USS_REQ,
		ussd_string := "Your extension is " & hex2str(g_pars.msisdn) & "\r"
	)

	/* Compose a new SS/REGISTER message with request */
	var template (value) PDU_ML3_MS_NW ussd_req := ts_ML3_MO_SS_REGISTER(
		tid := 1, /* We just need a single transaction */
		ti_flag := c_TIF_ORIG, /* Sent from the side that originates the TI */
		facility := valueof(facility_req)
	);

	/* Compose SS/RELEASE_COMPLETE template with expected response */
	var template PDU_ML3_NW_MS ussd_rsp := tr_ML3_MT_SS_RELEASE_COMPLETE(
		tid := 1, /* Response should arrive within the same transaction */
		ti_flag := c_TIF_REPL, /* Sent to the side that originates the TI */
		facility := valueof(facility_rsp)
	);

	/* Compose expected MSC -> HLR message */
	var template GSUP_PDU gsup_req := tr_GSUP_PROC_SS_REQ(
		imsi := g_pars.imsi,
		state := OSMO_GSUP_SESSION_STATE_BEGIN,
		ss := valueof(facility_req)
	);

	/* To be used for sending response with correct session ID */
	var GSUP_PDU gsup_req_complete;

	/* Request own number */
	RAN_CONN.send(ts_PDU_DTAP_MO(ussd_req));
	/* Expect GSUP message containing the SS payload */
	gsup_req_complete := f_expect_gsup_msg(gsup_req);

	/* Compose the response from HLR using received session ID */
	var template GSUP_PDU gsup_rsp := ts_GSUP_PROC_SS_REQ(
		imsi := g_pars.imsi,
		sid := gsup_req_complete.ies[1].val.session_id,
		state := OSMO_GSUP_SESSION_STATE_END,
		ss := valueof(facility_rsp)
	);

	/* Finally, HLR terminates the session */
	GSUP.send(gsup_rsp);
	/* Expect RELEASE_COMPLETE message with the response */
	f_expect_mt_dtap_msg(ussd_rsp);

	/* Hold the call for some time */
	f_sleep(1.0);

	/* Release the call (does Clear Complete itself) */
	f_call_hangup(cpars, true);
}
testcase TC_lu_and_mo_ussd_during_mt_call() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_tc_lu_and_mo_ussd_during_mt_call), 48);
	vc_conn.done;
}

/* BSSMAP Clear Request in the middle of a call, see OS#3062 */
friend function f_tc_mo_cc_bssmap_clear(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);
	var CallParameters cpars := valueof(t_CallParams('12345'H, 0));
	cpars.ran_clear_when_alerting := true;

	f_perform_lu();

	var default ccrel := activate(as_optional_cc_rel(cpars));
	f_mo_call_establish(cpars);
	f_expect_clear()
	deactivate(ccrel);

	f_sleep(1.0);
}
testcase TC_mo_cc_bssmap_clear() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_mo_cc_bssmap_clear), 43);
	vc_conn.done;
}


/* LU followed by MT call and MT USSD request during this call */
friend function f_tc_lu_and_mt_ussd_during_mt_call(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	f_init_handler(pars);

	/* Call parameters taken from f_tc_lu_and_mt_call */
	var CallParameters cpars := valueof(t_CallParams('123456'H, 0));

	/* Perform location update */
	f_perform_lu();

	/* Establish a MT call */
	f_mt_call_establish(cpars);

	/* Hold the call for some time */
	f_sleep(1.0);

	var template OCTN facility_req := f_USSD_FACILITY_IE_INVOKE(
		op_code := SS_OP_CODE_USS_REQUEST,
		ussd_string := "Please type anything..."
	);

	var template OCTN facility_rsp := f_USSD_FACILITY_IE_RETURN_RESULT(
		op_code := SS_OP_CODE_USS_REQUEST,
		ussd_string := "Nope."
	)

	/* Compose MT SS/REGISTER message with network-originated request */
	var template (value) PDU_ML3_NW_MS ussd_req := ts_ML3_MT_SS_REGISTER(
		tid := 0, /* FIXME: most likely, it should be 0 */
		ti_flag := c_TIF_ORIG, /* Sent from the side that originates the TI */
		facility := valueof(facility_req)
	);

	/* Compose HLR -> MSC GSUP message */
	var template (value) GSUP_PDU gsup_req := ts_GSUP_PROC_SS_REQ(
		imsi := g_pars.imsi,
		sid := g_pars.gsup_sid,
		state := OSMO_GSUP_SESSION_STATE_BEGIN,
		ss := valueof(facility_req)
	);

	/* Send it to MSC */
	GSUP.send(gsup_req);
	/* Expect MT REGISTER message with USSD request */
	f_expect_mt_dtap_msg(ussd_req);

	/* Compose a new MO SS/FACILITY message with response */
	var template (value) PDU_ML3_MS_NW ussd_rsp := ts_ML3_MO_SS_FACILITY(
		tid := 0, /* FIXME: it shall match the request tid */
		ti_flag := c_TIF_REPL, /* Sent to the side that originates the TI */
		facility := valueof(facility_rsp)
	);

	/* Compose expected MSC -> HLR GSUP message */
	var template GSUP_PDU gsup_rsp := tr_GSUP_PROC_SS_REQ(
		imsi := g_pars.imsi,
		sid := g_pars.gsup_sid,
		state := OSMO_GSUP_SESSION_STATE_CONTINUE,
		ss := valueof(facility_rsp)
	);

	/* MS sends response */
	RAN_CONN.send(ts_PDU_DTAP_MO(ussd_rsp));
	f_expect_gsup_msg(gsup_rsp);

	/* Compose expected MT SS/RELEASE COMPLETE message */
	var template PDU_ML3_NW_MS ussd_term := tr_ML3_MT_SS_RELEASE_COMPLETE(
		tid := 0, /* FIXME: it shall match the request tid */
		ti_flag := c_TIF_ORIG, /* Sent from the side that originates the TI */
		facility := omit
	);

	/* Compose MSC -> HLR GSUP message */
	var template GSUP_PDU gsup_term := ts_GSUP_PROC_SS_REQ(
		imsi := g_pars.imsi,
		sid := g_pars.gsup_sid,
		state := OSMO_GSUP_SESSION_STATE_END
	);

	/* Finally, HLR terminates the session */
	GSUP.send(gsup_term);
	/* Expect MT RELEASE COMPLETE without Facility IE */
	f_expect_mt_dtap_msg(ussd_term);

	/* Hold the call for some time */
	f_sleep(1.0);

	/* Release the call (does Clear Complete itself) */
	f_call_hangup(cpars, true);
}
testcase TC_lu_and_mt_ussd_during_mt_call() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_tc_lu_and_mt_ussd_during_mt_call), 49);
	vc_conn.done;
}

friend function f_TC_lu_and_ussd_notify_during_mt_call(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	var CallParameters cpars := valueof(t_CallParams);

	f_init_handler(pars);

	/* Perform location update */
	f_perform_lu();
	/* Initiate a MT call */
	f_mt_call_establish(cpars);

	/* Facility IE with network-originated USSD notification */
	var OCTN facility_req := f_USSD_FACILITY_IE_INVOKE(op_code := SS_OP_CODE_USS_NOTIFY,
							   ussd_string := "Knock knock");
	/* Facility IE with acknowledgment to the USSD notification */
	var OCTN facility_rsp := enc_SS_FacilityInformation(
		valueof(ts_SS_USSD_FACILITY_RETURN_RESULT_EMPTY())
	);

	/* HLR sends a USSD notification */
	GSUP.send(ts_GSUP_PROC_SS_REQ(imsi := g_pars.imsi,
				      sid := g_pars.gsup_sid,
				      state := OSMO_GSUP_SESSION_STATE_BEGIN,
				      ss := facility_req));
	/* ... and immediately terminates the session */
	GSUP.send(ts_GSUP_PROC_SS_REQ(imsi := g_pars.imsi,
				      sid := g_pars.gsup_sid,
				      state := OSMO_GSUP_SESSION_STATE_END));

	/* MSC forwards USSD notification to the MS */
	f_expect_mt_dtap_msg(tr_ML3_MT_SS_REGISTER(tid := 0,
						   ti_flag := c_TIF_ORIG,
						   facility := facility_req));
	/* ... immediately followed by the RELEASE COMPLETE message */
	f_expect_mt_dtap_msg(tr_ML3_MT_SS_RELEASE_COMPLETE(tid := 0,
							   ti_flag := c_TIF_ORIG,
							   facility := omit));

	/* MS didn't receive the RELEASE COMPLETE yet, so it responds */
	RAN_CONN.send(ts_PDU_DTAP_MO(ts_ML3_MO_SS_FACILITY(tid := 0,
							ti_flag := c_TIF_REPL,
							facility := facility_rsp)));
	/* this response is rejected because the SS transaction is gone */
	f_expect_mt_dtap_msg(tr_ML3_MT_SS_RELEASE_COMPLETE(tid := 0,
							   ti_flag := c_TIF_ORIG,
							   facility := omit));

	/* ... old osmo-msc crashes here (OS#6756) ...
	 * fixed in osmo-msc.git I724f0f0c9ef8611d3c3653e9370361b252127f72 */

	/* Release the call (does Clear Complete itself) */
	f_call_hangup(cpars, true);
}
testcase TC_lu_and_ussd_notify_during_mt_call() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_TC_lu_and_ussd_notify_during_mt_call), 111);
	vc_conn.done;
}


/* LU followed by MO USSD request and MO Release during transaction */
friend function f_tc_lu_and_mo_ussd_mo_release(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	f_init_handler(pars);

	/* Perform location update */
	f_perform_lu();

	/* Send CM Service Request for SS/USSD */
	f_establish_fully(EST_TYPE_SS_ACT);

	/* We need to inspect GSUP activity */
	f_create_gsup_expect(hex2str(g_pars.imsi));

	var template OCTN facility_ms_req := f_USSD_FACILITY_IE_INVOKE(
		invoke_id := 1, /* Initial request */
		op_code := SS_OP_CODE_PROCESS_USS_REQ,
		ussd_string := "*6766*266#"
	);

	var template OCTN facility_net_req := f_USSD_FACILITY_IE_INVOKE(
		invoke_id := 2, /* Counter request */
		op_code := SS_OP_CODE_USS_REQUEST,
		ussd_string := "Password?!?"
	)

	/* Compose MO SS/REGISTER message with request */
	var template (value) PDU_ML3_MS_NW ussd_ms_req := ts_ML3_MO_SS_REGISTER(
		tid := 1, /* We just need a single transaction */
		ti_flag := c_TIF_ORIG, /* Sent from the side that originates the TI */
		facility := valueof(facility_ms_req)
	);

	/* Compose expected MSC -> HLR message */
	var template GSUP_PDU gsup_ms_req := tr_GSUP_PROC_SS_REQ(
		imsi := g_pars.imsi,
		state := OSMO_GSUP_SESSION_STATE_BEGIN,
		ss := valueof(facility_ms_req)
	);

	/* To be used for sending response with correct session ID */
	var GSUP_PDU gsup_ms_req_complete;

	/* Initiate a new transaction */
	RAN_CONN.send(ts_PDU_DTAP_MO(ussd_ms_req));
	/* Expect GSUP request with original Facility IE */
	gsup_ms_req_complete := f_expect_gsup_msg(gsup_ms_req);

	/* Compose the response from HLR using received session ID */
	var template (value) GSUP_PDU gsup_net_req := ts_GSUP_PROC_SS_REQ(
		imsi := g_pars.imsi,
		sid := gsup_ms_req_complete.ies[1].val.session_id,
		state := OSMO_GSUP_SESSION_STATE_CONTINUE,
		ss := valueof(facility_net_req)
	);

	/* Compose expected MT SS/FACILITY template with counter request */
	var template PDU_ML3_NW_MS ussd_net_req := tr_ML3_MT_SS_FACILITY(
		tid := 1, /* Response should arrive within the same transaction */
		ti_flag := c_TIF_REPL, /* Sent to the side that originates the TI */
		facility := valueof(facility_net_req)
	);

	/* Send response over GSUP */
	GSUP.send(gsup_net_req);
	/* Expect MT SS/FACILITY message with counter request */
	f_expect_mt_dtap_msg(ussd_net_req);

	/* Compose MO SS/RELEASE COMPLETE */
	var template (value) PDU_ML3_MS_NW ussd_abort := ts_ML3_MO_SS_RELEASE_COMPLETE(
		tid := 1, /* Response should arrive within the same transaction */
		ti_flag := c_TIF_ORIG, /* Sent from the side that originates the TI */
		facility := omit
		/* TODO: cause? */
	);

	/* Compose expected HLR -> MSC abort message */
	var template GSUP_PDU gsup_abort := tr_GSUP_PROC_SS_REQ(
		imsi := g_pars.imsi,
		sid := gsup_ms_req_complete.ies[1].val.session_id,
		state := OSMO_GSUP_SESSION_STATE_END
	);

	/* Abort transaction */
	RAN_CONN.send(ts_PDU_DTAP_MO(ussd_abort));
	/* Expect GSUP message indicating abort */
	f_expect_gsup_msg(gsup_abort);

	f_expect_clear();
}
testcase TC_lu_and_mo_ussd_mo_release() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_tc_lu_and_mo_ussd_mo_release), 50);
	vc_conn.done;
}


/* LU followed by MO USSD request and MT Release due to timeout */
friend function f_tc_lu_and_ss_session_timeout(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	f_init_handler(pars);

	/* Perform location update */
	f_perform_lu();

	/* Send CM Service Request for SS/USSD */
	f_establish_fully(EST_TYPE_SS_ACT);

	/* We need to inspect GSUP activity */
	f_create_gsup_expect(hex2str(g_pars.imsi));

	var template OCTN facility_ms_req := f_USSD_FACILITY_IE_INVOKE(
		invoke_id := 1,
		op_code := SS_OP_CODE_PROCESS_USS_REQ,
		ussd_string := "#release_me");

	/* Compose MO SS/REGISTER message with request */
	var template (value) PDU_ML3_MS_NW ussd_ms_req := ts_ML3_MO_SS_REGISTER(
		tid := 1, /* An arbitrary transaction identifier */
		ti_flag := c_TIF_ORIG, /* Sent from the side that originates the TI */
		facility := valueof(facility_ms_req));

	/* Compose expected MSC -> HLR message */
	var template GSUP_PDU gsup_ms_req := tr_GSUP_PROC_SS_REQ(
		imsi := g_pars.imsi,
		state := OSMO_GSUP_SESSION_STATE_BEGIN,
		ss := valueof(facility_ms_req));

	/* To be used for sending response with correct session ID */
	var GSUP_PDU gsup_ms_req_complete;

	/* Initiate a new SS transaction */
	RAN_CONN.send(ts_PDU_DTAP_MO(ussd_ms_req));
	/* Expect GSUP request with original Facility IE */
	gsup_ms_req_complete := f_expect_gsup_msg(gsup_ms_req);

	/* Don't respond, wait for timeout */
	f_sleep(3.0);

	var template PDU_ML3_NW_MS dtap_rel := tr_ML3_MT_SS_RELEASE_COMPLETE(
		tid := 1, /* Should match the request's tid */
		ti_flag := c_TIF_REPL, /* Sent to the side that originates the TI */
		cause := *, /* TODO: expect some specific value */
		facility := omit);

	var template GSUP_PDU gsup_rel := tr_GSUP_PROC_SS_ERR(
		imsi := g_pars.imsi,
		sid := gsup_ms_req_complete.ies[1].val.session_id,
		state := OSMO_GSUP_SESSION_STATE_END,
		cause := ?); /* TODO: expect some specific value */

	/* Expect release on both interfaces */
	interleave {
	[] RAN_CONN.receive(tr_PDU_DTAP_MT(dtap_rel)) {  };
	[] GSUP.receive(gsup_rel) {  };
	}

	f_expect_clear();
	setverdict(pass);
}
testcase TC_lu_and_ss_session_timeout() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "msc", "ncss guard-timeout 3");
	vc_conn := f_start_handler(refers(f_tc_lu_and_ss_session_timeout), 51);
	vc_conn.done;
	f_vty_config(MSCVTY, "msc", "ncss guard-timeout 0");
}

/* MT (network-originated) USSD for unknown subscriber */
friend function f_tc_mt_ussd_for_unknown_subscr(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	var hexstring imsi := '000000000000000'H; /* Some unknown IMSI */
	var OCT4 sid := '20000222'O;

	f_init_handler(pars);
	f_ran_register_imsi(imsi, 'FFFFFFFF'O);
	f_create_gsup_expect(hex2str(imsi));

	var template (value) GSUP_PDU gsup_req := ts_GSUP_PROC_SS_REQ(
		imsi := imsi,
		sid := sid,
		state := OSMO_GSUP_SESSION_STATE_BEGIN,
		ss := f_rnd_octstring(23)
	);

	/* Error with cause GMM_CAUSE_IMSI_UNKNOWN */
	var template GSUP_PDU gsup_rsp := tr_GSUP_PROC_SS_ERR(
		imsi := imsi,
		sid := sid,
		state := OSMO_GSUP_SESSION_STATE_END,
		cause := 2 /* FIXME: introduce an enumerated type! */
	);

	/* Initiate a MT USSD notification */
	GSUP.send(gsup_req);

	/* Expect GSUP PROC_SS_ERROR message */
	f_expect_gsup_msg(gsup_rsp);
}
testcase TC_mt_ussd_for_unknown_subscr() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_tc_mt_ussd_for_unknown_subscr), 0);
	vc_conn.done;
}

/* MO (mobile-originated) SS/USSD for unknown transaction */
friend function f_tc_mo_ussd_for_unknown_trans(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	f_init_handler(pars);

	f_ran_register_imsi(g_pars.imsi, g_pars.tmsi);
	f_create_gsup_expect(hex2str(g_pars.imsi));

	/* Perform location update */
	f_perform_lu();

	/* Send CM Service Request for SS/USSD */
	f_establish_fully(EST_TYPE_SS_ACT);

	/* GSM 04.80 FACILITY message for a non-existing transaction */
	var template (value) PDU_ML3_MS_NW mo_ss_fac := ts_ML3_MO_SS_FACILITY(
		tid := 1, /* An arbitrary transaction identifier */
		ti_flag := c_TIF_ORIG, /* Sent from the side that originates the TI */
		facility := f_rnd_octstring(23) /* We don't care about the Facility IE */
	);

	/* GSM 04.80 RELEASE COMPLETE message for a non-existing transaction */
	var template (value) PDU_ML3_MS_NW mo_ss_rel := ts_ML3_MO_SS_RELEASE_COMPLETE(
		tid := 1, /* An arbitrary transaction identifier */
		ti_flag := c_TIF_ORIG, /* Sent from the side that originates the TI */
		facility := f_rnd_octstring(23) /* We don't care about the Facility IE */
	);

	/* Expected response from the network */
	var template PDU_ML3_NW_MS mt_ss_rel := tr_ML3_MT_SS_RELEASE_COMPLETE(
		tid := 1, /* Same as in the FACILITY message */
		ti_flag := c_TIF_REPL, /* Sent to the side that originates the TI */
		facility := omit
	);

	/* Send GSM 04.80 FACILITY for non-existing transaction */
	RAN_CONN.send(ts_PDU_DTAP_MO(mo_ss_fac));

	/* Expect GSM 04.80 RELEASE COMPLETE message */
	f_expect_mt_dtap_msg(mt_ss_rel);
	f_expect_clear();

	/* Send another CM Service Request for SS/USSD */
	f_establish_fully(EST_TYPE_SS_ACT);

	/* Send GSM 04.80 RELEASE COMPLETE for non-existing transaction */
	RAN_CONN.send(ts_PDU_DTAP_MO(mo_ss_rel));

	/* Expect GSM 04.80 RELEASE COMPLETE message */
	f_expect_mt_dtap_msg(mt_ss_rel);
	f_expect_clear();
}
testcase TC_mo_ussd_for_unknown_trans() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_tc_mo_ussd_for_unknown_trans), 111);
	vc_conn.done;
}

/* MT (network-originated) USSD for unknown session */
friend function f_tc_proc_ss_for_unknown_session(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	var OCT4 sid := '20000333'O;

	f_init_handler(pars);

	/* Perform location update */
	f_perform_lu();

	f_ran_register_imsi(g_pars.imsi, g_pars.tmsi);
	f_create_gsup_expect(hex2str(g_pars.imsi));

	/* Request referencing a non-existing SS session */
	var template (value) GSUP_PDU gsup_req := ts_GSUP_PROC_SS_REQ(
		imsi := g_pars.imsi,
		sid := sid,
		state := OSMO_GSUP_SESSION_STATE_CONTINUE,
		ss := f_rnd_octstring(23)
	);

	/* Error with some cause value */
	var template GSUP_PDU gsup_rsp := tr_GSUP_PROC_SS_ERR(
		imsi := g_pars.imsi,
		sid := sid,
		state := OSMO_GSUP_SESSION_STATE_END,
		cause := ? /* FIXME: introduce an enumerated type! */
	);

	/* Initiate a MT USSD notification */
	GSUP.send(gsup_req);

	/* Expect GSUP PROC_SS_ERROR message */
	f_expect_gsup_msg(gsup_rsp);
}
testcase TC_proc_ss_for_unknown_session() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_tc_proc_ss_for_unknown_session), 110);
	vc_conn.done;
}

/* MT (network-originated) USSD and no response to Paging Request */
friend function f_tc_proc_ss_paging_fail(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	f_init_handler(pars);

	/* Perform location update */
	f_perform_lu();

	f_ran_register_imsi(g_pars.imsi, g_pars.tmsi);
	f_create_gsup_expect(hex2str(g_pars.imsi));

	var template (value) GSUP_PDU gsup_req := ts_GSUP_PROC_SS_REQ(
		imsi := g_pars.imsi,
		sid := '20000444'O,
		state := OSMO_GSUP_SESSION_STATE_BEGIN,
		ss := f_rnd_octstring(23)
	);

	/* Error with some cause value */
	var template GSUP_PDU gsup_rsp := tr_GSUP_PROC_SS_ERR(
		imsi := g_pars.imsi,
		sid := '20000444'O,
		state := OSMO_GSUP_SESSION_STATE_END,
		cause := ? /* FIXME: introduce an enumerated type! */
	);

	/* Initiate a MT USSD notification, expect paging */
	GSUP.send(gsup_req);
	f_expect_paging();

	/* Wait up to 20 seconds for GSUP PROC_SS_ERROR message.
	 * OsmoMSC waits for Paging Response 10 seconds by default. */
	f_expect_gsup_msg(gsup_rsp, T_val := 20.0);
}
testcase TC_proc_ss_paging_fail() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_tc_proc_ss_paging_fail), 101);
	vc_conn.done;
}

/* MT (network-originated) USSD followed by immediate abort */
friend function f_tc_proc_ss_abort(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	var octetstring facility := f_rnd_octstring(23);
	var OCT4 sid := '20000555'O;

	f_init_handler(pars);

	/* Perform location update */
	f_perform_lu();

	f_ran_register_imsi(g_pars.imsi, g_pars.tmsi);
	f_create_gsup_expect(hex2str(g_pars.imsi));

	/* PROC_SS_REQ initiates a mobile-originated SS/USSD session */
	var template (value) GSUP_PDU gsup_req := ts_GSUP_PROC_SS_REQ(
		imsi := g_pars.imsi, sid := sid,
		state := OSMO_GSUP_SESSION_STATE_BEGIN,
		ss := facility
	);

	/* On the MS side, we expect GSM 04.80 REGISTER message */
	var template PDU_ML3_NW_MS dtap_reg := tr_ML3_MT_SS_REGISTER(
		tid := 0, /* Most likely, it should be 0 */
		ti_flag := c_TIF_ORIG, /* Sent from the side that originates the TI */
		facility := facility
	);

	/* PROC_SS_ERR with SESSION_STATE_END terminates the SS/USSD session */
	var template (value) GSUP_PDU gsup_abort := ts_GSUP_PROC_SS_ERR(
		imsi := g_pars.imsi, sid := sid,
		state := OSMO_GSUP_SESSION_STATE_END,
		cause := 0 /* FIXME: introduce an enumerated type! */
	);

	/* On the MS side, we expect GSM 04.80 REGISTER message */
	var template PDU_ML3_NW_MS dtap_rel := tr_ML3_MT_SS_RELEASE_COMPLETE(
		tid := 0, /* Most likely, it should be 0 */
		ti_flag := c_TIF_ORIG, /* Sent from the side that originates the TI */
		cause := *, /* FIXME: expect some specific cause value */
		facility := omit
	);

	/* Initiate a MT USSD with random payload */
	GSUP.send(gsup_req);
	/* Expect Paging Request */
	f_expect_paging();

	/* Send Paging Response and establish connection */
	f_establish_fully(EST_TYPE_PAG_RESP);
	/* Expect MT REGISTER message with random facility */
	f_expect_mt_dtap_msg(dtap_reg);

	/* HLR/EUSE decides to abort the session even
	 * before getting any response from the MS */
	 /* Initiate a MT USSD with random payload */
	GSUP.send(gsup_abort);

	/* Expect RELEASE COMPLETE on ths MS side */
	f_expect_mt_dtap_msg(dtap_rel);

	f_expect_clear();
}
testcase TC_proc_ss_abort() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_tc_proc_ss_abort), 102);
	vc_conn.done;
}

/* MO (mobile-originated) SS/USSD FACILITY for an unknown transaction,
 * and CM SERVICE REQUEST with wrong establishment cause prior to that.
 * This is an "evil MS" scenario that can be used to reproduce OS#6756.
 * More realistic scenario for this bug: TC_lu_and_ussd_notify_during_mt_call. */
friend function f_TC_mo_ussd_evil_ms(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	f_init_handler(pars);

	f_ran_register_imsi(g_pars.imsi, g_pars.tmsi);
	f_create_gsup_expect(hex2str(g_pars.imsi));

	/* Perform location update */
	f_perform_lu();

	/* Send CM Service Request indicating *wrong* reason */
	f_establish_fully(EST_TYPE_MO_CALL);

	/* GSM 04.80 FACILITY message for a non-existing transaction */
	var template (value) PDU_ML3_MS_NW mo_ss_fac := ts_ML3_MO_SS_FACILITY(
		tid := 1, /* An arbitrary transaction identifier */
		ti_flag := c_TIF_ORIG, /* Sent from the side that originates the TI */
		facility := f_rnd_octstring(23) /* We don't care about the Facility IE */
	);

	/* Expected response from the network */
	var template PDU_ML3_NW_MS mt_ss_rel := tr_ML3_MT_SS_RELEASE_COMPLETE(
		tid := 1, /* Same as in the FACILITY message */
		ti_flag := c_TIF_REPL, /* Sent to the side that originates the TI */
		facility := omit
	);

	/* Send GSM 04.80 FACILITY for non-existing transaction */
	RAN_CONN.send(ts_PDU_DTAP_MO(mo_ss_fac));

	/* Expect GSM 04.80 RELEASE COMPLETE message */
	f_expect_mt_dtap_msg(mt_ss_rel);
	f_expect_clear();
}
testcase TC_mo_ussd_evil_ms() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_TC_mo_ussd_evil_ms), 111);
	vc_conn.done;
}


/* Verify multiple concurrent MO SS/USSD transactions
 * (one subscriber - one transaction) */
testcase TC_multi_lu_and_mo_ussd() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn[16];
	var integer i;

	f_init();

	for (i := 0; i < sizeof(vc_conn); i := i + 1) {
		vc_conn[i] := f_start_handler(refers(f_tc_lu_and_mo_ussd_single_request), 210 + i);
	}

	for (i := 0; i < sizeof(vc_conn); i := i + 1) {
		vc_conn[i].done;
	}
}

/* Verify multiple concurrent MT SS/USSD transactions
 * (one subscriber - one transaction) */
testcase TC_multi_lu_and_mt_ussd() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn[16];
	var integer i;
	var OCT4 sid;

	f_init();

	for (i := 0; i < sizeof(vc_conn); i := i + 1) {
		sid := '200001'O & int2oct(i, 1); /* All transactions must use different session ID */
		vc_conn[i] := f_start_handler_with_pars(refers(f_tc_lu_and_mt_ussd_notification),
							f_init_pars(226 + i, gsup_sid := sid));
	}

	for (i := 0; i < sizeof(vc_conn); i := i + 1) {
		vc_conn[i].done;
	}
}


/* A5/1 only permitted on network side; attempt an invalid CIPHER MODE COMPLETE with A5/3 which MSC should reject. */
private function f_tc_cipher_complete_with_invalid_cipher(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	pars.net.expect_auth := true;
	pars.net.expect_ciph := true;
	pars.net.kc_support := '02'O;	/* A5/1 only */
	f_init_handler(pars);

	g_pars.vec := f_gen_auth_vec_2g();

	/* Can't use f_perform_lu() directly. Code below is based on it. */

	/* tell GSUP dispatcher to send this IMSI to us */
	f_create_gsup_expect(hex2str(g_pars.imsi));

	/* Send BSSAP_Conn_Req with COMPL L3 INFO to MSC */
	var PDU_ML3_MS_NW l3_lu := f_build_lu_imsi(g_pars.imsi)
	f_cl3_or_initial_ue(l3_lu);

	f_mm_auth();

	var OCT1 a5_net := f_alg_mask_from_cm(g_pars.cm2);
	var OCT1 a5_intersect := g_pars.net.kc_support and4b a5_net;
	alt {
	[] RAN_CONN.receive(tr_BSSMAP_CipherModeCmd(a5_intersect, g_pars.vec.kc)) {
		RAN_CONN.send(ts_BSSMAP_CipherModeCompl(int2oct(4 /* "accept" A5/3 */, 1)));
		}
	[] RAN_CONN.receive(tr_BSSMAP_CipherModeCmd(?, g_pars.vec.kc)) {
		setverdict(fail, "Wrong ciphering algorithm mask in CiphModCmd");
		mtc.stop;
		}
	[] as_unexp_bssap_msg();
	}
	f_expect_common_id();

	/* Expect LU reject from MSC. */
	alt {
	[] RAN_CONN.receive(tr_PDU_DTAP_MT(tr_ML3_MT_LU_Rej)) {
		setverdict(pass);
		}
	[] as_unexp_bssap_msg();
	}
	f_expect_clear();
}

testcase TC_cipher_complete_with_invalid_cipher() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "network", "encryption a5 1");

	vc_conn := f_start_handler(refers(f_tc_cipher_complete_with_invalid_cipher), 52, verify_cell_id := false);
	vc_conn.done;
}

/* Location Update with invalid (non-matching) MCC/MNC reported on BSSMAP level from BSC */
friend function f_tc_lu_with_invalid_mcc_mnc(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);

	/* tell GSUP dispatcher to send this IMSI to us */
	f_create_gsup_expect(hex2str(g_pars.imsi));

	/* modify the cell ID which will be used to construct the COMPLELTE L3 or InitialUE */
	g_pars.cell_id := valueof(ts_CellId_CGI('333'H, '22'H, 23, 42));

	/* Send BSSAP_Conn_Req with COMPL L3 INFO to MSC */
	var PDU_ML3_MS_NW l3_lu := f_build_lu_imsi(g_pars.imsi)
	f_cl3_or_initial_ue(l3_lu);
	f_expect_common_id();

	/* Expect LU reject from MSC. */
	alt {
	[] RAN_CONN.receive(tr_PDU_DTAP_MT(tr_ML3_MT_LU_Rej)) {
		setverdict(pass);
		}
	[] as_unexp_bssap_msg();
	}
	f_expect_clear(verify_vlr_cell_id:=false);
}
testcase TC_lu_with_invalid_mcc_mnc() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_tc_lu_with_invalid_mcc_mnc), 54);
	vc_conn.done;
}

private function f_tc_cipher_complete_without_alg(charstring id, BSC_ConnHdlrPars pars, octetstring kc_support) runs on BSC_ConnHdlr {
	pars.net.expect_auth := true;
	pars.net.expect_ciph := true;
	pars.net.kc_support := kc_support;
	f_init_handler(pars);

	g_pars.vec := f_gen_auth_vec_2g();

	/* Can't use f_perform_lu() directly. Code below is based on it. */

	/* tell GSUP dispatcher to send this IMSI to us */
	f_create_gsup_expect(hex2str(g_pars.imsi));

	/* Send BSSAP_Conn_Req with COMPL L3 INFO to MSC */
	var PDU_ML3_MS_NW l3_lu := f_build_lu_imsi(g_pars.imsi)
	f_cl3_or_initial_ue(l3_lu);

	f_mm_auth();

	var OCT1 a5_net := f_alg_mask_from_cm(g_pars.cm2);
	var OCT1 a5_intersect := g_pars.net.kc_support and4b a5_net;
	alt {
	[] RAN_CONN.receive(tr_BSSMAP_CipherModeCmd(a5_intersect, g_pars.vec.kc)) {
		RAN_CONN.send(ts_BSSMAP_CipherModeComplAlg(omit));
		}
	[] RAN_CONN.receive(tr_BSSMAP_ClassmarkReq) {
		RAN_CONN.send(ts_BSSMAP_ClassmarkUpd(g_pars.cm2, g_pars.cm3));
		repeat;
		}
	[] RAN_CONN.receive(tr_BSSMAP_CipherModeCmd(?, g_pars.vec.kc)) {
		setverdict(fail, "Wrong ciphering algorithm mask in CiphModCmd");
		mtc.stop;
		}
	[] as_unexp_bssap_msg();
	}
	f_expect_common_id();

	/* TODO: Verify MSC is using the best cipher available! How? */

	f_msc_lu_hlr();
	as_accept_reject_lu();
	f_expect_clear();
	setverdict(pass);
}

/* A5/1 only permitted on network side; attempt CIPHER MODE COMPLETE without specifying the accepted algorithm. */
private function f_tc_cipher_complete_1_without_cipher(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_tc_cipher_complete_without_alg(id, pars, '02'O /* A5/1 only */);
}

/* A5/3 only permitted on network side; attempt CIPHER MODE COMPLETE without specifying the accepted algorithm. */
private function f_tc_cipher_complete_3_without_cipher(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_tc_cipher_complete_without_alg(id, pars, '08'O /* A5/3 only */);
}

/* A5/1 + A5/3 permitted on network side; attempt CIPHER MODE COMPLETE without specifying the accepted algorithm. */
private function f_tc_cipher_complete_13_without_cipher(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_tc_cipher_complete_without_alg(id, pars, '0A'O /* A5/1 and A5/3 enabled */);
}

testcase TC_cipher_complete_1_without_cipher() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "network", "encryption a5 1");

	vc_conn := f_start_handler(refers(f_tc_cipher_complete_1_without_cipher), 53);
	vc_conn.done;
}

testcase TC_cipher_complete_3_without_cipher() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "network", "encryption a5 3");

	vc_conn := f_start_handler(refers(f_tc_cipher_complete_3_without_cipher), 54);
	vc_conn.done;
}

testcase TC_cipher_complete_13_without_cipher() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "network", "encryption a5 1 3");

	vc_conn := f_start_handler(refers(f_tc_cipher_complete_13_without_cipher), 55);
	vc_conn.done;
}

/* TODO (SMS):
   * different user data lengths
   * SMPP transaction mode with unsuccessful delivery
   * queued MT-SMS with no paging response + later delivery
   * different data coding schemes
   * multi-part SMS
   * user-data headers
   * TP-PID for SMS to SIM
   * behavior if SMS memory is full + RP-SMMA
   * delivery reports
   * SMPP osmocom extensions
   * more-messages-to-send
   * SMS during ongoing call (SACCH/SAPI3)
 */

/* TODO (General):
   * continue to send repeated MO signalling messages to keep channel open: does MSC tmeout?
   * malformed messages (missing IE, invalid message type): properly rejected?
   * MT call while LU or is ongoing: Do we use existing lchan or page while lchan active?
   * 3G/2G auth permutations
   * encryption algorithms vs. classmark vs. vty config
   * send new transaction after/during clear (like SMS, ...)
   * too long L3 INFO in DTAP
   * too long / padded BSSAP
   * too long / short TLV values
 */

/***********************************************************************
 * SGsAP Testing
 ***********************************************************************/

/* Check if a subscriber exists in the VLR */
private function f_ctrl_subscr_in_vlr(charstring imsi_or_msisdn) runs on BSC_ConnHdlr return boolean {

	var CtrlValue active_subsribers;
	var integer rc;
	active_subsribers := f_ctrl_get(IPA_CTRL, "subscriber-list-active-v1");

	rc := f_strstr(active_subsribers, imsi_or_msisdn);
	if (rc < 0) {
		return false;
	}

	return true;
}

/* Perform a Location Update at the A-Interface and run some checks to confirm
 * that everything is back to normal. */
private function f_sgsap_bssmap_screening()  runs on BSC_ConnHdlr {
	var SmsParameters spars := valueof(t_SmsPars);

	/* From now on, since we initiated LU from A-Interface, we expect no
	 * LastEutranPLMNId on Common Id, since the SGs interface should be gone
	 */
	g_pars.common_id_last_eutran_plmn := omit;

	/* Perform a location update, the SGs association is expected to fall
	 * back to NULL */
	f_perform_lu();
	f_ctrl_get_exp(IPA_CTRL, "fsm.SGs-UE.id.imsi:" & hex2str(g_pars.imsi) & ".state", "SGs-NULL");

	/* Trigger a paging request and expect the paging on BSSMAP, this is
	 * to make sure that pagings are sent throught the A-Interface again
	 * and not throught the SGs interface.*/
	f_ran_register_imsi(g_pars.imsi, g_pars.tmsi);
	f_vty_transceive(MSCVTY, "subscriber imsi " & hex2str(g_pars.imsi) & " paging");

	alt {
	[] as_paging() { setverdict(pass); }
	[] as_paging_any() {
		setverdict(fail, "Rx unexpected BSSMAP/RANAP Paging");
		mtc.stop;
		}
	[] SGsAP.receive {
		setverdict(fail, "Received unexpected message on SGs");
		}
	}

	/* Send an SMS to make sure that also payload messages are routed
	 * throught the A-Interface again */
	f_establish_fully(EST_TYPE_MO_SMS);
	f_mo_sms(spars);
	f_expect_clear();
}

private function f_tc_sgsap_reset(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	var charstring vlr_name;
	f_init_handler(pars);

	vlr_name := f_sgsap_reset_mme(mp_mme_name);
	log("VLR name: ", vlr_name);
	setverdict(pass);
	f_sleep(1.0);
}

testcase TC_sgsap_reset() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init(1, true);
	pars := f_init_pars(11810, true);
	vc_conn := f_start_handler_with_pars(refers(f_tc_sgsap_reset), pars);
	vc_conn.done;
}

/* like f_mm_auth() but for SGs */
function f_mm_auth_sgs() runs on BSC_ConnHdlr {
	if (g_pars.net.expect_auth) {
		g_pars.vec := f_gen_auth_vec_3g();
		var GSUP_IE auth_tuple := valueof(ts_GSUP_IE_AuthTuple2G3G(g_pars.vec.rand,
									   g_pars.vec.sres,
									   g_pars.vec.kc,
									   g_pars.vec.ik,
									   g_pars.vec.ck,
									   g_pars.vec.autn,
									   g_pars.vec.res));
		GSUP.receive(tr_GSUP_SAI_REQ(g_pars.imsi));
		GSUP.send(ts_GSUP_SAI_RES(g_pars.imsi, auth_tuple));
		SGsAP.receive(tr_ML3_MT_MM_AUTH_REQ_3G(g_pars.vec.rand, g_pars.vec.autn));
		SGsAP.send(ts_ML3_MT_MM_AUTH_RESP_3G(g_pars.vec.sres, g_pars.vec.res));
	}
}

/* like f_perform_lu(), but on SGs rather than BSSAP */
function f_sgs_perform_lu() runs on BSC_ConnHdlr {
	var octetstring mme_name := f_enc_dns_hostname(mp_mme_name);
	var PDU_SGsAP lur;
	var PDU_SGsAP lua;
	var PDU_SGsAP mm_info;
	var octetstring mm_info_dtap;
	var GsmMcc mcc;
	var GsmMnc mnc;
	var template (omit) TrackingAreaIdentityValue tai := omit;

	/* tell GSUP dispatcher to send this IMSI to us */
	f_create_gsup_expect(hex2str(g_pars.imsi));
	if (g_pars.common_id_last_eutran_plmn != omit) {
		f_dec_mcc_mnc(g_pars.common_id_last_eutran_plmn, mcc, mnc);
		tai := ts_SGsAP_TAI(mcc, mnc, 555);
	}
	lur := valueof(ts_SGsAP_LU_REQ(g_pars.imsi, mme_name, IMSI_attach,
					ts_SGsAP_LAI('901'H, '70'H, 2342),
					tai));
	/* Old LAI, if MS sends it */
	/* TMSI status, if MS has no valid TMSI */
	/* IMEISV, if it supports "automatic device detection" */
	/* TAI, if available in MME */
	/* E-CGI, if available in MME */
	SGsAP.send(lur);

	/* FIXME: is this really done over SGs?  The Ue is already authenticated
	 * via the MME ... */
	f_mm_auth_sgs();

	/* Expect MSC to perform LU with HLR */
	GSUP.receive(tr_GSUP_UL_REQ(g_pars.imsi));
	GSUP.send(ts_GSUP_ISD_REQ(g_pars.imsi, g_pars.msisdn));
	GSUP.receive(tr_GSUP_ISD_RES(g_pars.imsi));
	GSUP.send(ts_GSUP_UL_RES(g_pars.imsi));

	alt {
	[] SGsAP.receive(tr_SGsAP_LU_ACCEPT(g_pars.imsi, ?)) -> value lua {
		if (isvalue(lua.sGsAP_LOCATION_UPDATE_ACCEPT.newTMSIorIMSI.iD.iD.tmsi_ptmsi.octets)) {
			g_pars.tmsi :=lua.sGsAP_LOCATION_UPDATE_ACCEPT.newTMSIorIMSI.iD.iD.tmsi_ptmsi.octets
			SGsAP.send(ts_SGsAP_TMSI_REALL_CMPL(g_pars.imsi));
		}
		setverdict(pass);
		}
	[] SGsAP.receive(tr_SGsAP_LU_REJECT(g_pars.imsi, ?, ?)) {
		setverdict(fail, "Received LU-REJECT instead of ACCEPT");
		}
	[] SGsAP.receive {
		setverdict(fail, "Received unexpected message on SGs");
		}
	}

	/* Check MM information */
	if (mp_mm_info == true) {
		SGsAP.receive(tr_SGsAP_MM_INFO_REQ(g_pars.imsi, ?)) -> value mm_info;
		mm_info_dtap := '0532'O & mm_info.sGsAP_MM_INFORMATION_REQUEST.mM_Information.information;
		if (not match(dec_PDU_ML3_NW_MS(mm_info_dtap), tr_ML3_MT_MM_Info)) {
			setverdict(fail, "Unexpected MM Information");
		}
	}

	f_ctrl_get_exp(IPA_CTRL, "fsm.SGs-UE.id.imsi:" & hex2str(g_pars.imsi) & ".state", "SGs-ASSOCIATED");
}

private function f_tc_sgsap_lu(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);
	f_sgs_perform_lu();
	f_ctrl_get_exp(IPA_CTRL, "fsm.SGs-UE.id.imsi:" & hex2str(g_pars.imsi) & ".state", "SGs-ASSOCIATED");

	f_sgsap_bssmap_screening();

	setverdict(pass);
}
testcase TC_sgsap_lu() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init(1, true);
	pars := f_init_pars(11811, true);
	pars.common_id_last_eutran_plmn := f_enc_mcc_mnc('901'H, '70'H);
	vc_conn := f_start_handler_with_pars(refers(f_tc_sgsap_lu), pars);
	vc_conn.done;
}

/* Do LU by IMSI, refuse it on GSUP and expect LU REJ back to MS */
private function f_tc_sgsap_lu_imsi_reject(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);
	var PDU_SGsAP lur;

	f_create_gsup_expect(hex2str(g_pars.imsi));
	var octetstring mme_name := f_enc_dns_hostname(mp_mme_name);
	lur := valueof(ts_SGsAP_LU_REQ(g_pars.imsi, mme_name, IMSI_attach,
					ts_SGsAP_LAI('901'H, '70'H, 2342)));
	SGsAP.send(lur);

	GSUP.receive(tr_GSUP_UL_REQ(g_pars.imsi));
	GSUP.send(ts_GSUP_UL_ERR(g_pars.imsi, 23));
	alt {
	[] SGsAP.receive(tr_SGsAP_LU_REJECT(g_pars.imsi, ?, ?)) {
		setverdict(pass);
		}
	[] SGsAP.receive(tr_SGsAP_LU_ACCEPT(g_pars.imsi, ?)) {
		setverdict(fail, "Expecting LU REJ, but got ACCEPT");
		mtc.stop;
		}
	[] SGsAP.receive {
		setverdict(fail, "Received unexpected message on SGs");
		}
	}

	f_sgsap_bssmap_screening();

	setverdict(pass);
}
testcase TC_sgsap_lu_imsi_reject() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init(1, true);
	pars := f_init_pars(11812, true);

	vc_conn := f_start_handler_with_pars(refers(f_tc_sgsap_lu_imsi_reject), pars);
	vc_conn.done;
}

/* Do LU by IMSI, but then remain silent so that Ts6-1 times out */
private function f_tc_sgsap_lu_and_nothing(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	var octetstring mme_name := f_enc_dns_hostname(mp_mme_name);
	var PDU_SGsAP lur;

	f_init_handler(pars);

	/* tell GSUP dispatcher to send this IMSI to us */
	f_create_gsup_expect(hex2str(g_pars.imsi));

	lur := valueof(ts_SGsAP_LU_REQ(g_pars.imsi, mme_name, IMSI_attach,
					ts_SGsAP_LAI('901'H, '70'H, 2342)));
	/* Old LAI, if MS sends it */
	/* TMSI status, if MS has no valid TMSI */
	/* IMEISV, if it supports "automatic device detection" */
	/* TAI, if available in MME */
	/* E-CGI, if available in MME */
	SGsAP.send(lur);

	/* FIXME: is this really done over SGs?  The Ue is already authenticated
	 * via the MME ... */
	f_mm_auth_sgs();

	/* Expect MSC to perform LU with HLR */
	GSUP.receive(tr_GSUP_UL_REQ(g_pars.imsi));
	GSUP.send(ts_GSUP_ISD_REQ(g_pars.imsi, g_pars.msisdn));
	GSUP.receive(tr_GSUP_ISD_RES(g_pars.imsi));
	GSUP.send(ts_GSUP_UL_RES(g_pars.imsi));

	alt {
	[] SGsAP.receive(tr_SGsAP_LU_ACCEPT(g_pars.imsi, ?)) {
		setverdict(pass);
		}
	[] SGsAP.receive(tr_SGsAP_LU_REJECT(g_pars.imsi, ?, ?)) {
		setverdict(fail, "Received LU-REJECT instead of ACCEPT");
		}
	[] SGsAP.receive {
		setverdict(fail, "Received unexpected message on SGs");
		}
	}

	f_ctrl_get_exp(IPA_CTRL, "fsm.SGs-UE.id.imsi:" & hex2str(g_pars.imsi) & ".state", "SGs-ASSOCIATED");

	/* Wait until the VLR has abort the TMSI reallocation procedure */
	f_sleep(45.0);

	/* The outcome does not change the SGs state, see also 5.2.3.4 */
	f_ctrl_get_exp(IPA_CTRL, "fsm.SGs-UE.id.imsi:" & hex2str(g_pars.imsi) & ".state", "SGs-ASSOCIATED");

	f_sgsap_bssmap_screening();

	setverdict(pass);
}
testcase TC_sgsap_lu_and_nothing() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init(1, true);
	pars := f_init_pars(11813, true);

	vc_conn := f_start_handler_with_pars(refers(f_tc_sgsap_lu_and_nothing), pars);
	vc_conn.done;
}

private function f_tc_sgsap_expl_imsi_det_eps(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	f_init_handler(pars);
	f_sgs_perform_lu();
	f_sleep(3.0);

	var octetstring mme_name := f_enc_dns_hostname(mp_mme_name);
	SGsAP.send(ts_SGsAP_EPS_DETACH_IND(g_pars.imsi, mme_name, UE_initiated));
	SGsAP.receive(tr_SGsAP_EPS_DETACH_ACK(g_pars.imsi));
	f_ctrl_get_exp(IPA_CTRL, "fsm.SGs-UE.id.imsi:" & hex2str(g_pars.imsi) & ".state", "SGs-NULL");

	f_sgsap_bssmap_screening();

	setverdict(pass);
}
testcase TC_sgsap_expl_imsi_det_eps() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init(1, true);
	pars := f_init_pars(11814, true);
	pars.common_id_last_eutran_plmn := f_enc_mcc_mnc('901'H, '70'H);
	vc_conn := f_start_handler_with_pars(refers(f_tc_sgsap_expl_imsi_det_eps), pars);
	vc_conn.done;
}

private function f_tc_sgsap_impl_imsi_det_eps(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	f_init_handler(pars);
	f_sgs_perform_lu();
	f_sleep(3.0);

	var octetstring mme_name := f_enc_dns_hostname(mp_mme_name);
	SGsAP.send(ts_SGsAP_EPS_DETACH_IND(g_pars.imsi, mme_name, network_initiated));
	SGsAP.receive(tr_SGsAP_EPS_DETACH_ACK(g_pars.imsi));
	f_ctrl_get_exp(IPA_CTRL, "fsm.SGs-UE.id.imsi:" & hex2str(g_pars.imsi) & ".state", "SGs-NULL");

	f_sgsap_bssmap_screening();

	setverdict(pass);
}
testcase TC_sgsap_impl_imsi_det_eps() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init(1, true);
	pars := f_init_pars(11814, true);
	pars.common_id_last_eutran_plmn := f_enc_mcc_mnc('901'H, '70'H);
	vc_conn := f_start_handler_with_pars(refers(f_tc_sgsap_impl_imsi_det_eps), pars);
	vc_conn.done;
}

private function f_tc_sgsap_expl_imsi_det_noneps(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	f_init_handler(pars);
	f_sgs_perform_lu();
	f_sleep(3.0);

	var octetstring mme_name := f_enc_dns_hostname(mp_mme_name);
	SGsAP.send(ts_SGsAP_IMSI_DETACH_IND(g_pars.imsi, mme_name, combined_UE_initiated));
	SGsAP.receive(tr_SGsAP_IMSI_DETACH_ACK(g_pars.imsi));

	if (f_ctrl_subscr_in_vlr(hex2str(g_pars.imsi))) {
		setverdict(fail, "subscriber not removed from VLR");
	}

	f_sgsap_bssmap_screening();

	setverdict(pass);
}
testcase TC_sgsap_expl_imsi_det_noneps() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init(1, true);
	pars := f_init_pars(11815, true);
	pars.common_id_last_eutran_plmn := f_enc_mcc_mnc('901'H, '70'H);
	vc_conn := f_start_handler_with_pars(refers(f_tc_sgsap_expl_imsi_det_noneps), pars);
	vc_conn.done;
}

private function f_tc_sgsap_impl_imsi_det_noneps(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	f_init_handler(pars);
	f_sgs_perform_lu();
	f_sleep(3.0);

	var octetstring mme_name := f_enc_dns_hostname(mp_mme_name);
	SGsAP.send(ts_SGsAP_IMSI_DETACH_IND(g_pars.imsi, mme_name, implicit_network_initiated));
	SGsAP.receive(tr_SGsAP_IMSI_DETACH_ACK(g_pars.imsi));

	if (f_ctrl_subscr_in_vlr(hex2str(g_pars.imsi))) {
		setverdict(fail, "subscriber not removed from VLR");
	}

	f_sgsap_bssmap_screening();

	setverdict(pass);
}
testcase TC_sgsap_impl_imsi_det_noneps() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init(1, true);
	pars := f_init_pars(11815, true);
	pars.common_id_last_eutran_plmn := f_enc_mcc_mnc('901'H, '70'H);
	vc_conn := f_start_handler_with_pars(refers(f_tc_sgsap_impl_imsi_det_noneps), pars);
	vc_conn.done;
}

/* Trigger a paging request via VTY and send a paging reject in response */
private function f_tc_sgsap_paging_rej(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	f_init_handler(pars);
	f_sgs_perform_lu();
	f_sleep(1.0);

	var octetstring vlr_name := f_enc_dns_hostname(mp_vlr_name);
	var template PDU_SGsAP exp_resp := tr_SGsAP_PAGING_REQ(g_pars.imsi, vlr_name, CS_call_indicator, omit);
	var template  LocationAreaId exp_lai := ts_SGsAP_IE_Lai(valueof(ts_SGsAP_LAI('901'H, '70'H, 2342)));
	exp_resp.sGsAP_PAGING_REQUEST.locationAreaId := exp_lai;

	/* Initiate paging via VTY */
	f_vty_transceive(MSCVTY, "subscriber imsi " & hex2str(g_pars.imsi) & " paging");
	alt {
	[] SGsAP.receive(exp_resp) {
		setverdict(pass);
		}
	[] SGsAP.receive {
		setverdict(fail, "Received unexpected message on SGs");
		}
	}

	/* Now reject the paging */
	SGsAP.send(ts_SGsAP_PAGING_REJ(g_pars.imsi, IMSI_unknown));

	/* Wait for the states inside the MSC to settle and check the state
	 * of the SGs Association */
	f_sleep(1.0);
	f_ctrl_get_exp(IPA_CTRL, "fsm.SGs-UE.id.imsi:" & hex2str(g_pars.imsi) & ".state", "SGs-NULL");

	/* FIXME: At the moment we send an IMSI_unknown as cause code, which is fine,
	 * but we also need to cover tha case where the cause code indicates an
	 * "IMSI detached for EPS services". In those cases the VLR is expected to
	 * try paging on tha A/Iu interface. This will be another testcase similar to
	 * this one, but extended with checks for the presence of the A/Iu paging
	 * messages. */

	f_sgsap_bssmap_screening();

	setverdict(pass);
}
testcase TC_sgsap_paging_rej() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init(1, true);
	pars := f_init_pars(11816, true);
	pars.common_id_last_eutran_plmn := f_enc_mcc_mnc('901'H, '70'H);
	vc_conn := f_start_handler_with_pars(refers(f_tc_sgsap_paging_rej), pars);
	vc_conn.done;
}

/* Trigger a paging request via VTY and send a paging reject that indicates
 * that the subscriber intentionally rejected the call. */
private function f_tc_sgsap_paging_subscr_rej(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	f_init_handler(pars);
	f_sgs_perform_lu();
	f_sleep(1.0);

	var octetstring vlr_name := f_enc_dns_hostname(mp_vlr_name);
	var template PDU_SGsAP exp_resp := tr_SGsAP_PAGING_REQ(g_pars.imsi, vlr_name, CS_call_indicator, omit);
	var template  LocationAreaId exp_lai := ts_SGsAP_IE_Lai(valueof(ts_SGsAP_LAI('901'H, '70'H, 2342)));
	exp_resp.sGsAP_PAGING_REQUEST.locationAreaId := exp_lai;

	/* Initiate paging via VTY */
	f_vty_transceive(MSCVTY, "subscriber imsi " & hex2str(g_pars.imsi) & " paging");
	alt {
	[] SGsAP.receive(exp_resp) {
		setverdict(pass);
		}
	[] SGsAP.receive {
		setverdict(fail, "Received unexpected message on SGs");
		}
	}

	/* Now reject the paging */
	SGsAP.send(ts_SGsAP_PAGING_REJ(g_pars.imsi, user_rejected_mobile_terminating_CS_fallback_call));

	/* Wait for the states inside the MSC to settle and check the state
	 * of the SGs Association */
	f_sleep(1.0);
	f_ctrl_get_exp(IPA_CTRL, "fsm.SGs-UE.id.imsi:" & hex2str(g_pars.imsi) & ".state", "SGs-ASSOCIATED");

	/* FIXME: The VLR is supposed to trigger an User Determined User Busy (UDUB) as specified
	 * in 3GPP TS 24.082, this is not yet implemented in the MSC or in this tests, we need
	 * to check back how this works and how it can be tested */

	f_sgsap_bssmap_screening();

	setverdict(pass);
}
testcase TC_sgsap_paging_subscr_rej() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init(1, true);
	pars := f_init_pars(11817, true);
	pars.common_id_last_eutran_plmn := f_enc_mcc_mnc('901'H, '70'H);
	vc_conn := f_start_handler_with_pars(refers(f_tc_sgsap_paging_subscr_rej), pars);
	vc_conn.done;
}

/* Trigger a paging request via VTY and send an UE unreacable messge in response */
private function f_tc_sgsap_paging_ue_unr(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	f_init_handler(pars);
	f_sgs_perform_lu();
	f_sleep(1.0);

	var octetstring vlr_name := f_enc_dns_hostname(mp_vlr_name);
	var template PDU_SGsAP exp_resp := tr_SGsAP_PAGING_REQ(g_pars.imsi, vlr_name, CS_call_indicator, omit);
	var template  LocationAreaId exp_lai := ts_SGsAP_IE_Lai(valueof(ts_SGsAP_LAI('901'H, '70'H, 2342)));
	exp_resp.sGsAP_PAGING_REQUEST.locationAreaId := exp_lai;

	/* Initiate paging via VTY */
	f_vty_transceive(MSCVTY, "subscriber imsi " & hex2str(g_pars.imsi) & " paging");
	alt {
	[] SGsAP.receive(exp_resp) {
		setverdict(pass);
		}
	[] SGsAP.receive {
		setverdict(fail, "Received unexpected message on SGs");
		}
	}

	/* Now pretend that the UE is unreachable */
	SGsAP.send(ts_SGsAP_UE_UNREACHABLE(g_pars.imsi, UE_unreachable));

	/* Wait for the states inside the MSC to settle and check the state
	 * of the SGs Association. */
	f_sleep(1.0);
	f_ctrl_get_exp(IPA_CTRL, "fsm.SGs-UE.id.imsi:" & hex2str(g_pars.imsi) & ".state", "SGs-ASSOCIATED");

	f_sgsap_bssmap_screening();

	setverdict(pass);
}
testcase TC_sgsap_paging_ue_unr() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init(1, true);
	pars := f_init_pars(11818, true);
	pars.common_id_last_eutran_plmn := f_enc_mcc_mnc('901'H, '70'H);
	vc_conn := f_start_handler_with_pars(refers(f_tc_sgsap_paging_ue_unr), pars);
	vc_conn.done;
}

/* Trigger a paging request via VTY but don't respond to it */
private function f_tc_sgsap_paging_and_nothing(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	f_init_handler(pars);
	f_sgs_perform_lu();
	f_sleep(1.0);

	var octetstring vlr_name := f_enc_dns_hostname(mp_vlr_name);
	var template PDU_SGsAP exp_resp := tr_SGsAP_PAGING_REQ(g_pars.imsi, vlr_name, CS_call_indicator, omit);
	var template PDU_SGsAP exp_serv_abrt := ts_SGsAP_SERVICE_ABORT_REQ(g_pars.imsi);
	var template  LocationAreaId exp_lai := ts_SGsAP_IE_Lai(valueof(ts_SGsAP_LAI('901'H, '70'H, 2342)));
	exp_resp.sGsAP_PAGING_REQUEST.locationAreaId := exp_lai;

	/* Initiate paging via VTY */
	f_vty_transceive(MSCVTY, "subscriber imsi " & hex2str(g_pars.imsi) & " paging");
	alt {
	[] SGsAP.receive(exp_resp) {
		setverdict(pass);
		}
	[] SGsAP.receive {
		setverdict(fail, "Received unexpected message on SGs");
		}
	}

	/* While we are doing nothing, expect an SGsAP-SERVICE-ABORT-REQUEST
	 * after some time */
	timer T := 10.0;
	T.start
	alt {
		[] SGsAP.receive(exp_serv_abrt)
		{
			setverdict(pass);
		}
		[] SGsAP.receive {
			setverdict(fail, "unexpected SGsAP message received");
			self.stop;
		}
		[] T.timeout {
			setverdict(fail, "MSC did not send SGsAP-SERVICE-ABORT-REQUEST");
			self.stop;
		}
	}

	/* The SGs association must remain unchanged. */
	f_ctrl_get_exp(IPA_CTRL, "fsm.SGs-UE.id.imsi:" & hex2str(g_pars.imsi) & ".state", "SGs-ASSOCIATED");

	f_sgsap_bssmap_screening();

	setverdict(pass);
}
testcase TC_sgsap_paging_and_nothing() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init(1, true);
	pars := f_init_pars(11819, true);
	pars.common_id_last_eutran_plmn := f_enc_mcc_mnc('901'H, '70'H);
	vc_conn := f_start_handler_with_pars(refers(f_tc_sgsap_paging_and_nothing), pars);
	vc_conn.done;
}

/* Trigger a paging request via VTY and slip in an LU */
private function f_tc_sgsap_paging_and_lu(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	var octetstring vlr_name := f_enc_dns_hostname(mp_vlr_name);
	f_init_handler(pars);

	/* First we prepar the situation, where the SGs association is in state
	 * NULL and the confirmed by radio contact indicator is set to false
	 * as well. This can be archived by performing an SGs LU and then
	 * resetting the VLR */
	f_sgs_perform_lu();
	f_sgsap_reset_mme(mp_mme_name);
	f_sleep(1.0);
	f_ctrl_get_exp(IPA_CTRL, "fsm.SGs-UE.id.imsi:" & hex2str(g_pars.imsi) & ".state", "SGs-NULL");

	/* Perform a paging, expect the paging messages on the SGs interface */
	f_vty_transceive(MSCVTY, "subscriber imsi " & hex2str(g_pars.imsi) & " paging");
	alt {
	[] SGsAP.receive(tr_SGsAP_PAGING_REQ(pars.imsi, vlr_name, CS_call_indicator, omit)) {
		setverdict(pass);
		}
	[] SGsAP.receive {
		setverdict(fail, "Received unexpected message on SGs");
		}
	}

	/* Perform the LU as normal */
	f_sgs_perform_lu();
	f_ctrl_get_exp(IPA_CTRL, "fsm.SGs-UE.id.imsi:" & hex2str(g_pars.imsi) & ".state", "SGs-ASSOCIATED");

	/* Expect a new paging request right after the LU */
	alt {
	[] SGsAP.receive(tr_SGsAP_PAGING_REQ(pars.imsi, vlr_name, CS_call_indicator, omit)) {
		setverdict(pass);
		}
	[] SGsAP.receive {
		setverdict(fail, "Received unexpected message on SGs");
		}
	}

	/* Test is done now, lets round everything up by rejecting the paging
	 * cleanly. */
	SGsAP.send(ts_SGsAP_PAGING_REJ(g_pars.imsi, user_rejected_mobile_terminating_CS_fallback_call));
	f_ctrl_get_exp(IPA_CTRL, "fsm.SGs-UE.id.imsi:" & hex2str(g_pars.imsi) & ".state", "SGs-ASSOCIATED");

	f_sgsap_bssmap_screening();

	setverdict(pass);
}
testcase TC_sgsap_paging_and_lu() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init(1, true);
	pars := f_init_pars(11820, true);
	pars.common_id_last_eutran_plmn := f_enc_mcc_mnc('901'H, '70'H);
	vc_conn := f_start_handler_with_pars(refers(f_tc_sgsap_paging_and_lu), pars);
	vc_conn.done;
}

/* Send unexpected unit-data through the SGs interface */
private function f_tc_sgsap_unexp_ud(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);
	f_sleep(1.0);

	/* This simulates what happens when a subscriber without SGs
	 * association gets unitdata via the SGs interface. */

	/* Make sure the subscriber exists and the SGs association
	 * is in NULL state */
	f_perform_lu();
	f_ctrl_get_exp(IPA_CTRL, "fsm.SGs-UE.id.imsi:" & hex2str(g_pars.imsi) & ".state", "SGs-NULL");

	/* Send some random unit data, the MSC/VLR should send a release
	 * immediately. */
	SGsAP.send(ts_SGsAP_UL_UD(pars.imsi,'1234'O));
	SGsAP.receive(tr_SGsAP_RELEASE_REQ(pars.imsi, IMSI_detached_for_EPS_nonEPS_services));

	f_sgsap_bssmap_screening();

	setverdict(pass);
}
testcase TC_sgsap_unexp_ud() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init(1, true);
	pars := f_init_pars(11821, true);
	vc_conn := f_start_handler_with_pars(refers(f_tc_sgsap_unexp_ud), pars);
	vc_conn.done;
}

/* Send unsolicited unit-data through the SGs interface */
private function f_tc_sgsap_unsol_ud(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);
	f_sleep(1.0);

	/* This simulates what happens when the MME attempts to send unitdata
	 * to a subscriber that is completely unknown to the VLR */

	/* Send some random unit data, the MSC/VLR should send a release
	 * immediately. */
	SGsAP.send(ts_SGsAP_UL_UD(pars.imsi,'1234'O));
	SGsAP.receive(tr_SGsAP_RELEASE_REQ(pars.imsi, IMSI_unknown));

	f_sgsap_bssmap_screening();

	/* clean-up VLR state about this subscriber */
	f_imsi_detach_by_imsi();

	setverdict(pass);
}
testcase TC_sgsap_unsol_ud() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init(1, true);
	pars := f_init_pars(11822, true);
	vc_conn := f_start_handler_with_pars(refers(f_tc_sgsap_unsol_ud), pars);
	vc_conn.done;
}

private altstep as_other_sms_sgs() runs on BSC_ConnHdlr {
	/* FIXME: Match an actual payload (second questionmark), the type is
	 * octetstring, how do we use a tr_PDU_DTAP_MT here? */
	[] SGsAP.receive(tr_SGsAP_DL_UD(?,?)) {
		setverdict(fail, "Unexpected SMS related PDU from MSC");
		mtc.stop;
	}
}

/* receive a MT-SMS delivered from the MSC/SMSC over an already existing SGsAP connection */
function f_mt_sms_sgs(inout SmsParameters spars)
runs on BSC_ConnHdlr {
	var template (value) TPDU_RP_DATA_MS_SGSN tp_mo;
	var template (value) RPDU_MS_SGSN rp_mo;
	var template (value) PDU_ML3_MS_NW l3_mo;

	var template TPDU_RP_DATA_SGSN_MS tp_mt;
	var template RPDU_SGSN_MS rp_mt;
	var template PDU_ML3_NW_MS l3_mt;

	var PDU_ML3_NW_MS sgsap_l3_mt;

	var default d := activate(as_other_sms_sgs());

	/* Expect CP-DATA(RP-DATA(SMS-DELIVER)) */
	tp_mt := tr_SMS_DELIVER(?, spars.tp.ud, spars.tp.pid, spars.tp.dcs, ?);
	rp_mt := tr_RP_DATA_MT(?, spars.rp.smsc_addr, omit, tp_mt);
	l3_mt := tr_ML3_MT_SMS(?, c_TIF_ORIG, tr_CP_DATA_MT(rp_mt));

	SGsAP.receive(l3_mt) -> value sgsap_l3_mt;

	/* Extract relevant identifiers */
	spars.tid := bit2int(sgsap_l3_mt.tiOrSkip.transactionId.tio);
	spars.rp.msg_ref := sgsap_l3_mt.msgs.sms.cP_DATA.cP_User_Data.cP_RPDU.rP_DATA_SGSN_MS.rP_MessageReference;

	/* send CP-ACK for CP-DATA just received */
	l3_mo := ts_ML3_MO_SMS(spars.tid, c_TIF_REPL, ts_CP_ACK_MO);

	SGsAP.send(l3_mo);

	/* send RP-ACK for RP-DATA */
	rp_mo := ts_RP_ACK_MO(spars.rp.msg_ref);
	l3_mo := ts_ML3_MO_SMS(spars.tid, c_TIF_REPL, ts_CP_DATA_MO(rp_mo));

	SGsAP.send(l3_mo);

	/* expect CP-ACK for CP-DATA(RP-ACK) just sent */
	l3_mt := tr_ML3_MT_SMS(spars.tid, c_TIF_ORIG, tr_CP_ACK_MT);

	SGsAP.receive(l3_mt);

	deactivate(d);

	setverdict(pass);
}

/* submit a MO-SMS to MSC/SMSC over an already existing SGsAP connection */
function f_mo_sms_sgs(inout SmsParameters spars)
runs on BSC_ConnHdlr {
	var template (value) TPDU_RP_DATA_MS_SGSN tp_mo;
	var template (value) RPDU_MS_SGSN rp_mo;
	var template (value) PDU_ML3_MS_NW l3_mo;

	var template TPDU_RP_DATA_SGSN_MS tp_mt;
	var template RPDU_SGSN_MS rp_mt;
	var template PDU_ML3_NW_MS l3_mt;

	var default d := activate(as_other_sms_sgs());

	/* just in case this is routed to SMPP.. */
	f_create_smpp_expect(hex2str(spars.tp.da.tP_DA_NoPad.tP_DAValue));

	tp_mo := ts_SMS_SUBMIT(spars.tp.msg_ref, spars.tp.da, spars.tp.pid, spars.tp.dcs,
				 spars.tp.udl, spars.tp.ud);
	rp_mo := ts_RP_DATA_MO(spars.rp.msg_ref, omit, spars.rp.smsc_addr, tp_mo);
	l3_mo := ts_ML3_MO_SMS(spars.tid, c_TIF_ORIG, ts_CP_DATA_MO(rp_mo));

	SGsAP.send(l3_mo);

	/* receive CP-ACK for CP-DATA above */
	SGsAP.receive(tr_ML3_MT_SMS(spars.tid, c_TIF_REPL, tr_CP_ACK_MT));

	if (ispresent(spars.exp_rp_err)) {
		/* expect an RP-ERROR message from MSC with given cause */
		rp_mt := tr_RP_ERROR_MT(spars.rp.msg_ref, spars.exp_rp_err);
		l3_mt := tr_ML3_MT_SMS(spars.tid, c_TIF_REPL, tr_CP_DATA_MT(rp_mt));
		SGsAP.receive(l3_mt);
		/* send CP-ACK for CP-DATA just received */
		l3_mo := ts_ML3_MO_SMS(spars.tid, c_TIF_ORIG, ts_CP_ACK_MO);
		SGsAP.send(l3_mo);
	} else {
		/* expect RP-ACK for RP-DATA */
		rp_mt := tr_RP_ACK_MT(spars.rp.msg_ref);
		l3_mt := tr_ML3_MT_SMS(spars.tid, c_TIF_REPL, tr_CP_DATA_MT(rp_mt));
		SGsAP.receive(l3_mt);
		/* send CP-ACO for CP-DATA just received */
		l3_mo := ts_ML3_MO_SMS(spars.tid, c_TIF_ORIG, ts_CP_ACK_MO);
		SGsAP.send(l3_mo);
	}

	deactivate(d);

	setverdict(pass);
}

private function f_vty_sms_send_conn_hdlr(charstring imsi, charstring msisdn, charstring text)
runs on BSC_ConnHdlr {
	f_vty_transceive(MSCVTY, "subscriber imsi "&imsi&" sms sender msisdn "&msisdn&" send "&text);
}

/* Send a MT SMS via SGs interface */
private function f_tc_sgsap_mt_sms(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);
	f_sgs_perform_lu();
	f_sleep(1.0);
	var SmsParameters spars := valueof(t_SmsPars);
	spars.tp.ud := 'C8329BFD064D9B53'O;

	/* Trigger SMS via VTY */
	f_vty_sms_send_conn_hdlr(hex2str(pars.imsi), "2342", "Hello SMS");
	var octetstring vlr_name := f_enc_dns_hostname(mp_vlr_name);

	/* Expect a paging request and respond accordingly with a service request */
	SGsAP.receive(tr_SGsAP_PAGING_REQ(pars.imsi, vlr_name, SMS_indicator, omit));
	SGsAP.send(ts_SGsAP_SERVICE_REQ(pars.imsi, SMS_indicator, EMM_CONNECTED));

	/* Connection is now live, receive the MT-SMS */
	f_mt_sms_sgs(spars);

	/* Expect a concluding release from the MSC */
	SGsAP.receive(tr_SGsAP_RELEASE_REQ(pars.imsi, omit));

	/* Make sure that subscriber is still present and the SGs association is in tact (ref-counting) */
	f_ctrl_get_exp(IPA_CTRL, "fsm.SGs-UE.id.imsi:" & hex2str(g_pars.imsi) & ".state", "SGs-ASSOCIATED");

	f_sgsap_bssmap_screening();

	setverdict(pass);
}
testcase TC_sgsap_mt_sms() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init(1, true);
	pars := f_init_pars(11823, true);
	pars.common_id_last_eutran_plmn := f_enc_mcc_mnc('901'H, '70'H);
	vc_conn := f_start_handler_with_pars(refers(f_tc_sgsap_mt_sms), pars);
	vc_conn.done;
}

/* Send a MO SMS via SGs interface */
private function f_tc_sgsap_mo_sms(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);
	f_sgs_perform_lu();
	f_sleep(1.0);
	var SmsParameters spars := valueof(t_SmsPars);
	spars.tp.ud := 'C8329BFD064D9B53'O;

	/* Send the MO-SMS */
	f_mo_sms_sgs(spars);

	/* Expect a concluding release from the MSC/VLR */
	SGsAP.receive(tr_SGsAP_RELEASE_REQ(pars.imsi, omit));

	/* Make sure that subscriber is still present and the SGs association is in tact (ref-counting) */
	f_ctrl_get_exp(IPA_CTRL, "fsm.SGs-UE.id.imsi:" & hex2str(g_pars.imsi) & ".state", "SGs-ASSOCIATED");

	setverdict(pass);

	f_sgsap_bssmap_screening()
}
testcase TC_sgsap_mo_sms() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init(1, true);
	pars := f_init_pars(11824, true);
	pars.common_id_last_eutran_plmn := f_enc_mcc_mnc('901'H, '70'H);
	vc_conn := f_start_handler_with_pars(refers(f_tc_sgsap_mo_sms), pars);
	vc_conn.done;
}

/* Trigger sending of an MT sms via VTY but never respond to anything  */
private function f_tc_sgsap_mt_sms_and_nothing(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars, 170.0);
	f_sgs_perform_lu();
	f_sleep(1.0);

	var SmsParameters spars := valueof(t_SmsPars);
	spars.tp.ud := 'C8329BFD064D9B53'O;
	var integer page_count := 0;
	var octetstring vlr_name := f_enc_dns_hostname(mp_vlr_name);
	var template PDU_SGsAP exp_pag_req := tr_SGsAP_PAGING_REQ(g_pars.imsi, vlr_name, SMS_indicator, omit);
	var template LocationAreaId exp_lai := ts_SGsAP_IE_Lai(valueof(ts_SGsAP_LAI('901'H, '70'H, 2342)));
	exp_pag_req.sGsAP_PAGING_REQUEST.locationAreaId := exp_lai;

	/* Trigger SMS via VTY */
	f_vty_sms_send_conn_hdlr(hex2str(pars.imsi), "2342", "Hello SMS");

	/* Expect the MSC/VLR to page exactly once */
	SGsAP.receive(exp_pag_req);

	/* Wait some time to make sure the MSC is not delivering any further
	 * paging messages or anything else that could be unexpected. */
	timer T := 20.0;
	T.start
	alt {
		[] SGsAP.receive(exp_pag_req)
		{
			setverdict(fail, "paging seems not to stop!");
			mtc.stop;
		}
		[] SGsAP.receive {
			setverdict(fail, "unexpected SGsAP message received");
			self.stop;
		}
		[] T.timeout {
			setverdict(pass);
		}
	}

	/* Even on a failed paging the SGs Association should stay intact */
	f_ctrl_get_exp(IPA_CTRL, "fsm.SGs-UE.id.imsi:" & hex2str(g_pars.imsi) & ".state", "SGs-ASSOCIATED");

	/* Make sure that the SMS we just inserted is cleared and the
	 * subscriber is expired. This is necessary because otherwise the MSC
	 * might re-try the SMS delivery and disturb the following tests. */

	f_vty_sms_clear(hex2str(g_pars.imsi));

	f_vty_transceive(MSCVTY, "subscriber imsi " & hex2str(g_pars.imsi) & " expire");

	setverdict(pass);

	f_sgsap_bssmap_screening();
}
testcase TC_sgsap_mt_sms_and_nothing() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init(1, true);
	pars := f_init_pars(11825, true);
	pars.common_id_last_eutran_plmn := f_enc_mcc_mnc('901'H, '70'H);
	vc_conn := f_start_handler_with_pars(refers(f_tc_sgsap_mt_sms_and_nothing), pars);
	vc_conn.done;
}

/* Trigger sending of an MT sms via VTY but reject the paging immediately */
private function f_tc_sgsap_mt_sms_and_reject(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars, 150.0);
	f_sgs_perform_lu();
	f_sleep(1.0);

	var SmsParameters spars := valueof(t_SmsPars);
	spars.tp.ud := 'C8329BFD064D9B53'O;
	var integer page_count := 0;
	var octetstring vlr_name := f_enc_dns_hostname(mp_vlr_name);
	var template PDU_SGsAP exp_pag_req := tr_SGsAP_PAGING_REQ(g_pars.imsi, vlr_name, SMS_indicator, omit);
	var template LocationAreaId exp_lai := ts_SGsAP_IE_Lai(valueof(ts_SGsAP_LAI('901'H, '70'H, 2342)));
	exp_pag_req.sGsAP_PAGING_REQUEST.locationAreaId := exp_lai;

	/* Trigger SMS via VTY */
	f_vty_sms_send_conn_hdlr(hex2str(pars.imsi), "2342", "Hello SMS");

	/* Expect a paging request and reject it immediately */
	SGsAP.receive(exp_pag_req);
	SGsAP.send(ts_SGsAP_PAGING_REJ(g_pars.imsi, IMSI_unknown));

	/* The MSC/VLR should no longer try to page once the paging has been
	 * rejected. Wait some time and check if there are no unexpected
	 * messages on the SGs interface. */
	timer T := 20.0;
	T.start
	alt {
		[] SGsAP.receive(exp_pag_req)
		{
			setverdict(fail, "paging seems not to stop!");
			mtc.stop;
		}
		[] SGsAP.receive {
			setverdict(fail, "unexpected SGsAP message received");
			self.stop;
		}
		[] T.timeout {
			setverdict(pass);
		}
	}

	f_vty_sms_clear(hex2str(g_pars.imsi));

	/* A rejected paging with IMSI_unknown (see above) should always send
	 * the SGs association to NULL. */
	f_ctrl_get_exp(IPA_CTRL, "fsm.SGs-UE.id.imsi:" & hex2str(g_pars.imsi) & ".state", "SGs-NULL");

	f_sgsap_bssmap_screening();

	setverdict(pass);
}
testcase TC_sgsap_mt_sms_and_reject() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init(1, true);
	pars := f_init_pars(11826, true);
	pars.common_id_last_eutran_plmn := f_enc_mcc_mnc('901'H, '70'H);
	vc_conn := f_start_handler_with_pars(refers(f_tc_sgsap_mt_sms_and_reject), pars);
	vc_conn.done;
}

/* Perform an MT CSFB call including LU */
private function f_mt_lu_and_csfb_call(charstring id, BSC_ConnHdlrPars pars, boolean bssmap_lu) runs on BSC_ConnHdlr {
	f_init_handler(pars);

	/* Be sure that the BSSMAP reset is done before we begin. */
	f_sleep(2.0);

	/* Testcase variation: See what happens when we do a regular BSSMAP
	 * LU first (this should not hurt in any way!) */
	if (bssmap_lu) {
		f_perform_lu();
	}
	pars.common_id_last_eutran_plmn := f_enc_mcc_mnc('901'H, '70'H);

	f_sgs_perform_lu();
	f_sleep(1.0);

	var octetstring vlr_name := f_enc_dns_hostname(mp_vlr_name);
	var CallParameters cpars := valueof(t_CallParams('12345'H, 0));

	/* Initiate a call via MNCC interface */
	f_mt_call_initiate(cpars);

	/* Expect a paging request and respond accordingly with a service request */
	SGsAP.receive(tr_SGsAP_PAGING_REQ(pars.imsi, vlr_name, CS_call_indicator, omit));
	SGsAP.send(ts_SGsAP_SERVICE_REQ(pars.imsi, CS_call_indicator, EMM_CONNECTED));

	/* Complete the call, hold it for some time and then tear it down */
	f_mt_call_complete(cpars);
	f_sleep(3.0);
	f_call_hangup(cpars, true, is_csfb := true);

	/* Make sure that subscriber is still present and the SGs association is in tact (ref-counting) */
	f_ctrl_get_exp(IPA_CTRL, "fsm.SGs-UE.id.imsi:" & hex2str(g_pars.imsi) & ".state", "SGs-ASSOCIATED");

	/* Test for successful return by triggering a paging, when the paging
	 * request is received via SGs, we can be sure that the MSC/VLR has
	 * recognized that the UE is now back on 4G */
	f_sleep(1.0);
	f_vty_transceive(MSCVTY, "subscriber imsi " & hex2str(g_pars.imsi) & " paging");
	alt {
	[] SGsAP.receive(tr_SGsAP_PAGING_REQ(pars.imsi, vlr_name, CS_call_indicator, omit)) {
		setverdict(pass);
		}
	[] SGsAP.receive {
		setverdict(fail, "Received unexpected message on SGs");
		}
	}

	f_sgsap_bssmap_screening();

	setverdict(pass);
}

/* Perform a regular BSSAP LU first, do a SGSAP LU and then make a CSFB call */
private function f_tc_bssap_lu_sgsap_lu_and_mt_call(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_mt_lu_and_csfb_call(id, pars, true);
}
testcase TC_bssap_lu_sgsap_lu_and_mt_call() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init(1, true);
	pars := f_init_pars(118139, true);

	vc_conn := f_start_handler_with_pars(refers(f_tc_bssap_lu_sgsap_lu_and_mt_call), pars);
	vc_conn.done;
}

/* Perform a SGSAP LU and then make a CSFB call */
private function f_tc_sgsap_lu_and_mt_call(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_mt_lu_and_csfb_call(id, pars, false);
}
testcase TC_sgsap_lu_and_mt_call() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init(1, true);
	pars := f_init_pars(11827, true);

	vc_conn := f_start_handler_with_pars(refers(f_tc_sgsap_lu_and_mt_call), pars);
	vc_conn.done;
}

/* Simulate an HLR/VLR failure */
private function f_tc_sgsap_vlr_failure(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	var octetstring mme_name := f_enc_dns_hostname(mp_mme_name);
	var octetstring vlr_name := f_enc_dns_hostname(mp_vlr_name);

	var PDU_SGsAP lur;

	f_init_handler(pars);

	/* Attempt location update (which is expected to fail) */
	lur := valueof(ts_SGsAP_LU_REQ(g_pars.imsi, mme_name, IMSI_attach,
					ts_SGsAP_LAI('901'H, '70'H, 2342)));
	SGsAP.send(lur);

	/* Respond to SGsAP-RESET-INDICATION from VLR */
	alt {
	[] SGsAP.receive(tr_SGsAP_RESET_IND_VLR(vlr_name)); {
		SGsAP.send(valueof(ts_SGsAP_RESET_ACK_MME(mme_name)));
		setverdict(pass);
		}
	[] SGsAP.receive {
		setverdict(fail, "Received unexpected message on SGs");
		}
	}

	f_sleep(1.0);
	setverdict(pass);
}
testcase TC_sgsap_vlr_failure() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init(1, true, false);
	pars := f_init_pars(11811, true, false);
	vc_conn := f_start_handler_with_pars(refers(f_tc_sgsap_vlr_failure), pars);
	vc_conn.done;
}

/* SGs TODO:
   * LU attempt for IMSI without NAM_PS in HLR
   * LU attempt with AUTH FAIL due to invalid RES/SRES
   * LU attempt with no response from HLR (VLR should timeout + LU REJ)
   * LU attempt with new TMSI but without TMSI REALL CMPL baco to VLR
   * implicit IMSI detach from EPS
   * implicit IMSI detach from non-EPS
   * MM INFO
   *
 */

private function f_tc_ho_inter_bsc_unknown_cell(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);
	var CallParameters cpars := valueof(t_CallParams('12345'H, 0));

	f_perform_lu();
	f_mo_call_establish(cpars);

	f_sleep(1.0);

	var myBSSMAP_Cause cause_val := GSM0808_CAUSE_BETTER_CELL;
	var BssmapCause cause := enum2int(cause_val);

	var template BSSMAP_FIELD_CellIdentificationList cil;
	cil := { cIl_LAI := { ts_BSSMAP_CI_LAI('023'H, '42'H, 999) } };

	RAN_CONN.send(ts_BSSMAP_HandoverRequired(cause, cil));
	RAN_CONN.receive(tr_BSSMAP_HandoverRequiredReject);

	f_call_hangup(cpars, true);
}
testcase TC_ho_inter_bsc_unknown_cell() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_ho_inter_bsc_unknown_cell), 53);
	vc_conn.done;
}

private altstep as_mgcp_ack_all_mdcx(CallParameters cpars) runs on BSC_ConnHdlr {
	var MgcpCommand mgcp_cmd;
	[] MGCP.receive(tr_MDCX) -> value mgcp_cmd {
		var charstring conn_id;
		f_mgcp_find_param_entry(mgcp_cmd.params, "I", conn_id);
		var SDP_Message sdp := valueof(ts_SDP(cpars.mgw_conn_2.mgw_rtp_ip, cpars.mgw_conn_2.mgw_rtp_ip,
							hex2str(cpars.mgcp_call_id), "42",
							cpars.mgw_conn_2.mgw_rtp_port,
							{ int2str(cpars.rtp_payload_type) },
							{ valueof(ts_SDP_rtpmap(cpars.rtp_payload_type,
										cpars.rtp_sdp_format)),
							  valueof(ts_SDP_ptime(20)) }));
		MGCP.send(ts_MDCX_ACK(mgcp_cmd.line.trans_id, str2hex(conn_id), sdp));
		repeat;
	}
}

private altstep as_mgcp_ack_all_dlcx(CallParameters cpars) runs on BSC_ConnHdlr {
	var MgcpCommand mgcp_cmd;
	[] MGCP.receive(tr_DLCX(?)) -> value mgcp_cmd {
		MGCP.send(ts_DLCX_ACK2(mgcp_cmd.line.trans_id));
		repeat;
	}
}

private function f_tc_ho_inter_bsc0(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	var CallParameters cpars;

	cpars := valueof(t_CallParams('12345'H, 0));
	if (pars.use_ipv6) {
		cpars.mgw_conn_1.mgw_rtp_ip := "::1";
		cpars.mgw_conn_2.mgw_rtp_ip := "::2";
		cpars.bss_rtp_ip := "::3";
	}
	if (pars.use_csd) {
		f_set_cpars_csd(cpars, "BS25T", '1'B, GSM48_BCAP_TR_TRANSP, GSM48_BCAP_UR_4800);
	}

	f_init_handler(pars);

	f_vty_transceive(MSCVTY, "configure terminal");
	f_vty_transceive(MSCVTY, "msc");
	f_vty_transceive(MSCVTY, "neighbor a cgi 262 42 23 42 ran-pc 0.24.1");
	f_vty_transceive(MSCVTY, "neighbor a cgi 023 42 5 6 ran-pc 0.24.2");
	f_vty_transceive(MSCVTY, "exit");
	f_vty_transceive(MSCVTY, "exit");

	f_perform_lu();
	f_mo_call_establish(cpars);

	/* Remember the last n_sd (sequence number),
	 * we will need it when the other BSS hands over back to us. */
	var N_Sd_Array last_n_sd := f_bssmap_last_n_sd();

	f_sleep(1.0);

	var default ack_mdcx := activate(as_mgcp_ack_all_mdcx(cpars));

	var myBSSMAP_Cause cause_val := GSM0808_CAUSE_BETTER_CELL;
	var BssmapCause cause := enum2int(cause_val);

	var template BSSMAP_FIELD_CellIdentificationList cil;
	cil := { cIl_CGI := { ts_BSSMAP_CI_CGI('023'H, '42'H, 5, 6) } };

	/* old BSS sends Handover Required */
	RAN_CONN.send(ts_BSSMAP_HandoverRequired(cause, cil));

	/* Now the action goes on in f_tc_ho_inter_bsc1() */

	/* MSC forwards the RR Handover Command to old BSS */
	var PDU_BSSAP ho_command;
	RAN_CONN.receive(tr_BSSMAP_HandoverCommand) -> value ho_command;

	log("GOT HandoverCommand", ho_command);

	RAN_CONN.receive(tr_BSSMAP_HandoverSucceeded);

	/* f_tc_ho_inter_bsc1() completes Handover, then expecting a Clear here. */
	f_expect_clear();

	log("FIRST inter-BSC Handover done");


	/* ------------------------ */

	/* Ok, that went well, now the other BSC is handovering back here --
	 * from now on this here is the new BSS. */
	f_create_bssmap_exp_n_connect(193);

	var template BSSMAP_IE_EncryptionInformation encryptionInformation;
	var template BSSMAP_IE_ChosenEncryptionAlgorithm chosenEncryptionAlgorithm;
	var template BSSMAP_IE_KC128 kC128;
	var OCT1 a5_perm_alg;
	f_get_expected_encryption(encryptionInformation, chosenEncryptionAlgorithm, kC128, a5_perm_alg);
	var template PDU_BSSAP expect_ho_request := tr_BSSMAP_HandoverRequest(encryptionInformation,
									      chosenEncryptionAlgorithm,
									      kC128, codecList := ?);
	var PDU_BSSAP ho_request;
	alt {
	[] RAN_CONN.receive(expect_ho_request);
	[] RAN_CONN.receive(tr_BSSMAP_HandoverRequest) -> value ho_request {
		log("Error: Wrong handoverRequest received. Expected: ", expect_ho_request,
		    " got ", ho_request);
		setverdict(fail, "Wrong handoverRequest received");
		mtc.stop;
		}
	}

	/* new BSS composes a RR Handover Command */
	var PDU_ML3_NW_MS rr_ho_cmd := valueof(ts_RR_HandoverCommand);
	var octetstring rr_ho_cmd_enc := enc_PDU_ML3_NW_MS(rr_ho_cmd);
	var BSSMAP_IE_AoIP_TransportLayerAddress tla tla :=
		valueof(f_ts_BSSMAP_IE_AoIP_TLA(cpars.bss_rtp_ip, cpars.bss_rtp_port));
	RAN_CONN.send(ts_BSSMAP_HandoverRequestAcknowledge(rr_ho_cmd_enc, lengthof(rr_ho_cmd_enc),
							   tla, ts_BSSMAP_IE_SpeechCodec({ts_CodecFR})));

	/* Now f_tc_ho_inter_bsc1() expects HandoverCommand */

	f_sleep(0.5);

	/* Notify that the MS is now over here */

	RAN_CONN.send(ts_BSSMAP_HandoverDetect);
	f_sleep(0.1);
	RAN_CONN.send(ts_BSSMAP_HandoverComplete);

	f_sleep(3.0);

	deactivate(ack_mdcx);

	/* Use the n_sd (sequence number) we stored before the first handover.
	 * Otherwise the MSC may treat our DTAP messages as duplicates and discard them. */
	f_bssmap_continue_after_n_sd(last_n_sd);

	var default ccrel := activate(as_optional_cc_rel(cpars, true));
	f_call_hangup(cpars, true);
	f_sleep(1.0);
	deactivate(ccrel);

	setverdict(pass);
}
private function f_tc_ho_inter_bsc1(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	var charstring bss_rtp_ip;
	if (pars.use_ipv6) {
		bss_rtp_ip := "::8";
	} else {
		bss_rtp_ip := "1.2.3.4";
	}
	f_init_handler(pars);
	f_create_bssmap_exp_n_connect(194);

	var template BSSMAP_IE_EncryptionInformation encryptionInformation;
	var template BSSMAP_IE_ChosenEncryptionAlgorithm chosenEncryptionAlgorithm;
	var template BSSMAP_IE_KC128 kC128;
	var OCT1 a5_perm_alg;
	f_get_expected_encryption(encryptionInformation, chosenEncryptionAlgorithm, kC128, a5_perm_alg);
	var template PDU_BSSAP expect_ho_request := tr_BSSMAP_HandoverRequest(encryptionInformation,
									      chosenEncryptionAlgorithm,
									      kC128, codecList := ?);
	var PDU_BSSAP ho_request;
	alt {
	[] RAN_CONN.receive(expect_ho_request);
	[] RAN_CONN.receive(tr_BSSMAP_HandoverRequest) -> value ho_request {
		log("Error: Wrong handoverRequest received. Expected: ", expect_ho_request,
		    " got ", ho_request);
		setverdict(fail, "Wrong handoverRequest received");
		mtc.stop;
		}
	}
	/* new BSS composes a RR Handover Command */
	var PDU_ML3_NW_MS rr_ho_cmd := valueof(ts_RR_HandoverCommand);
	var octetstring rr_ho_cmd_enc := enc_PDU_ML3_NW_MS(rr_ho_cmd);
	var BSSMAP_IE_AoIP_TransportLayerAddress tla :=
		valueof(f_ts_BSSMAP_IE_AoIP_TLA(bss_rtp_ip, 2342));
	RAN_CONN.send(ts_BSSMAP_HandoverRequestAcknowledge(rr_ho_cmd_enc, lengthof(rr_ho_cmd_enc),
							   tla, ts_BSSMAP_IE_SpeechCodec({ts_CodecFR})));

	/* Now f_tc_ho_inter_bsc0() expects HandoverCommand */

	f_sleep(0.5);

	/* Notify that the MS is now over here */

	RAN_CONN.send(ts_BSSMAP_HandoverDetect);
	f_sleep(0.1);
	RAN_CONN.send(ts_BSSMAP_HandoverComplete);

	f_sleep(3.0);

	/* Now I'd like to f_call_hangup() but we don't know any cpars here. So
	 * ... handover back to the first BSC :P */

	var myBSSMAP_Cause cause_val := GSM0808_CAUSE_BETTER_CELL;
	var BssmapCause cause := enum2int(cause_val);

	var template BSSMAP_FIELD_CellIdentificationList cil;
	cil := { cIl_CGI := { ts_BSSMAP_CI_CGI('262'H, '42'H, 23, 42) } };

	/* old BSS sends Handover Required */
	RAN_CONN.send(ts_BSSMAP_HandoverRequired(cause, cil));

	/* Now the action goes on in f_tc_ho_inter_bsc0() */

	/* MSC forwards the RR Handover Command to old BSS */
	var PDU_BSSAP ho_command;
	RAN_CONN.receive(tr_BSSMAP_HandoverCommand) -> value ho_command;

	log("GOT HandoverCommand", ho_command);

	RAN_CONN.receive(tr_BSSMAP_HandoverSucceeded);

	/* f_tc_ho_inter_bsc1() completes Handover, then expecting a Clear here. */
	f_expect_clear();
	setverdict(pass);
}
function f_tc_ho_inter_bsc_main(boolean use_ipv6 := false, integer a5_n := 0, boolean use_csd := false) runs on MTC_CT {
	var BSC_ConnHdlr vc_conn0;
	var BSC_ConnHdlr vc_conn1;
	f_init(2);

	var BSC_ConnHdlrPars pars0 := f_init_pars(53);
	pars0.use_ipv6 := use_ipv6;
	pars0.use_csd := use_csd;
	pars0.net.expect_ciph := a5_n > 0;
	pars0.net.expect_auth := pars0.net.expect_ciph;
	pars0.net.kc_support := bit2oct('00000001'B << a5_n);
	pars0.cm2.classmarkInformationType2_oct5.a5_3 := '1'B;
	pars0.cm2.classmarkInformationType2_oct5.a5_2 := '0'B;
	pars0.cm2.classmarkInformationType2_oct5.cm3 := '1'B;
	pars0.cm3 := valueof(ts_CM3_default);
	pars0.use_umts_aka := true;
	pars0.vec := f_gen_auth_vec_3g();
	pars0.vec_keep := true;
	pars0.ran_idx := 0;

	var BSC_ConnHdlrPars pars1 := f_init_pars(53);
	pars1.use_ipv6 := use_ipv6;
	pars1.use_csd := use_csd;
	pars1.net.expect_ciph := pars0.net.expect_ciph;
	pars1.net.expect_auth := pars0.net.expect_ciph;
	pars1.net.kc_support := bit2oct('00000001'B << a5_n);
	pars1.cm2 := pars0.cm2;
	pars1.cm3 := pars0.cm3;
	pars1.use_umts_aka := true;
	/* Both components need the same auth vector info because we expect f_tc_ho_inter_bsc0's ciphering key to be
	 * identical to the one that shows up in f_tc_ho_inter_bsc1. Can only do that by feeding in a vector to both
	 * components and then not overwriting it in BSC_ConnectionHandler. */
	pars1.vec := pars0.vec;
	pars1.vec_keep := true;
	pars1.ran_idx := 1;

	if (a5_n > 0) {
		f_vty_config(MSCVTY, "network", "authentication required");
	}
	f_vty_config(MSCVTY, "network", "encryption a5 " & int2str(a5_n));

	vc_conn0 := f_start_handler_with_pars(refers(f_tc_ho_inter_bsc0), pars0);
	vc_conn1 := f_start_handler_with_pars(refers(f_tc_ho_inter_bsc1), pars1);
	vc_conn0.done;
	vc_conn1.done;
}
testcase TC_ho_inter_bsc() runs on MTC_CT {
	f_tc_ho_inter_bsc_main(false, a5_n := 0);
}
testcase TC_ho_inter_bsc_a5_1() runs on MTC_CT {
	f_tc_ho_inter_bsc_main(false, a5_n := 1);
}
testcase TC_ho_inter_bsc_a5_3() runs on MTC_CT {
	f_tc_ho_inter_bsc_main(false, a5_n := 3);
}
testcase TC_ho_inter_bsc_a5_4() runs on MTC_CT {
	f_tc_ho_inter_bsc_main(false, a5_n := 4);
}
testcase TC_ho_inter_bsc_ipv6() runs on MTC_CT {
	f_tc_ho_inter_bsc_main(true);
}
testcase TC_ho_inter_bsc_csd() runs on MTC_CT {
	f_tc_ho_inter_bsc_main(use_csd := true);
}

function f_ML3_patch_seq_nr_MS_NW(in uint2_t seq_nr, inout octetstring enc_l3) {
	log("MS_NW patching N(SD)=", seq_nr, " into dtap ", enc_l3);
	enc_l3[2] := (enc_l3[2] and4b '3f'O) or4b bit2oct(int2bit(seq_nr, 8) << 6);
	log("MS_NW patched enc_l3: ", enc_l3);
}

private function f_tc_ho_inter_msc_out(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	var CallParameters cpars;
	var PDU_BSSAP ho_request;

	cpars := valueof(t_CallParams('12345'H, 0));
	if (pars.use_ipv6) {
		cpars.mgw_conn_1.mgw_rtp_ip := "::1";
		cpars.mgw_conn_2.mgw_rtp_ip := "::2";
		cpars.bss_rtp_ip := "::3";
	}
	if (pars.use_csd) {
		f_set_cpars_csd(cpars, "BS25T", '1'B, GSM48_BCAP_TR_TRANSP, GSM48_BCAP_UR_4800);
	}
	var hexstring ho_number := f_gen_msisdn(99999);

	f_init_handler(pars);

	f_create_mncc_expect(hex2str(ho_number));

	f_vty_transceive(MSCVTY, "configure terminal");
	f_vty_transceive(MSCVTY, "msc");
	f_vty_transceive(MSCVTY, "neighbor a cgi 017 017 1 1 msc-ipa-name msc-017-017-1");
	f_vty_transceive(MSCVTY, "exit");
	f_vty_transceive(MSCVTY, "exit");

	f_perform_lu();
	f_mo_call_establish(cpars);

	f_sleep(1.0);

	var default ack_mdcx := activate(as_mgcp_ack_all_mdcx(cpars));

	var myBSSMAP_Cause cause_val := GSM0808_CAUSE_BETTER_CELL;
	var BssmapCause cause := enum2int(cause_val);

	var template BSSMAP_FIELD_CellIdentificationList cil;
	cil := { cIl_CGI := { ts_BSSMAP_CI_CGI('017'H, '017'H, 1, 1) } };

	/* old BSS sends Handover Required */
	RAN_CONN.send(ts_BSSMAP_HandoverRequired(cause, cil));

	/* The target cell 017-017 LAC 1 is configured to be a remote MSC of name "msc-017-017-1".
	 * This MSC tries to reach the other MSC via GSUP. */

	var template BSSMAP_IE_EncryptionInformation encryptionInformation;
	var template BSSMAP_IE_ChosenEncryptionAlgorithm chosenEncryptionAlgorithm;
	var template BSSMAP_IE_KC128 kC128;
	var OCT1 a5_perm_alg;
	f_get_expected_encryption(encryptionInformation, chosenEncryptionAlgorithm, kC128, a5_perm_alg);
	var template PDU_BSSAP expect_ho_request := tr_BSSMAP_HandoverRequest(encryptionInformation,
									      chosenEncryptionAlgorithm,
									      kC128, codecList := ?);

	var octetstring remote_msc_name := '6D73632D3031372D3031372D3100'O; /* "msc-017-017-1\0" as octetstring */
	var GSUP_PDU prep_ho_req;
	alt {
	[] GSUP.receive(tr_GSUP_E_AN_APDU(OSMO_GSUP_MSGT_E_PREPARE_HANDOVER_REQUEST,
				pars.imsi, destination_name := remote_msc_name,
				an_apdu := t_GSUP_AN_APDU(OSMO_GSUP_AN_PROTO_48006, pdu := ?))) -> value prep_ho_req;
	[] GSUP.receive(tr_GSUP_E_AN_APDU(OSMO_GSUP_MSGT_E_PREPARE_HANDOVER_REQUEST)) {
		setverdict(fail, "Wrong OSMO_GSUP_MSGT_E_PREPARE_HANDOVER_REQUEST message received");
		mtc.stop;
		}
	}

	var GSUP_IeValue source_name_ie;
	f_gsup_find_ie(prep_ho_req, OSMO_GSUP_SOURCE_NAME_IE, source_name_ie);
	var octetstring local_msc_name := source_name_ie.source_name;

	/* Decode PDU to 1) match with expect_ho_request and 2) to forward the actual chosen encryption algorithm. */
	var GSUP_IeValue an_apdu_ie;
	f_gsup_find_ie(prep_ho_req, OSMO_GSUP_AN_APDU_IE, an_apdu_ie);
	ho_request := dec_PDU_BSSAP(an_apdu_ie.an_apdu.pdu);
	if (not match(ho_request, expect_ho_request)) {
		setverdict(fail, "Wrong PDU in OSMO_GSUP_MSGT_E_PREPARE_HANDOVER_REQUEST message received");
		mtc.stop;
	}

	/* Remote MSC has figured out its BSC and signals success */
	var PDU_ML3_NW_MS rr_ho_cmd := valueof(ts_RR_HandoverCommand);
	var octetstring rr_ho_cmd_enc := enc_PDU_ML3_NW_MS(rr_ho_cmd);
	var PDU_BSSAP ho_req_ack := valueof(ts_BSSMAP_HandoverRequestAcknowledge(rr_ho_cmd_enc, lengthof(rr_ho_cmd_enc),
			aoIPTransportLayer := omit,
			speechCodec := ts_BSSMAP_IE_SpeechCodec({ts_CodecFR}),
			chosenEncryptionAlgorithm := ho_request.pdu.bssmap.handoverRequest.chosenEncryptionAlgorithm));
	GSUP.send(ts_GSUP_E_PrepareHandoverResult(
				pars.imsi,
				ho_number,
				remote_msc_name, local_msc_name,
				valueof(t_GSUP_AN_APDU(OSMO_GSUP_AN_PROTO_48006, enc_PDU_BSSAP(ho_req_ack)))));

	/* MSC forwards the RR Handover Command to old BSS */
	RAN_CONN.receive(tr_BSSMAP_HandoverCommand);

	/* The MS shows up at remote new BSS */

	GSUP.send(ts_GSUP_E_AN_APDU(OSMO_GSUP_MSGT_E_PROCESS_ACCESS_SIGNALLING_REQUEST,
				pars.imsi, remote_msc_name, local_msc_name,
				valueof(t_GSUP_AN_APDU(OSMO_GSUP_AN_PROTO_48006,
						enc_PDU_BSSAP(valueof(ts_BSSMAP_HandoverDetect))))));
	RAN_CONN.receive(tr_BSSMAP_HandoverSucceeded);
	f_sleep(0.1);

	/* Save the MS sequence counters for use on the other connection */
	var N_Sd_Array last_n_sd := f_bssmap_last_n_sd();

	GSUP.send(ts_GSUP_E_AN_APDU(OSMO_GSUP_MSGT_E_SEND_END_SIGNAL_REQUEST,
				pars.imsi, remote_msc_name, local_msc_name,
				valueof(t_GSUP_AN_APDU(OSMO_GSUP_AN_PROTO_48006,
						enc_PDU_BSSAP(valueof(ts_BSSMAP_HandoverComplete))))));

	/* The local BSS conn clears, all communication goes via remote MSC now */
	f_expect_clear();

	/**********************************/
	/* Play through some signalling across the inter-MSC link.
	 * This is a copy of f_tc_lu_and_mo_ussd_single_request() translated into GSUP AN-APDUs. */

	if (false) {
	var template OCTN facility_req := f_USSD_FACILITY_IE_INVOKE(
		invoke_id := 5, /* Phone may not start from 0 or 1 */
		op_code := SS_OP_CODE_PROCESS_USS_REQ,
		ussd_string := "*#100#"
	);

	var template OCTN facility_rsp := f_USSD_FACILITY_IE_RETURN_RESULT(
		invoke_id := 5, /* InvokeID shall be the same for both REQ and RSP */
		op_code := SS_OP_CODE_PROCESS_USS_REQ,
		ussd_string := "Your extension is " & hex2str(g_pars.msisdn) & "\r"
	)

	/* Compose a new SS/REGISTER message with request */
	var template (value) PDU_ML3_MS_NW ussd_req := ts_ML3_MO_SS_REGISTER(
		tid := 1, /* We just need a single transaction */
		ti_flag := c_TIF_ORIG, /* Sent from the side that originates the TI */
		facility := valueof(facility_req)
	);
	var PDU_ML3_MS_NW ussd_req_v := valueof(ussd_req);

	/* Compose SS/RELEASE_COMPLETE template with expected response */
	var template PDU_ML3_NW_MS ussd_rsp := tr_ML3_MT_SS_RELEASE_COMPLETE(
		tid := 1, /* Response should arrive within the same transaction */
		ti_flag := c_TIF_REPL, /* Sent to the side that originates the TI */
		facility := valueof(facility_rsp)
	);

	/* Compose expected MSC -> HLR message */
	var template GSUP_PDU gsup_req := tr_GSUP_PROC_SS_REQ(
		imsi := g_pars.imsi,
		state := OSMO_GSUP_SESSION_STATE_BEGIN,
		ss := valueof(facility_req)
	);

	/* To be used for sending response with correct session ID */
	var GSUP_PDU gsup_req_complete;

	/* Request own number */
	/* From remote MSC instead of BSSAP directly */
	/* Patch the correct N_SD value into the message. */
	var octetstring l3_enc := enc_PDU_ML3_MS_NW(ussd_req_v);
	var RAN_Emulation.ConnectionData cd;
	f_ML3_patch_seq_nr_MS_NW(f_next_n_sd(last_n_sd, f_ML3_n_sd_idx(ussd_req_v)), l3_enc);
	GSUP.send(ts_GSUP_E_AN_APDU(OSMO_GSUP_MSGT_E_PROCESS_ACCESS_SIGNALLING_REQUEST,
				pars.imsi, remote_msc_name, local_msc_name,
				valueof(t_GSUP_AN_APDU(OSMO_GSUP_AN_PROTO_48006,
						enc_PDU_BSSAP(valueof(ts_BSSAP_DTAP(l3_enc)))
						))
				));

	/* Expect GSUP message containing the SS payload */
	gsup_req_complete := f_expect_gsup_msg(gsup_req);

	/* Compose the response from HLR using received session ID */
	var template GSUP_PDU gsup_rsp := ts_GSUP_PROC_SS_REQ(
		imsi := g_pars.imsi,
		sid := gsup_req_complete.ies[1].val.session_id,
		state := OSMO_GSUP_SESSION_STATE_END,
		ss := valueof(facility_rsp)
	);

	/* Finally, HLR terminates the session */
	GSUP.send(gsup_rsp);

	/* The USSD response goes out to remote MSC, on GSUP E instead of BSSAP */
	var GSUP_PDU gsup_ussd_rsp;
	GSUP.receive(tr_GSUP_E_AN_APDU(OSMO_GSUP_MSGT_E_FORWARD_ACCESS_SIGNALLING_REQUEST,
				pars.imsi, destination_name := remote_msc_name)) -> value gsup_ussd_rsp;

	var GSUP_IeValue an_apdu;
	if (not f_gsup_find_ie(gsup_ussd_rsp, OSMO_GSUP_AN_APDU_IE, an_apdu)) {
		setverdict(fail, "No AN-APDU in received GSUP message. Expected USSD response in DTAP, got", gsup_ussd_rsp);
		mtc.stop;
	}
	var PDU_BSSAP bssap_dtap_mt := dec_PDU_BSSAP(an_apdu.an_apdu.pdu);
	var PDU_ML3_NW_MS dtap_mt := dec_PDU_ML3_NW_MS(bssap_dtap_mt.pdu.dtap);
	log("Expecting", ussd_rsp);
	log("Got", dtap_mt);
        if (not match(dtap_mt, ussd_rsp)) {
		setverdict(fail, "Unexpected GSUP message. Expected USSD response in DTAP, got", gsup_ussd_rsp);
		mtc.stop;
	}
	}
	/**********************************/


	/* inter-MSC handover back to the first MSC */
	f_create_bssmap_exp_n_connect(193);
	cil := { cIl_CGI := { ts_BSSMAP_CI_CGI('262'H, '42'H, 23, 42) } };

	/* old BSS sends Handover Required, via inter-MSC E link: like
	 * RAN_CONN.send(ts_BSSMAP_HandoverRequired(cause, cil));
	 * but via GSUP */
	GSUP.send(ts_GSUP_E_AN_APDU(OSMO_GSUP_MSGT_E_PREPARE_SUBSEQUENT_HANDOVER_REQUEST,
				pars.imsi, remote_msc_name, local_msc_name,
				valueof(t_GSUP_AN_APDU(OSMO_GSUP_AN_PROTO_48006,
						enc_PDU_BSSAP(valueof(ts_BSSMAP_HandoverRequired(cause, cil)))
						))
				));

	/* MSC asks local BSS to prepare Handover to it */
	f_get_expected_encryption(encryptionInformation, chosenEncryptionAlgorithm, kC128, a5_perm_alg);
	expect_ho_request := tr_BSSMAP_HandoverRequest(encryptionInformation,
						       chosenEncryptionAlgorithm,
						       kC128, codecList := ?);
	alt {
	[] RAN_CONN.receive(expect_ho_request) -> value ho_request;
	[] RAN_CONN.receive(tr_BSSMAP_HandoverRequest) -> value ho_request {
		log("Error: Wrong handoverRequest received. Expected: ", expect_ho_request,
		    " got ", ho_request);
		setverdict(fail, "Wrong handoverRequest received");
		mtc.stop;
		}
	}

	/* Make sure the new BSSAP conn continues with the correct N_SD sequence numbers */
	f_bssmap_continue_after_n_sd(last_n_sd);

	/* new BSS composes a RR Handover Command */
	rr_ho_cmd := valueof(ts_RR_HandoverCommand);
	rr_ho_cmd_enc := enc_PDU_ML3_NW_MS(rr_ho_cmd);
	var BSSMAP_IE_AoIP_TransportLayerAddress tla :=
		valueof(f_ts_BSSMAP_IE_AoIP_TLA(cpars.bss_rtp_ip, cpars.bss_rtp_port));
	RAN_CONN.send(ts_BSSMAP_HandoverRequestAcknowledge(rr_ho_cmd_enc, lengthof(rr_ho_cmd_enc),
			tla, ts_BSSMAP_IE_SpeechCodec({ts_CodecFR}),
			chosenEncryptionAlgorithm := ho_request.pdu.bssmap.handoverRequest.chosenEncryptionAlgorithm));

	/* HandoverCommand goes out via remote MSC-I */
	var GSUP_PDU prep_subsq_ho_res;
	GSUP.receive(tr_GSUP_E_AN_APDU(OSMO_GSUP_MSGT_E_PREPARE_SUBSEQUENT_HANDOVER_RESULT,
				pars.imsi, destination_name := remote_msc_name)) -> value prep_subsq_ho_res;

	/* MS shows up at the local BSS */
	RAN_CONN.send(ts_BSSMAP_HandoverDetect);
	f_sleep(0.1);
	RAN_CONN.send(ts_BSSMAP_HandoverComplete);

	/* Handover Succeeded message */
	GSUP.receive(tr_GSUP_E_AN_APDU(OSMO_GSUP_MSGT_E_FORWARD_ACCESS_SIGNALLING_REQUEST,
				pars.imsi, destination_name := remote_msc_name));

	/* MS has handovered to here, Clear Command goes out via remote MSC-I -- in form of a GSUP Close. */
	GSUP.receive(tr_GSUP_E_NO_PDU(OSMO_GSUP_MSGT_E_CLOSE,
				pars.imsi, destination_name := remote_msc_name));

	/* Handover ends successfully. Call goes on for a little longer and then we hang up. */

	f_sleep(1.0);
	deactivate(ack_mdcx);

	/* FIXME: the inter-MSC call has put a number of MNCC messages in the queue, which above code should expect and
	 * clear out. The f_call_hangup() expects an MNCC_REL_IND, so, for the time being, just clear the MNCC messages
	 * before starting the call hangup. Instead of this, the individual messages should be tested for above. */
	MNCC.clear;

	var default ccrel := activate(as_optional_cc_rel(cpars, true));
	f_call_hangup(cpars, true);
	f_sleep(1.0);
	deactivate(ccrel);

	setverdict(pass);
}
function f_tc_ho_inter_msc_out_a5(integer a5_n) runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init(1);

	var BSC_ConnHdlrPars pars := f_init_pars(54);
	pars.net.expect_ciph := a5_n > 0;
	pars.net.expect_auth := pars.net.expect_ciph;
	pars.net.kc_support := bit2oct('00000001'B << a5_n);
	pars.cm2.classmarkInformationType2_oct5.a5_3 := '1'B;
	pars.cm2.classmarkInformationType2_oct5.a5_2 := '0'B;
	pars.cm2.classmarkInformationType2_oct5.cm3 := '1'B;
	pars.cm3 := valueof(ts_CM3_default);
	pars.use_umts_aka := true;

	if (a5_n > 0) {
		f_vty_config(MSCVTY, "network", "authentication required");
	}
	f_vty_config(MSCVTY, "network", "encryption a5 " & int2str(a5_n));

	vc_conn := f_start_handler_with_pars(refers(f_tc_ho_inter_msc_out), pars);
	vc_conn.done;
}
testcase TC_ho_inter_msc_out() runs on MTC_CT {
	f_tc_ho_inter_msc_out_a5(0);
}
testcase TC_ho_inter_msc_out_a5_1() runs on MTC_CT {
	f_tc_ho_inter_msc_out_a5(1);
}
testcase TC_ho_inter_msc_out_a5_3() runs on MTC_CT {
	f_tc_ho_inter_msc_out_a5(3);
}
testcase TC_ho_inter_msc_out_a5_4() runs on MTC_CT {
	f_tc_ho_inter_msc_out_a5(4);
}
testcase TC_ho_inter_msc_out_ipv6() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init(1);

	var BSC_ConnHdlrPars pars := f_init_pars(54);
	pars.use_ipv6 := true;

	vc_conn := f_start_handler_with_pars(refers(f_tc_ho_inter_msc_out), pars);
	vc_conn.done;
}
testcase TC_ho_inter_msc_out_csd() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init(1);

	var BSC_ConnHdlrPars pars := f_init_pars(54);
	pars.use_csd := true;

	vc_conn := f_start_handler_with_pars(refers(f_tc_ho_inter_msc_out), pars);
	vc_conn.done;
}

private function f_tc_lu_imsi_auth_tmsi_check_imei(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	pars.net.expect_auth := true;
	pars.net.expect_imei := true;
	f_init_handler(pars);
	f_perform_lu();
}
testcase TC_lu_imsi_auth_tmsi_check_imei() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "network", "authentication required");
	f_vty_config(MSCVTY, "msc", "check-imei-rqd 1");

	vc_conn := f_start_handler(refers(f_tc_lu_imsi_auth_tmsi_check_imei), 5);
	vc_conn.done;
}

private function f_tc_lu_imsi_auth3g_tmsi_check_imei(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	pars.net.expect_auth := true;
	pars.use_umts_aka := true;
	pars.net.expect_imei := true;
	f_init_handler(pars);
	f_perform_lu();
}
testcase TC_lu_imsi_auth3g_tmsi_check_imei() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "network", "authentication required");
	f_vty_config(MSCVTY, "msc", "check-imei-rqd 1");

	vc_conn := f_start_handler(refers(f_tc_lu_imsi_auth3g_tmsi_check_imei), 5);
	vc_conn.done;
}

private function f_tc_lu_imsi_noauth_tmsi_check_imei(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	pars.net.expect_imei := true;
	f_init_handler(pars);
	f_perform_lu();
}
testcase TC_lu_imsi_noauth_tmsi_check_imei() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "msc", "check-imei-rqd 1");

	vc_conn := f_start_handler(refers(f_tc_lu_imsi_noauth_tmsi_check_imei), 5);
	vc_conn.done;
}

private function f_tc_lu_imsi_noauth_notmsi_check_imei(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	pars.net.expect_tmsi := false;
	pars.net.expect_imei := true;
	f_init_handler(pars);
	f_perform_lu();
}
testcase TC_lu_imsi_noauth_notmsi_check_imei() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "msc", "no assign-tmsi");
	f_vty_config(MSCVTY, "msc", "check-imei-rqd 1");

	vc_conn := f_start_handler(refers(f_tc_lu_imsi_noauth_notmsi_check_imei), 5);
	vc_conn.done;
}

private function f_tc_lu_imsi_auth_tmsi_check_imei_nack(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	var PDU_ML3_MS_NW l3_lu;

	pars.net.expect_auth := true;
	pars.net.expect_imei := true;
	pars.net.check_imei_result := OSMO_GSUP_IMEI_RESULT_NACK;
	f_init_handler(pars);

	/* Cannot use f_perform_lu() as we expect a reject */
	l3_lu := f_build_lu_imsi(g_pars.imsi)
	f_create_gsup_expect(hex2str(g_pars.imsi));
	f_bssap_compl_l3(l3_lu);
	RAN_CONN.send(ts_BSSMAP_ClassmarkUpd(g_pars.cm2, g_pars.cm3));

	f_mm_common();
	f_msc_lu_hlr();
	f_mm_imei();
	f_expect_lu_reject();
	f_expect_clear(verify_vlr_cell_id:=false);
}
testcase TC_lu_imsi_auth_tmsi_check_imei_nack() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "network", "authentication required");
	f_vty_config(MSCVTY, "msc", "check-imei-rqd 1");

	vc_conn := f_start_handler(refers(f_tc_lu_imsi_auth_tmsi_check_imei_nack), 5);
	vc_conn.done;
}

private function f_tc_lu_imsi_auth_tmsi_check_imei_err(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	var PDU_ML3_MS_NW l3_lu;

	pars.net.expect_auth := true;
	pars.net.expect_imei := true;
	pars.net.check_imei_error := true;
	f_init_handler(pars);

	/* Cannot use f_perform_lu() as we expect a reject */
	l3_lu := f_build_lu_imsi(g_pars.imsi)
	f_create_gsup_expect(hex2str(g_pars.imsi));
	f_bssap_compl_l3(l3_lu);
	RAN_CONN.send(ts_BSSMAP_ClassmarkUpd(g_pars.cm2, g_pars.cm3));

	f_mm_common();
	f_msc_lu_hlr();
	f_mm_imei();
	f_expect_lu_reject();
	f_expect_clear(verify_vlr_cell_id:=false);
}
testcase TC_lu_imsi_auth_tmsi_check_imei_err() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "network", "authentication required");
	f_vty_config(MSCVTY, "msc", "check-imei-rqd 1");

	vc_conn := f_start_handler(refers(f_tc_lu_imsi_auth_tmsi_check_imei_err), 5);
	vc_conn.done;
}

private function f_tc_lu_imsi_auth_tmsi_check_imei_early(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	pars.net.expect_auth := true;
	pars.net.expect_imei_early := true;
	f_init_handler(pars);
	f_perform_lu();
}
testcase TC_lu_imsi_auth_tmsi_check_imei_early() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "network", "authentication required");
	f_vty_config(MSCVTY, "msc", "check-imei-rqd early");

	vc_conn := f_start_handler(refers(f_tc_lu_imsi_auth_tmsi_check_imei_early), 5);
	vc_conn.done;
}

private function f_tc_lu_imsi_auth3g_tmsi_check_imei_early(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	pars.net.expect_auth := true;
	pars.use_umts_aka := true;
	pars.net.expect_imei_early := true;
	f_init_handler(pars);
	f_perform_lu();
}
testcase TC_lu_imsi_auth3g_tmsi_check_imei_early() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "network", "authentication required");
	f_vty_config(MSCVTY, "msc", "check-imei-rqd early");

	vc_conn := f_start_handler(refers(f_tc_lu_imsi_auth3g_tmsi_check_imei_early), 5);
	vc_conn.done;
}

private function f_tc_lu_imsi_noauth_tmsi_check_imei_early(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	pars.net.expect_imei_early := true;
	f_init_handler(pars);
	f_perform_lu();
}
testcase TC_lu_imsi_noauth_tmsi_check_imei_early() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "msc", "check-imei-rqd early");

	vc_conn := f_start_handler(refers(f_tc_lu_imsi_noauth_tmsi_check_imei_early), 5);
	vc_conn.done;
}

private function f_tc_lu_imsi_noauth_notmsi_check_imei_early(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	pars.net.expect_tmsi := false;
	pars.net.expect_imei_early := true;
	f_init_handler(pars);
	f_perform_lu();
}
testcase TC_lu_imsi_noauth_notmsi_check_imei_early() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "msc", "no assign-tmsi");
	f_vty_config(MSCVTY, "msc", "check-imei-rqd early");

	vc_conn := f_start_handler(refers(f_tc_lu_imsi_noauth_notmsi_check_imei_early), 5);
	vc_conn.done;
}

private function f_tc_lu_imsi_auth_tmsi_check_imei_early_nack(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	var PDU_ML3_MS_NW l3_lu;

	pars.net.expect_auth := true;
	pars.net.expect_imei_early := true;
	pars.net.check_imei_result := OSMO_GSUP_IMEI_RESULT_NACK;
	f_init_handler(pars);

	/* Cannot use f_perform_lu() as we expect a reject */
	l3_lu := f_build_lu_imsi(g_pars.imsi)
	f_create_gsup_expect(hex2str(g_pars.imsi));
	f_bssap_compl_l3(l3_lu);
	RAN_CONN.send(ts_BSSMAP_ClassmarkUpd(g_pars.cm2, g_pars.cm3));

	f_mm_imei_early();
	f_expect_lu_reject();
	f_expect_clear(verify_vlr_cell_id:=false);
}
testcase TC_lu_imsi_auth_tmsi_check_imei_early_nack() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "network", "authentication required");
	f_vty_config(MSCVTY, "msc", "check-imei-rqd early");

	vc_conn := f_start_handler(refers(f_tc_lu_imsi_auth_tmsi_check_imei_early_nack), 5);
	vc_conn.done;
}

private function f_tc_lu_imsi_auth_tmsi_check_imei_early_err(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	var PDU_ML3_MS_NW l3_lu;

	pars.net.expect_auth := true;
	pars.net.expect_imei_early := true;
	pars.net.check_imei_error := true;
	f_init_handler(pars);

	/* Cannot use f_perform_lu() as we expect a reject */
	l3_lu := f_build_lu_imsi(g_pars.imsi)
	f_create_gsup_expect(hex2str(g_pars.imsi));
	f_bssap_compl_l3(l3_lu);
	RAN_CONN.send(ts_BSSMAP_ClassmarkUpd(g_pars.cm2, g_pars.cm3));

	f_mm_imei_early();
	f_expect_lu_reject();
	f_expect_clear(verify_vlr_cell_id:=false);
}
testcase TC_lu_imsi_auth_tmsi_check_imei_early_err() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "network", "authentication required");
	f_vty_config(MSCVTY, "msc", "check-imei-rqd early");

	vc_conn := f_start_handler(refers(f_tc_lu_imsi_auth_tmsi_check_imei_early_err), 5);
	vc_conn.done;
}

friend function f_tc_invalid_mgcp_crash(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);
	var CallParameters cpars := valueof(t_CallParams('12345'H, 0));

	/* Set invalid IP address so that osmo-msc discards the rtp_stream and MGCP endpoint FSM instances in the middle
	 * of successful MGCP response dispatch. If things aren't safeguarded, the on_success() in osmo_mgcpc_ep_fsm
	 * will cause a use-after-free after that event dispatch. */
	cpars.mgw_conn_1.mgw_rtp_ip := "0.0.0.0";
	cpars.mgw_conn_2.mgw_rtp_ip := "0.0.0.0";
	cpars.rtp_sdp_format := "FOO/8000";
	cpars.expect_release := true;

	f_perform_lu();
	f_mo_call_establish(cpars);
}
testcase TC_invalid_mgcp_crash() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_invalid_mgcp_crash), 7);
	vc_conn.done;
}

/* Test how the MSC handles a malformed MM IDENTITY RESPONSE with no identity. */
friend function f_tc_mm_id_resp_no_identity(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	f_init_handler(pars);

	/* Initiate Location Updating using an unknown TMSI */
	f_bssap_compl_l3(f_build_lu_tmsi('FFFFFFFF'O));

	/* Expect an Identity Request, send response with no identity */
	RAN_CONN.receive(tr_PDU_DTAP_MT(tr_ML3_MT_MM_ID_Req(CM_ID_TYPE_IMSI)));
	RAN_CONN.send(ts_PDU_DTAP_MO(ts_ML3_MO_MM_ID_Rsp({
		lengthIndicator := 1,
		mobileIdentityV := {
			typeOfIdentity := '000'B,
			oddEvenInd_identity := {
				no_identity := {
					oddevenIndicator := '0'B,
					fillerDigits := '00000'H
				}
			}
		}
	})));

	/* XXX: Current osmo-msc does not react on bad/malformed MM IDENTITY RESPONSE immediately.
	 * It instead relies on expiry of timer X1, which is set to 5.0 seconds by default.  This
	 * is not good (DoS vector) and should ideally be fixed, but for now just work it around. */
	f_expect_lu_reject(Tval := 5.0 + 1.0);
	f_expect_clear();
}
testcase TC_mm_id_resp_no_identity() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;

	f_init();

	vc_conn := f_start_handler(refers(f_tc_mm_id_resp_no_identity), 7, verify_cell_id := false);
	vc_conn.done;
}

/* Verify the case when T3212 expires during Paging procedure, just before the receipt
 * of Paging Response. This used to provoke a NULL-pointer dereference in old versions
 * of OsmoMSC, but apparently the bug has been fixed, and we're safe now. */
friend function f_tc_lu_and_expire_while_paging(charstring id, BSC_ConnHdlrPars pars)
runs on BSC_ConnHdlr {
	var charstring imsi := hex2str(pars.imsi);

	f_init_handler(pars);

	/* Perform location update */
	f_perform_lu();

	f_ran_register_imsi(g_pars.imsi, g_pars.tmsi);
	f_create_gsup_expect(hex2str(g_pars.imsi));

	/* Initiate paging procedure from the VTY */
	f_vty_transceive(MSCVTY, "subscriber imsi " & imsi & " paging");
	f_expect_paging();

	/* Emulate T3212 expiration during paging (we don't want to wait, right?) */
	f_vty_transceive(MSCVTY, "subscriber imsi " & imsi & " expire");

	/* MS sends PAGING RESPONSE, *old* OsmoMSC crashes here... */
	f_establish_fully(EST_TYPE_PAG_RESP);

	/* The recent OsmoMSC keeps subscriber in its VLR unless the Paging is completed.
	 * In this case we do not send anything and just wait for a Clear Command. */
	f_expect_clear(verify_vlr_cell_id := false);
}
testcase TC_lu_and_expire_while_paging() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;

	f_init();

	vc_conn := f_start_handler(refers(f_tc_lu_and_expire_while_paging), 7);
	vc_conn.done;
}

private altstep as_mncc_rx_rtp_create(CallParameters cpars) runs on BSC_ConnHdlr {
	[] MNCC.receive(tr_MNCC_RTP_CREATE(cpars.mncc_callref));
}

const charstring REEST_LOST_CONNECTION := "REEST_LOST_CONNECTION";
const charstring REEST_CLEARED := "REEST_CLEARED";

friend function f_tc_call_re_establishment_1(charstring id, BSC_ConnHdlrPars pars)
  runs on BSC_ConnHdlr {
	f_init_handler(pars, t_guard := 30.0);

	f_perform_lu();

	var CallParameters cpars := valueof(t_CallParams('12345'H, 0));
	f_mo_call_establish(cpars);
	f_sleep(3.0);
	COORD.send(REEST_LOST_CONNECTION);
	COORD.send(cpars);
	f_expect_clear(verify_vlr_cell_id := false);
	COORD.send(REEST_CLEARED);
}

friend function f_tc_call_re_establishment_2(charstring id, BSC_ConnHdlrPars pars)
  runs on BSC_ConnHdlr {
	f_init_handler(pars, t_guard := 30.0);
	var CallParameters cpars;

	COORD.receive(REEST_LOST_CONNECTION);
	COORD.receive(tr_CallParams) -> value cpars;

	f_gsup_change_connhdlr(hex2str(g_pars.imsi));
	f_create_smpp_expect(hex2str(pars.msisdn));

	/* The MS has lost the first channel and decides to show up on a new conn (on a nearby neighbor cell) to ask for
	 * CM Re-Establishment. Send a Complete Layer 3 to osmo-msc with a CM Re-Establishment Request. */
	var MobileIdentityLV mi := valueof(ts_MI_IMSI_LV(g_pars.imsi));
	var PDU_ML3_MS_NW l3_info := valueof(ts_CM_REESTABL_REQ(mi));
	f_cl3_or_initial_ue(l3_info);

	/* At this point the other test component should receive the Clear Command for the first A connection. */

	/* This new connection continues with Authentication... */
	f_mm_common();

	/* ...and with Assignment of a voice channel. */
	var template BSSMAP_IE_AoIP_TransportLayerAddress tla_ass :=
		(f_tr_BSSMAP_IE_AoIP_TLA(cpars.mgw_conn_1.mgw_rtp_ip, ?),
		f_tr_BSSMAP_IE_AoIP_TLA(cpars.mgw_conn_2.mgw_rtp_ip, ?));
	RAN_CONN.receive(tr_BSSMAP_AssignmentReq(omit, tla_ass));
	/* By this Assignment Request, the CM Re-Establishment Request is implicitly accepted. */

	/* Send Assignment Complete from BSC */
	var template BSSMAP_IE_AoIP_TransportLayerAddress tla;
	tla := f_ts_BSSMAP_IE_AoIP_TLA(cpars.bss_rtp_ip, cpars.bss_rtp_port);
	var BSSMAP_IE_SpeechCodec codec;
	codec := valueof(ts_BSSMAP_IE_SpeechCodec({ts_CodecFR}));

	/* Make really sure the other component is done with its MGCP */
	COORD.receive(REEST_CLEARED);

	/* Transfer state for this call over to this test component so we can resolve MNCC and MGCP in this function. */
	f_mncc_change_connhdlr(cpars.mncc_callref);
	f_mgcp_change_connhdlr(cpars.mgcp_ep);

	/* osmo-msc may redirect the MGW endpoint to the newly allocated channel.
	 * Apparently osmo-msc currently also sends an MDCX to the CN side, just repeating the same configuration that
	 * is already in use. This test accepts any number of or even lack of MDCX. */
	var default ack_mdcx := activate(as_mgcp_ack_all_mdcx(cpars));
	var default optional_rtp_create := activate(as_mncc_rx_rtp_create(cpars));

	RAN_CONN.send(ts_BSSMAP_AssignmentComplete(omit, tla, codec));

	/* The call has been fully re-established.
	 * Let a bit of time pass before hanging up, for everything to settle. */
	f_sleep(3.0);

	deactivate(optional_rtp_create);
	deactivate(ack_mdcx);

	/* Hang up the call and clear the new, second A connection */
	var default ack_dlcx := activate(as_mgcp_ack_all_dlcx(cpars));

	/* CC release. This is the proper MS initiated release sequence as shown by
	 * https://git.osmocom.org/osmo-msc/tree/doc/sequence_charts/voice_call_full.msc?id=e53ecde83e4fb2470209e818e9ad76a2d6a19190
	 * f_call_hangup() seems a bit mixed up, so here a "proper" sequence. Fix of f_call_hangup() pending. */
	RAN_CONN.send(ts_PDU_DTAP_MO(ts_ML3_MO_CC_DISC(cpars.transaction_id, '0'B, '0000000'B)));
	MNCC.receive(tr_MNCC_DISC_ind(cpars.mncc_callref));
	MNCC.send(ts_MNCC_REL_req(cpars.mncc_callref, valueof(ts_MNCC_cause(23))));
	RAN_CONN.receive(tr_PDU_DTAP_MT(tr_ML3_MT_CC_RELEASE(cpars.transaction_id)));
	RAN_CONN.send(ts_PDU_DTAP_MO(ts_ML3_MO_CC_REL_COMPL(cpars.transaction_id, '0'B)));
	MNCC.receive(tr_MNCC_REL_cnf(cpars.mncc_callref, cause := *));

	/* BSSAP clear */
	interleave {
	[] RAN_CONN.receive(tr_BSSMAP_ClearCommand) {
		RAN_CONN.send(ts_BSSMAP_ClearComplete);
		}
	[] RAN_CONN.receive(tr_MSC_CONN_PRIM_DISC_IND);
	}

	f_sleep(1.0);
	deactivate(ack_dlcx);
}

testcase TC_call_re_establishment() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn1;
	var BSC_ConnHdlr vc_conn2;
	f_init();

	var BSC_ConnHdlrPars pars1 := f_init_pars(91);
	var BSC_ConnHdlrPars pars2 := pars1;

	vc_conn1 := f_start_handler_create(pars1);
	vc_conn2 := f_start_handler_create(pars2);
	connect(vc_conn1:COORD, vc_conn2:COORD);
	f_start_handler_run(vc_conn1, refers(f_tc_call_re_establishment_1), pars1);
	f_start_handler_run(vc_conn2, refers(f_tc_call_re_establishment_2), pars2);
	vc_conn1.done;
	vc_conn2.done;
}

testcase TC_call_re_establishment_auth() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn1;
	var BSC_ConnHdlr vc_conn2;
	f_init();

	f_vty_config(MSCVTY, "network", "authentication required");

	var BSC_ConnHdlrPars pars1 := f_init_pars(92);
	pars1.net.expect_auth := true;
	var BSC_ConnHdlrPars pars2 := pars1;

	vc_conn1 := f_start_handler_create(pars1);
	vc_conn2 := f_start_handler_create(pars2);
	connect(vc_conn1:COORD, vc_conn2:COORD);
	f_start_handler_run(vc_conn1, refers(f_tc_call_re_establishment_1), pars1);
	f_start_handler_run(vc_conn2, refers(f_tc_call_re_establishment_2), pars2);
	vc_conn1.done;
	vc_conn2.done;
}

testcase TC_call_re_establishment_ciph() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn1;
	var BSC_ConnHdlr vc_conn2;
	f_init();

	f_vty_config(MSCVTY, "network", "authentication required");
	f_vty_config(MSCVTY, "network", "encryption a5 3");

	var BSC_ConnHdlrPars pars1 := f_init_pars(92);
	pars1.net.expect_auth := true;
	pars1.net.expect_ciph := true;
	pars1.net.kc_support := '08'O;	/* A5/3 only */
	var BSC_ConnHdlrPars pars2 := pars1;

	vc_conn1 := f_start_handler_create(pars1);
	vc_conn2 := f_start_handler_create(pars2);
	connect(vc_conn1:COORD, vc_conn2:COORD);
	f_start_handler_run(vc_conn1, refers(f_tc_call_re_establishment_1), pars1);
	f_start_handler_run(vc_conn2, refers(f_tc_call_re_establishment_2), pars2);
	vc_conn1.done;
	vc_conn2.done;
}

/* Establish a conn with a valid Mobile Identity. Then send a CM Service Request containing a mismatching Mobile
 * Identity on the same conn. Caused a crash, see OS#5532. */
friend function f_tc_cm_serv_wrong_mi(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);

	/* Set up a fully identified conn */
	f_perform_lu();
	f_establish_fully();

	/* CM Serv Req with mismatching Mobile Identity */
	var MobileIdentityLV mi := valueof(ts_MI_IMSI_LV(f_gen_imsi(99999))); /* ensure it is different from below*/
	RAN_CONN.send(ts_PDU_DTAP_MO(ts_CM_SERV_REQ(CM_TYPE_MO_SMS, mi)));
	RAN_CONN.receive(tr_PDU_DTAP_MT(tr_CM_SERV_REJ));

	/* Cancel the first CM Service from f_establish_fully() */
	RAN_CONN.send(ts_BSSMAP_ClearRequest(0));

	f_expect_clear();
}
testcase TC_cm_serv_wrong_mi() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_tc_cm_serv_wrong_mi), 94);
	vc_conn.done;
}

/*                              a5 0       a5 0        a5 0 3         a5 0 3   a5 3       a5 3
 *         HLR has auth info    no         yes         no             yes      no         yes
 *
 *           test case index    [0]        [1]         [2]            [3]      [4]        [5]
 *   authentication optional    No auth    No auth     attempt auth,  auth     reject     auth
 *                                         (%)         fall back to   +ciph               +ciph
 *                                                     no-auth
 *
 *                              [6]        [7]         [8]            [9]      [10]       [11]
 *  authentication mandatory    reject     auth        reject         auth     reject     auth
 *                                         only                       +ciph               +ciph
 *
 *  (%): Arguably, when HLR has auth info, the MSC should use it. Current behavior of osmo-msc is to not attempt auth at
 *       all. Related: OS#4830.
 */
type record of BSC_ConnHdlrNetworkPars rof_netpars;

const rof_netpars auth_options_testcases := {
	{
		/* [0] auth optional, encr a5 0: no-auth" */
		kc_support := '01'O,
		net_config := { "authentication optional",
				"encryption a5 0" },
		expect_attach_success := true,
		expect_tmsi := true,
		expect_auth_attempt := false,
		hlr_has_auth_info := false,
		expect_auth := false,
		expect_ciph := false,
		expect_imei := false,
		expect_imei_early := false,
		check_imei_result := OSMO_GSUP_IMEI_RESULT_ACK,
		check_imei_error := false
	},
	{
		/* [1] auth optional, encr a5 0, HLR HAS auth info: no-auth */
		kc_support := '01'O,
		net_config := { "authentication optional",
				"encryption a5 0" },
		expect_attach_success := true,
		expect_tmsi := true,
		expect_auth_attempt := false,
		hlr_has_auth_info := true,
		expect_auth := false,
		expect_ciph := false,
		expect_imei := false,
		expect_imei_early := false,
		check_imei_result := OSMO_GSUP_IMEI_RESULT_ACK,
		check_imei_error := false
	},
	{
		/* [2] auth optional, encr a5 0 3, HLR has NO Auth Info: Fall back to no-auth" */
		kc_support := '09'O,
		net_config := { "authentication optional",
				"encryption a5 0 3" },
		expect_attach_success := true,
		expect_tmsi := true,
		expect_auth_attempt := true,
		hlr_has_auth_info := false,
		expect_auth := false,
		expect_ciph := false,
		expect_imei := false,
		expect_imei_early := false,
		check_imei_result := OSMO_GSUP_IMEI_RESULT_ACK,
		check_imei_error := false
	},
	{
		/* [3] auth optional, encr a5 0 3, HLR HAS Auth Info: Use A5/3 */
		kc_support := '09'O,
		net_config := { "authentication optional",
				"encryption a5 0 3" },
		expect_attach_success := true,
		expect_tmsi := true,
		expect_auth_attempt := true,
		hlr_has_auth_info := true,
		expect_auth := true,
		expect_ciph := true,
		expect_imei := false,
		expect_imei_early := false,
		check_imei_result := OSMO_GSUP_IMEI_RESULT_ACK,
		check_imei_error := false
	},
	{
		/* [4] auth optional, encr a5 3, HLR has NO Auth Info: reject.
		 * Auth is required implicitly because ciph is required. */
		kc_support := '08'O,
		net_config := { "authentication optional",
				"encryption a5 3" },
		expect_attach_success := false,
		expect_tmsi := true,
		expect_auth_attempt := true,
		hlr_has_auth_info := false,
		expect_auth := false,
		expect_ciph := false,
		expect_imei := false,
		expect_imei_early := false,
		check_imei_result := OSMO_GSUP_IMEI_RESULT_ACK,
		check_imei_error := false
	},
	{
		/* [5] auth optional, encr a5 3, HLR HAS Auth Info: auth + ciph.
		 * Auth is required implicitly because ciph is required. */
		kc_support := '08'O,
		net_config := { "authentication optional",
				"encryption a5 3" },
		expect_attach_success := true,
		expect_tmsi := true,
		expect_auth_attempt := true,
		hlr_has_auth_info := true,
		expect_auth := true,
		expect_ciph := true,
		expect_imei := false,
		expect_imei_early := false,
		check_imei_result := OSMO_GSUP_IMEI_RESULT_ACK,
		check_imei_error := false
	},

	/* Same as above, but with 'authentication required' */

	{
		/* [6] auth required, encr a5 0, HLR has NO auth info: reject */
		kc_support := '01'O,
		net_config := { "authentication required",
				"encryption a5 0" },
		expect_attach_success := false,
		expect_tmsi := true,
		expect_auth_attempt := true,
		hlr_has_auth_info := false,
		expect_auth := false,
		expect_ciph := false,
		expect_imei := false,
		expect_imei_early := false,
		check_imei_result := OSMO_GSUP_IMEI_RESULT_ACK,
		check_imei_error := false
	},
	{
		/* [7] auth required, encr a5 0, HLR HAS auth info: do auth, no ciph" */
		kc_support := '01'O,
		net_config := { "authentication required",
				"encryption a5 0" },
		expect_attach_success := true,
		expect_tmsi := true,
		expect_auth_attempt := true,
		hlr_has_auth_info := true,
		expect_auth := true,
		expect_ciph := false,
		expect_imei := false,
		expect_imei_early := false,
		check_imei_result := OSMO_GSUP_IMEI_RESULT_ACK,
		check_imei_error := false
	},
	{
		/* [8] auth required, encr a5 0 3, HLR has NO Auth Info: reject */
		kc_support := '09'O,
		net_config := { "authentication required",
				"encryption a5 0 3" },
		expect_attach_success := false,
		expect_tmsi := true,
		expect_auth_attempt := true,
		hlr_has_auth_info := false,
		expect_auth := false,
		expect_ciph := false,
		expect_imei := false,
		expect_imei_early := false,
		check_imei_result := OSMO_GSUP_IMEI_RESULT_ACK,
		check_imei_error := false
	},
	{
		/* [9] auth required, encr a5 0 3, HLR HAS Auth Info: Use A5/3 */
		kc_support := '09'O,
		net_config := { "authentication required",
				"encryption a5 0 3" },
		expect_attach_success := true,
		expect_tmsi := true,
		expect_auth_attempt := true,
		hlr_has_auth_info := true,
		expect_auth := true,
		expect_ciph := true,
		expect_imei := false,
		expect_imei_early := false,
		check_imei_result := OSMO_GSUP_IMEI_RESULT_ACK,
		check_imei_error := false
	},
	{
		/* [10] auth required, encr a5 3, HLR has NO Auth Info: reject. */
		kc_support := '08'O,
		net_config := { "authentication required",
				"encryption a5 3" },
		expect_attach_success := false,
		expect_tmsi := true,
		expect_auth_attempt := true,
		hlr_has_auth_info := false,
		expect_auth := false,
		expect_ciph := false,
		expect_imei := false,
		expect_imei_early := false,
		check_imei_result := OSMO_GSUP_IMEI_RESULT_ACK,
		check_imei_error := false
	},
	{
		/* [11] auth required, encr a5 3, HLR HAS Auth Info: auth + ciph. */
		kc_support := '08'O,
		net_config := { "authentication required",
				"encryption a5 3" },
		expect_attach_success := true,
		expect_tmsi := true,
		expect_auth_attempt := true,
		hlr_has_auth_info := true,
		expect_auth := true,
		expect_ciph := true,
		expect_imei := false,
		expect_imei_early := false,
		check_imei_result := OSMO_GSUP_IMEI_RESULT_ACK,
		check_imei_error := false
	}
};

private function f_tc_auth_options(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);

	/* Location Updating */
	log(MSCVTY, "f_perform_lu() starting");
	f_perform_lu();
	log(MSCVTY, "f_perform_lu() done");

	f_sleep(1.0);

	if (not pars.net.expect_attach_success) {
		/* Expected above LU to fail. In order to test CM Service Request below, a LU has to succeed first. So
		 * run another LU that will be successful. Careful not to load auth tokens into the VLR that may taint
		 * the test for CM Service Request below. */

		log(MSCVTY, "Running a successful LU so that CM Service Request can be tested");
		var BSC_ConnHdlrNetworkPars saved_net := g_pars.net;
		g_pars.net.kc_support := '01'O;
		g_pars.net.expect_attach_success := true;
		g_pars.net.expect_auth_attempt := false;
		g_pars.net.expect_auth := false;
		g_pars.net.expect_ciph := false;
		f_vty_config3(MSCVTY, {"network"}, {"authentication optional", "encryption a5 0"});
		f_perform_lu();

		/* Reconfigure like it was before */
		g_pars.net := saved_net;
		f_vty_config3(MSCVTY, {"network"}, g_pars.net.net_config);
		log(MSCVTY, "Running a successful LU done");
	}

	/* CM Service Request */
	log(MSCVTY, "f_establish_fully() starting");
	f_establish_fully();
	log(MSCVTY, "f_establish_fully() done");
	RAN_CONN.send(ts_BSSMAP_ClearRequest(0));
	f_expect_clear();
}

function f_TC_auth_options(integer tc_i) runs on MTC_CT {
	f_init();

	var BSC_ConnHdlrNetworkPars tc := auth_options_testcases[tc_i];

	f_vty_config3(MSCVTY, {"network"}, tc.net_config);

	var BSC_ConnHdlrPars pars := f_init_pars(42300 + tc_i);
	pars.net := tc;

	var BSC_ConnHdlr vc_conn;
	vc_conn := f_start_handler_with_pars(refers(f_tc_auth_options), pars);
	vc_conn.done;
}

testcase TC_auth_options_0() runs on MTC_CT {
	f_TC_auth_options(0);
}

testcase TC_auth_options_1() runs on MTC_CT {
	f_TC_auth_options(1);
}

testcase TC_auth_options_2() runs on MTC_CT {
	f_TC_auth_options(2);
}

testcase TC_auth_options_3() runs on MTC_CT {
	f_TC_auth_options(3);
}

testcase TC_auth_options_4() runs on MTC_CT {
	f_TC_auth_options(4);
}

testcase TC_auth_options_5() runs on MTC_CT {
	f_TC_auth_options(5);
}

testcase TC_auth_options_6() runs on MTC_CT {
	f_TC_auth_options(6);
}

testcase TC_auth_options_7() runs on MTC_CT {
	f_TC_auth_options(7);
}

testcase TC_auth_options_8() runs on MTC_CT {
	f_TC_auth_options(8);
}

testcase TC_auth_options_9() runs on MTC_CT {
	f_TC_auth_options(9);
}

testcase TC_auth_options_10() runs on MTC_CT {
	f_TC_auth_options(10);
}

testcase TC_auth_options_11() runs on MTC_CT {
	f_TC_auth_options(11);
}

private function f_set_cpars_csd(inout CallParameters cpars, charstring bs_name, BIT1 async,
				 GSM48_bcap_transp transp, GSM48_bcap_user_rate user_rate) {
	log("-----------------------------------------------");
	log("CSD Bearer Service: " & bs_name);
	log("-----------------------------------------------");

	cpars.csd := true;

	cpars.bearer_cap := valueof(ts_Bcap_csd);
	cpars.bearer_cap.octet6.synchronous_asynchronous := async;
	cpars.bearer_cap.octet6.connectionElement := int2bit(enum2int(transp), 2);
	cpars.bearer_cap.octet6.userRate := int2bit(enum2int(user_rate), 4);

	cpars.mncc_bearer_cap := valueof(ts_MNCC_bcap_data);
	cpars.mncc_bearer_cap.data.async := bit2int(async);
	cpars.mncc_bearer_cap.data.transp := transp;
	cpars.mncc_bearer_cap.data.user_rate := user_rate;
}

friend function f_mo_csd(charstring bs_name, BIT1 async, GSM48_bcap_transp transp, GSM48_bcap_user_rate user_rate)
		runs on BSC_ConnHdlr {
	var CallParameters cpars := valueof(t_CallParams);

	g_Tguard.start(20.0);
	f_set_cpars_csd(cpars, bs_name, async, transp, user_rate);
	f_perform_lu();
	f_mo_call(cpars, 0.5);
}

friend function f_tc_lu_and_mo_csd(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);

	f_mo_csd("BS21T", '1'B, GSM48_BCAP_TR_TRANSP, GSM48_BCAP_UR_300);
	f_mo_csd("BS22T", '1'B, GSM48_BCAP_TR_TRANSP, GSM48_BCAP_UR_1200);
	f_mo_csd("BS24T", '1'B, GSM48_BCAP_TR_TRANSP, GSM48_BCAP_UR_2400);
	f_mo_csd("BS25T", '1'B, GSM48_BCAP_TR_TRANSP, GSM48_BCAP_UR_4800);
	f_mo_csd("BS26T", '1'B, GSM48_BCAP_TR_TRANSP, GSM48_BCAP_UR_9600);

	f_mo_csd("BS21NT", '1'B, GSM48_BCAP_TR_RLP, GSM48_BCAP_UR_300);
	f_mo_csd("BS22NT", '1'B, GSM48_BCAP_TR_RLP, GSM48_BCAP_UR_1200);
	f_mo_csd("BS24NT", '1'B, GSM48_BCAP_TR_RLP, GSM48_BCAP_UR_2400);
	f_mo_csd("BS25NT", '1'B, GSM48_BCAP_TR_RLP, GSM48_BCAP_UR_4800);
	f_mo_csd("BS26NT", '1'B, GSM48_BCAP_TR_RLP, GSM48_BCAP_UR_9600);

	f_mo_csd("BS31T", '0'B, GSM48_BCAP_TR_TRANSP, GSM48_BCAP_UR_1200);
	f_mo_csd("BS32T", '0'B, GSM48_BCAP_TR_TRANSP, GSM48_BCAP_UR_2400);
	f_mo_csd("BS33T", '0'B, GSM48_BCAP_TR_TRANSP, GSM48_BCAP_UR_4800);
	f_mo_csd("BS34T", '0'B, GSM48_BCAP_TR_TRANSP, GSM48_BCAP_UR_9600);
}
testcase TC_lu_and_mo_csd() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_lu_and_mo_csd), 7);
	vc_conn.done;
}

friend function f_mt_csd(charstring bs_name, BIT1 async, GSM48_bcap_transp transp, GSM48_bcap_user_rate user_rate)
		runs on BSC_ConnHdlr {
	var CallParameters cpars := valueof(t_CallParams);

	g_Tguard.start(20.0);
	f_set_cpars_csd(cpars, bs_name, async, transp, user_rate);
	f_perform_lu();
	f_mt_call(cpars, 0.5);
}
friend function f_tc_lu_and_mt_csd(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);

	f_mt_csd("BS21T", '1'B, GSM48_BCAP_TR_TRANSP, GSM48_BCAP_UR_300);
	f_mt_csd("BS22T", '1'B, GSM48_BCAP_TR_TRANSP, GSM48_BCAP_UR_1200);
	f_mt_csd("BS24T", '1'B, GSM48_BCAP_TR_TRANSP, GSM48_BCAP_UR_2400);
	f_mt_csd("BS25T", '1'B, GSM48_BCAP_TR_TRANSP, GSM48_BCAP_UR_4800);
	f_mt_csd("BS26T", '1'B, GSM48_BCAP_TR_TRANSP, GSM48_BCAP_UR_9600);

	f_mt_csd("BS21NT", '1'B, GSM48_BCAP_TR_RLP, GSM48_BCAP_UR_300);
	f_mt_csd("BS22NT", '1'B, GSM48_BCAP_TR_RLP, GSM48_BCAP_UR_1200);
	f_mt_csd("BS24NT", '1'B, GSM48_BCAP_TR_RLP, GSM48_BCAP_UR_2400);
	f_mt_csd("BS25NT", '1'B, GSM48_BCAP_TR_RLP, GSM48_BCAP_UR_4800);
	f_mt_csd("BS26NT", '1'B, GSM48_BCAP_TR_RLP, GSM48_BCAP_UR_9600);

	f_mt_csd("BS31T", '0'B, GSM48_BCAP_TR_TRANSP, GSM48_BCAP_UR_1200);
	f_mt_csd("BS32T", '0'B, GSM48_BCAP_TR_TRANSP, GSM48_BCAP_UR_2400);
	f_mt_csd("BS33T", '0'B, GSM48_BCAP_TR_TRANSP, GSM48_BCAP_UR_4800);
	f_mt_csd("BS34T", '0'B, GSM48_BCAP_TR_TRANSP, GSM48_BCAP_UR_9600);
}
testcase TC_lu_and_mt_csd() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_lu_and_mt_csd), 7);
	vc_conn.done;
}

/* MSC <-> BSC: ID req/rsp for IMSI */
private altstep as_id_req_imsi()
runs on BSC_ConnHdlr {
	[] RAN_CONN.receive(tr_PDU_DTAP_MT(tr_ML3_MT_MM_ID_Req(CM_ID_TYPE_IMSI))) {
		var MobileIdentityLV mi := valueof(ts_MI_IMSI_LV(g_pars.imsi));
		RAN_CONN.send(ts_PDU_DTAP_MO(ts_ML3_MO_MM_ID_Rsp(mi)));
		repeat;
		}
}

/* MSC is configured to not assign a TMSI; MS sends LU Request with a TMSI MI (from another cell), and MSC shall not use
 * that TMSI. */
private function f_tc_lu_tmsi_noauth_notmsi(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars, t_guard := 20.0);

	/* Perform Location Updating using an unknown TMSI MI. Expect an ID Request to come from the MSC and answer
	 * that with as_id_req_imsi(). */
	activate(as_id_req_imsi());
	f_perform_lu(use_mi := ts_MI_TMSI_LV(pars.tmsi));

	f_sleep(1.0);

	/* Attached by invalid TMSI, and the MSC has asked for the IMSI. Initiate Paging and make sure the MSC doesn't
	 * use the invalid TMSI for it. */
	f_ran_register_imsi(g_pars.imsi, omit);
	f_vty_transceive(MSCVTY, "subscriber imsi " & hex2str(g_pars.imsi) & " paging");
	f_expect_paging_tmsi(omit);

	/* Respond to paging, to clean up internal paging state for this subscriber, so we can get a clean second run
	 * out of this test code. Don't use the TMSI in the paging response. */
	f_cl3_or_initial_ue(valueof(ts_PAG_RESP(ts_MI_IMSI_LV(pars.imsi))));
	f_mm_common();
	/* The paging was by VTY, so nothing happens, just a release. */
	f_expect_clear();

	/* Clean up ttcn state for the second test run to work out. */
	f_unregister_gsup_imsi(hex2str(pars.imsi));
	f_ran_unregister_imsi(pars.imsi);
}
testcase TC_lu_tmsi_noauth_notmsi() runs on MTC_CT {
	var BSC_ConnHdlrPars pars;
	var BSC_ConnHdlr vc_conn;
	f_init();
	f_vty_config(MSCVTY, "msc", "no assign-tmsi");
	pars := f_init_pars(101);
	pars.net.expect_tmsi := false;
	pars.tmsi := '0badbad0'O;
	pars.mm_info := false;
	vc_conn := f_start_handler_with_pars(refers(f_tc_lu_tmsi_noauth_notmsi), pars);
	vc_conn.done;

	/* Now run the same test *again*, to test against an evil twin VLR entry:
	 * A vlr_subscr with the correct IMSI is now present in the VLR.
	 * We again ask for a LU with the 0x0bad TMSI. The VLR will initially create another vlr_subsrc(TMSI=0x0bad).
	 * When it learns the IMSI via ID Request, it needs to realize that this IMSI is already present on the first
	 * vsub, and sort out the VLR record so that only one entry for this IMSI exists.
	 */
	pars := f_init_pars(101);
	pars.net.expect_tmsi := false;
	pars.tmsi := '0badbad0'O;
	pars.mm_info := false;
	vc_conn := f_start_handler_with_pars(refers(f_tc_lu_tmsi_noauth_notmsi), pars);
	vc_conn.done;
}

friend function f_tc_lu_and_mo_call_reass_for_mt_codec(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);
	var CallParameters cpars := valueof(t_CallParams);
	/* MO will first choose GSM-FR = BSC returns GSM-FR in Assignment Complete's Codec (Chosen) */
	cpars.ass_compl_chosen_codec := valueof(ts_CodecFR);
	/* But when the MT call leg responds, we learn that it only supports AMR */
	cpars.mncc_alert_req_sends_remote_sdp :=
			  "v=0\r\n"
			& "o=BSC_ConnectionHandler.ttcn 0 0 IN IP4 1.1.1.1\r\n"
			& "s=GSM Call\r\n"
			& "c=IN IP4 " & cpars.bss_rtp_ip & "\r\n"
			& "t=0 0\r\n"
			& "m=audio " & int2str(cpars.bss_rtp_port) & " RTP/AVP 112\r\n"
			& "a=rtpmap:112 AMR/8000\r\n"
			& "a=fmtp:112 octet-align=1\r\n"
			& "a=ptime:20\r\n";
	/* MSC should ask for another Assignment after MNCC_ALERT_REQ, that should now contain only the remote call
	 * leg's capabilities, i.e. only AMR. */
	cpars.expect_re_assignment := true;
	cpars.re_ass_req_codecs := {valueof(ts_CodecAMR_F), valueof(ts_CodecAMR_H)};
	/* When the MSC asks for another Assignment after MNCC_ALERT_REQ, we'll give it AMR. */
	cpars.re_ass_compl_chosen_codec := valueof(ts_CodecAMR_F);
	f_perform_lu();
	f_mo_call(cpars);
}
testcase TC_lu_and_mo_call_reass_for_mt_codec() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_tc_lu_and_mo_call_reass_for_mt_codec), 7);
	vc_conn.done;
}

/* When the last local IPA/SCTP link/ASP is terminated, last AS goes inactive
 * and a SCCP N-PCSTATE.ind (unavailable) should arrive to upper layers.
 * As a result, osmo-msc should immediately mark the ran_peer as unusable.
 * In AoIP, the SCCP N-PCSTATE is triggered by instructing the STP to
 * shutdown the ASP serving the MSC, which will close the SCTP assoc between
 * itself and IUT (MSC), which should then generate an N-PCSTATE.ind.
 */
friend function f_tc_mt_sms(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	var SmsParameters spars := valueof(t_SmsPars);

	f_init_handler(pars);

	/* register an 'expect' for given IMSI (+TMSI) */
	f_ran_register_imsi(g_pars.imsi, g_pars.tmsi);

	f_vty_sms_send(hex2str(pars.imsi), "2342", "Hello SMS");

	/* MSC->BSC: expect PAGING from MSC. We can't match on specific TMSI
	because it was provided in a previous first vc_conn in test during 1st LU. */
	f_expect_paging_tmsi(?);

	/* Establish DTAP / BSSAP / SCCP connection */
	f_establish_fully(EST_TYPE_PAG_RESP);

	spars.tp.ud := 'C8329BFD064D9B53'O;
	f_mt_sms(spars);

	f_expect_clear();
	f_ran_unregister_imsi(g_pars.imsi);
}
testcase TC_stat_bsc_sctp_disconnected() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	var BSC_ConnHdlrPars pars;
	var charstring msc_stats_prefix := f_msc_stats_prefix();

	/* ran_peers.total: Despite we only use 1 RAN_CONN in this test, previous tests may have
	 * used more of them (up to configured NUM_BSC), and hence IUT may remember about them: */
	var StatsDExpects expect_connected := {
		{name := msc_stats_prefix & "ran_peers.total", mtype := "g", min := 1, max := NUM_BSC},
		{name := msc_stats_prefix & "ran_peers.active", mtype := "g", min := 1, max := 1}
	};
	var StatsDExpects expect_disconnected := {
		{name := msc_stats_prefix & "ran_peers.total", mtype := "g", min := 1, max := NUM_BSC},
		{name := msc_stats_prefix & "ran_peers.active", mtype := "g", min := 0, max := 0}
	};

	g_statd_timeout := 15.0;
	f_init();
	f_init_vty_stp();

	connect(self:STATSD_PROC, vc_STATSD:STATSD_PROC);
	f_statsd_reset();
	f_statsd_expect(expect_connected, wait_converge := true);
	disconnect(self:STATSD_PROC, vc_STATSD:STATSD_PROC);

	pars := f_init_pars(1);
	vc_conn := f_start_handler_with_pars(refers(f_tc_lu_and_mt_sms), pars);
	vc_conn.done;

	f_logp(MSCVTY, "Shutting down MSC ASP in STP");
	f_vty_stp_msc_asp_cmd("shutdown");

	/* Wait for AS PENDING->INACTIVE transition (T(r) timeout after 2000msec): */
	connect(self:STATSD_PROC, vc_STATSD:STATSD_PROC);
	f_statsd_expect(expect_disconnected, wait_converge := true);
	disconnect(self:STATSD_PROC, vc_STATSD:STATSD_PROC);

	f_logp(MSCVTY, "Restarting MSC ASP in STP");
	f_vty_stp_msc_asp_cmd("no shutdown");

	connect(self:STATSD_PROC, vc_STATSD:STATSD_PROC);
	f_statsd_expect(expect_connected, wait_converge := true);
	disconnect(self:STATSD_PROC, vc_STATSD:STATSD_PROC);

	vc_conn := f_start_handler_with_pars(refers(f_tc_mt_sms), pars);
	vc_conn.done;
	setverdict(pass);
}

/* Test starting and stopping silent call via the VTY */
private function f_TC_silent_call_start_stop(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	var charstring cmd, resp;
	timer T;

	f_init_handler(pars);

	cmd := "subscriber imsi " & hex2str(g_pars.imsi) & " silent-call ";

	f_perform_lu();
	f_ran_register_imsi(g_pars.imsi, g_pars.tmsi);

	/* Start silent call via the VTY */
	MSCVTY.send(cmd & "start any signalling");
	resp := f_vty_wait_for_prompt(MSCVTY);
	if (resp != "% Silent call initiated") {
		setverdict(fail, "VTY: Unexpected response: ", resp);
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__);
	}

	/* MSC->BSC: expect PAGING from the MSC */
	f_expect_paging();
	/* MS -> MSC: PAGING RESPONSE */
	f_establish_fully(EST_TYPE_PAG_RESP);

	/* Hold the call for some time */
	T.start(3.0);
	alt {
	[] RAN_CONN.receive(tr_BSSMAP_AssignmentReq) {
		RAN_CONN.send(ts_BSSMAP_AssignmentComplete);
		repeat;
		}
	[] as_unexp_bssap_msg();
	[] T.timeout { setverdict(pass); }
	}

	/* Stop silent call via the VTY */
	MSCVTY.send(cmd & "stop");
	resp := f_vty_wait_for_prompt(MSCVTY);
	if (resp != "% Silent call ended\n% Silent call stopped") {
		setverdict(fail, "VTY: Unexpected response: ", resp);
	}

	f_expect_clear();
}
testcase TC_silent_call_start_stop() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_TC_silent_call_start_stop), 30);
	vc_conn.done;
}

/* Test initiating a silent call while there's an active connection.
 * The MSC is expected to be smart and reject such an attempt. */
private function f_TC_silent_call_active_conn(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	var charstring cmd, resp;

	f_init_handler(pars);

	cmd := "subscriber imsi " & hex2str(g_pars.imsi) & " silent-call ";

	f_perform_lu();
	f_ran_register_imsi(g_pars.imsi, g_pars.tmsi);

	/* The MS establishes a connection (e.g. for periodic Location Updating) */
	f_establish_fully();

	/* Try initiating a silent call via the VTY */
	MSCVTY.send(cmd & "start any signalling");
	resp := f_vty_wait_for_prompt(MSCVTY);
	select (resp) {
	case ("% Subscriber already has an active connection") {
		setverdict(pass);
		}
	case ("% Silent call initiated") {
		setverdict(fail, "The MSC initiated silent call despite an active connection");
		f_expect_paging();
		}
	case else {
		setverdict(fail, "Unexpected VTY response: ", resp);
		}
	}

	RAN_CONN.send(ts_BSSMAP_ClearRequest(0));
	f_expect_clear();
}
testcase TC_silent_call_active_conn() runs on MTC_CT {
	var BSC_ConnHdlr vc_conn;
	f_init();

	vc_conn := f_start_handler(refers(f_TC_silent_call_active_conn), 30);
	vc_conn.done;
}

control {
	execute( TC_cr_before_reset() );
	execute( TC_lu_imsi_noauth_tmsi() );
	execute( TC_lu_imsi_noauth_notmsi() );
	execute( TC_lu_tmsi_noauth_notmsi() );
	execute( TC_lu_imsi_reject() );
	execute( TC_lu_imsi_timeout_gsup() );
	execute( TC_lu_imsi_auth_tmsi() );
	execute( TC_lu_imsi_auth3g_tmsi() );
	execute( TC_lu_imsi_timeout_tmsi_realloc() );
	execute( TC_cmserv_imsi_unknown() );
	execute( TC_cmserv_tmsi_unknown() );
	execute( TC_lu_and_mo_call() );
	execute( TC_lu_and_mo_call_ipv6() );
	execute( TC_lu_and_mo_call_sccp_tiar_timeout() );
	execute( TC_lu_auth_sai_timeout() );
	execute( TC_lu_auth_sai_err() );
	execute( TC_lu_clear_request() );
	execute( TC_mo_call_clear_request() );
	execute( TC_mt_call_clear_request() );
	execute( TC_lu_disconnect() );
	execute( TC_lu_by_imei() );
	execute( TC_lu_by_tmsi_noauth_unknown() );
	execute( TC_attached_imsi_lu_unknown_tmsi() );
	execute( TC_imsi_detach_by_imsi() );
	execute( TC_imsi_detach_by_tmsi() );
	execute( TC_imsi_detach_by_imei() );
	execute( TC_emerg_call_imei_reject() );
	execute( TC_emerg_call_imsi() );
	execute( TC_cm_serv_req_vgcs_reject() );
	execute( TC_cm_serv_req_vbs_reject() );
	execute( TC_cm_serv_req_lcs_reject() );
	execute( TC_cm_reest_req_reject() );
	execute( TC_lu_auth_2G_fail() );
	execute( TC_lu_imsi_auth_tmsi_encr_13_13() );
	execute( TC_cl3_no_payload() );
	execute( TC_cl3_rnd_payload() );
	execute( TC_establish_and_nothing() );
	execute( TC_mo_setup_and_nothing() );
	execute( TC_mo_crcx_ran_timeout() );
	execute( TC_mo_crcx_ran_reject() );
	execute( TC_mt_crcx_ran_reject() );
	execute( TC_mo_setup_and_dtmf_dup() );
	execute( TC_mt_t310() );
	execute( TC_gsup_cancel() );
	execute( TC_lu_imsi_auth_tmsi_encr_1_13() );
	execute( TC_lu_imsi_auth_tmsi_encr_3_13() );
	execute( TC_lu_imsi_auth_tmsi_encr_3_1() );
	execute( TC_lu_imsi_auth_tmsi_encr_3_1_no_cm() );
	execute( TC_lu_imsi_auth_tmsi_encr_13_2() );
	execute( TC_lu_imsi_auth_tmsi_encr_013_2() );
	execute( TC_lu_imsi_auth_tmsi_encr_0134_1() );
	execute( TC_lu_imsi_auth_tmsi_encr_0134_34() );
	execute( TC_lu_imsi_auth_tmsi_encr_0134_34_no_cm3() );

	execute( TC_mo_release_timeout() );
	execute( TC_lu_and_mt_call_no_dlcx_resp() );
	execute( TC_reset_two() );

	execute( TC_lu_and_mt_call() );
	execute( TC_lu_and_mt_call_ipv6() );
	execute( TC_lu_and_mt_call_already_paging() );
	execute( TC_lu_and_mt_call_osmux() );

	execute( TC_lu_and_mo_sms() );
	execute( TC_lu_and_mt_sms() );
	execute( TC_lu_and_mt_sms_already_paging() );
	execute( TC_lu_and_mt_sms_paging_and_nothing() );
	execute( TC_lu_and_mt_sms_paging_repeated() );
	execute( TC_smpp_mo_sms() );
	execute( TC_smpp_mo_sms_rp_error() );
	execute( TC_smpp_mt_sms() );

	execute( TC_gsup_mo_sms() );
	execute( TC_gsup_mo_smma() );
	execute( TC_gsup_mt_sms_ack() );
	execute( TC_gsup_mt_sms_err() );
	execute( TC_gsup_mt_sms_rp_mr() );
	execute( TC_gsup_mo_mt_sms_rp_mr() );
	execute( TC_gsup_mt_multi_part_sms() );
	execute( TC_gsup_mt_sms_lu_delay() );
	execute( TC_gsup_mt_sms_paging_timeout() );
	execute( TC_gsup_mt_sms_conn_timeout() );
	execute( TC_gsup_lu_and_det() );

	execute( TC_lu_and_mo_ussd_single_request() );
	execute( TC_lu_and_mt_ussd_notification() );
	execute( TC_lu_and_mo_ussd_during_mt_call() );
	execute( TC_lu_and_mt_ussd_during_mt_call() );
	execute( TC_lu_and_mo_ussd_mo_release() );
	execute( TC_lu_and_ss_session_timeout() );

	execute( TC_mt_ussd_for_unknown_subscr() );
	execute( TC_mo_ussd_for_unknown_trans() );
	execute( TC_proc_ss_for_unknown_session() );
	execute( TC_proc_ss_paging_fail() );
	execute( TC_proc_ss_abort() );
	execute( TC_lu_and_ussd_notify_during_mt_call() );
	execute( TC_mo_ussd_evil_ms() );

	execute( TC_multi_lu_and_mo_ussd() );
	execute( TC_multi_lu_and_mt_ussd() );

	execute( TC_cipher_complete_with_invalid_cipher() );
	execute( TC_cipher_complete_1_without_cipher() );
	execute( TC_cipher_complete_3_without_cipher() );
	execute( TC_cipher_complete_13_without_cipher() );
	execute( TC_lu_with_invalid_mcc_mnc() );

	execute( TC_sgsap_reset() );
	execute( TC_sgsap_lu() );
	execute( TC_sgsap_lu_imsi_reject() );
	execute( TC_sgsap_lu_and_nothing() );
	execute( TC_sgsap_expl_imsi_det_eps() );
	execute( TC_sgsap_impl_imsi_det_eps() );
	execute( TC_sgsap_expl_imsi_det_noneps() );
	execute( TC_sgsap_impl_imsi_det_noneps() );
	execute( TC_sgsap_paging_rej() );
	execute( TC_sgsap_paging_subscr_rej() );
	execute( TC_sgsap_paging_ue_unr() );
	execute( TC_sgsap_paging_and_nothing() );
	execute( TC_sgsap_paging_and_lu() );
	execute( TC_sgsap_mt_sms() );
	execute( TC_sgsap_mo_sms() );
	execute( TC_sgsap_mt_sms_and_nothing() );
	execute( TC_sgsap_mt_sms_and_reject() );
	execute( TC_sgsap_unexp_ud() );
	execute( TC_sgsap_unsol_ud() );
	execute( TC_bssap_lu_sgsap_lu_and_mt_call() );
	execute( TC_sgsap_lu_and_mt_call() );
	execute( TC_sgsap_vlr_failure() );

	execute( TC_ho_inter_bsc_unknown_cell() );
	execute( TC_ho_inter_bsc() );
	execute( TC_ho_inter_bsc_a5_1() );
	execute( TC_ho_inter_bsc_a5_3() );
	execute( TC_ho_inter_bsc_a5_4() );
	execute( TC_ho_inter_bsc_ipv6() );
	execute( TC_ho_inter_bsc_csd() );

	execute( TC_ho_inter_msc_out() );
	execute( TC_ho_inter_msc_out_a5_1() );
	execute( TC_ho_inter_msc_out_a5_3() );
	execute( TC_ho_inter_msc_out_a5_4() );
	execute( TC_ho_inter_msc_out_ipv6() );
	execute( TC_ho_inter_msc_out_csd() );

	execute( TC_lu_imsi_auth_tmsi_check_imei() );
	execute( TC_lu_imsi_auth3g_tmsi_check_imei() );
	execute( TC_lu_imsi_noauth_tmsi_check_imei() );
	execute( TC_lu_imsi_noauth_notmsi_check_imei() );
	execute( TC_lu_imsi_auth_tmsi_check_imei_nack() );
	execute( TC_lu_imsi_auth_tmsi_check_imei_err() );
	execute( TC_lu_imsi_auth_tmsi_check_imei_early() );
	execute( TC_lu_imsi_auth3g_tmsi_check_imei_early() );
	execute( TC_lu_imsi_noauth_tmsi_check_imei_early() );
	execute( TC_lu_imsi_noauth_notmsi_check_imei_early() );
	execute( TC_lu_imsi_auth_tmsi_check_imei_early_nack() );
	execute( TC_lu_imsi_auth_tmsi_check_imei_early_err() );
	execute( TC_lu_imsi_auth_tmsi_encr_3_1_log_msc_debug() );

	execute( TC_mo_cc_bssmap_clear() );
	execute( TC_invalid_mgcp_crash() );
	execute( TC_mm_id_resp_no_identity() );
	execute( TC_lu_and_expire_while_paging() );
	execute( TC_paging_response_imsi_unknown() );
	execute( TC_paging_response_tmsi_unknown() );

	execute( TC_call_re_establishment() );
	execute( TC_call_re_establishment_auth() );
	execute( TC_call_re_establishment_ciph() );

	execute( TC_cm_serv_wrong_mi() );

	execute( TC_auth_options_0() );
	execute( TC_auth_options_1() );
	execute( TC_auth_options_2() );
	execute( TC_auth_options_3() );
	execute( TC_auth_options_4() );
	execute( TC_auth_options_5() );
	execute( TC_auth_options_6() );
	execute( TC_auth_options_7() );
	execute( TC_auth_options_8() );
	execute( TC_auth_options_9() );
	execute( TC_auth_options_10() );
	execute( TC_auth_options_11() );

	execute( TC_lu_and_mo_csd() );
	execute( TC_lu_and_mt_csd() );

	execute( TC_lu_and_mo_call_reass_for_mt_codec() );

	execute( TC_stat_bsc_sctp_disconnected() );

	execute( TC_silent_call_start_stop() );
	execute( TC_silent_call_active_conn() );
}


}
