summaryrefslogtreecommitdiffstats
path: root/msc/MSC_Tests.ttcn
blob: dc3ad1ea584643c80a93aca0c773e2286d831816 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
module MSC_Tests {

import from General_Types all;
import from Osmocom_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 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 GSUP_Emulation all;
import from GSUP_Types all;
import from IPA_Emulation all;

import from BSSAP_Types all;
import from BSSAP_Adapter all;
import from BSSAP_CodecPort all;
import from BSSMAP_Templates all;
import from BSSMAP_Emulation all;
import from BSC_ConnectionHandler all;

import from MobileL3_Types all;
import from MobileL3_CommonIE_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 SS_Types all;
import from SS_Templates all;
import from USSD_Helpers all;

const integer NUM_BSC := 2;
type record of BSSAP_Configuration BSSAP_Configurations;

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

	var BSSAP_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;

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

	/* 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;
}

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;

	/* local parameters of emulated HLR */
	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;

	charstring mp_msc_mncc := "/tmp/mncc";

	integer mp_msc_smpp_port := 2775;
	charstring mp_smpp_system_id := "msc_tester";
	charstring mp_smpp_password := "osmocom1";

	BSSAP_Configurations mp_bssap_cfg := {
		{
			sccp_service_type := "mtp3_itu",
			sctp_addr := { 23905, "127.0.0.1", 2905, "127.0.0.1" },
			own_pc := 185,
			own_ssn := 254,
			peer_pc := 187,
			peer_ssn := 254,
			sio := '83'O,
			rctx := 0
		},
		{
			sccp_service_type := "mtp3_itu",
			sctp_addr := { 23906, "127.0.0.1", 2905, "127.0.0.1" },
			own_pc := 186,
			own_ssn := 254,
			peer_pc := 187,
			peer_ssn := 254,
			sio := '83'O,
			rctx := 1
		}
	};
}

/* 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");
		self.stop;
	}
}

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, "", -1));
}


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
	}

	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 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(t_ASP_IPA_EVT_UD(ASP_IPA_EVENT_UP)) { }
		[] T.timeout {
			setverdict(fail, "No connection to GSUP Port");
			self.stop
		}
	}
}

function f_init(integer num_bsc := 1) runs on MTC_CT {

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

	if (num_bsc > NUM_BSC) {
		setverdict(fail, "excess number of BSC instances requested");
	}

	for (var integer i := 0; i < num_bsc; i := i + 1) {
		if (isbound(mp_bssap_cfg[i])) {
			f_bssap_init(g_bssap[i], mp_bssap_cfg[i], "MSC_Test_" & int2str(i), BSC_BssmapOps);
			f_bssap_start(g_bssap[i]);
		} else {
			setverdict(fail, "missing BSSAP configuration");
		}
	}

	f_ipa_ctrl_start(mp_msc_ip, mp_msc_ctrl_port);
	f_init_mncc("MSC_Test");
	f_init_mgcp("MSC_Test");
	f_init_gsup("MSC_Test");
	f_init_smpp("MSC_Test");

	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, "network", "encryption a5 0");
}

/* 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_bssap_init(g_bssap[0], mp_bssap_cfg[0], "MSC_Test", omit);
	connect(g_bssap[0].vc_SCCP:SCCP_SP_PORT, self:BSSAP_DIRECT);

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

template PDU_BSSAP ts_BSSAP_BSSMAP := {
	discriminator := '0'B,
	spare := '0000000'B,
	dlci := omit,
	lengthIndicator := 0,	/* overwritten by codec */
	pdu := ?
}

template PDU_BSSAP tr_BSSAP_BSSMAP := {
	discriminator := '0'B,
	spare := '0000000'B,
	dlci := omit,
	lengthIndicator := ?,
	pdu := {
		bssmap := ?
	}
}


type integer BssmapCause;

template (value) BSSMAP_IE_Cause ts_BSSMAP_IE_Cause(BssmapCause val) := {
	elementIdentifier := '04'O,
	lengthIndicator := 0,
	causeValue := int2bit(val, 7),
	extensionCauseValue := '0'B,
	spare1 := omit
}

template (value) PDU_BSSAP ts_BSSMAP_Reset(BssmapCause cause) modifies ts_BSSAP_BSSMAP := {
	pdu := {
		bssmap := {
			reset := {
				messageType := '30'O,
				cause := ts_BSSMAP_IE_Cause(cause),
				a_InterfaceSelectorForReset := omit
			}
		}
	}
}

template (value) PDU_BSSAP ts_BSSMAP_ResetAck modifies ts_BSSAP_BSSMAP := {
	pdu := {
		bssmap := {
			resetAck := {
				messageType := '31'O,
				a_InterfaceSelectorForReset := omit
			}
		}
	}
}

template PDU_BSSAP tr_BSSMAP_ResetAck modifies tr_BSSAP_BSSMAP := {
	pdu := {
		bssmap := {
			resetAck := {
				messageType := '31'O,
				a_InterfaceSelectorForReset := *
			}
		}
	}
}

template BSSMAP_IE_CellIdentifier ts_BSSMAP_IE_CellID := {
	elementIdentifier := '05'O,
	lengthIndicator := 0,
	cellIdentifierDiscriminator := '0000'B,
	spare1_4 := '0000'B,
	cellIdentification := ?
}

type uint16_t BssmapLAC;
type uint16_t BssmapCI;

/*
template BSSMAP_IE_CellIdentifier ts_CellId_CGI(mcc, mnc, lac, ci)
modifies ts_BSSMAP_IE_CellID := {
	cellIdentification := {
		cI_LAC_CGI := {
			mnc_mcc := FIXME,
			lac := int2oct(lac, 2),
			ci := int2oct(ci, 2)
		}
	}
}
*/

template BSSMAP_IE_CellIdentifier ts_CellID_LAC_CI(BssmapLAC lac, BssmapCI ci)
modifies ts_BSSMAP_IE_CellID := {
	cellIdentification := {
		cI_LAC_CI := {
			lac := int2oct(lac, 2),
			ci := int2oct(ci, 2)
		}
	}
}

template BSSMAP_IE_CellIdentifier ts_CellId_CI(BssmapCI ci)
modifies ts_BSSMAP_IE_CellID := {
	cellIdentification := {
		cI_CI := int2oct(ci, 2)
	}
}

template BSSMAP_IE_CellIdentifier ts_CellId_none
modifies ts_BSSMAP_IE_CellID := {
	cellIdentification := {
		cI_noCell := ''O
	}
}


template BSSMAP_IE_Layer3Information ts_BSSMAP_IE_L3Info(octetstring l3info) := {
	elementIdentifier := '17'O,
	lengthIndicator := 0,
	layer3info := l3info
}

template PDU_BSSAP ts_BSSMAP_ComplL3(BSSMAP_IE_CellIdentifier cell_id, octetstring l3_info)
modifies ts_BSSAP_BSSMAP := {
	pdu := {
		bssmap := {
			completeLayer3Information := {
				messageType := '57'O,
				cellIdentifier := cell_id,
				layer3Information := ts_BSSMAP_IE_L3Info(l3_info),
				chosenChannel := omit,
				lSAIdentifier := omit,
				aPDU := omit,
				codecList := omit,
				redirectAttemptFlag := omit,
				sendSequenceNumber := omit,
				iMSI := omit
			}
		}
	}
}

template PDU_BSSAP ts_BSSMAP_HandoReq(BssmapCause cause, BSSMAP_IE_CellIdentifierList cid_list)
modifies ts_BSSAP_BSSMAP := {
	pdu := {
		bssmap := {
			handoverRequired := {
				messageType := '11'O,
				cause := ts_BSSMAP_IE_Cause(cause),
				responseRequest := omit,
				cellIdentifierList := cid_list,
				circuitPoolList := omit,
				currentChannelType1 := omit,
				speechVersion := omit,
				queueingIndicator := omit,
				oldToNewBSSInfo := omit,
				sourceToTargetRNCTransparentInfo := omit,
				sourceToTargetRNCTransparentInfoCDMA := omit,
				gERANClassmark := omit,
				talkerPriority := omit,
				speechCodec := omit,
				cSG_Identifier := omit
			}
		}
	}
}

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) runs on MTC_CT return BSC_ConnHdlrPars {
	var BSC_ConnHdlrNetworkPars net_pars := {
		kc_support := '0A'O,	/* A5/1 and A5/3 enabled */
		expect_tmsi := true,
		expect_auth := false,
		expect_ciph := false
	};
	var BSC_ConnHdlrPars pars := {
		sccp_addr_own := g_bssap[0].sccp_addr_own,
		sccp_addr_peer := g_bssap[0].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,
		net := net_pars,
		send_early_cm := true
	};
	return 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;
	var charstring id := testcasename();

	vc_conn := BSC_ConnHdlr.create(id);
	/* BSSMAP part / A interface */
	connect(vc_conn:BSSAP, g_bssap[0].vc_BSSMAP:CLIENT);
	connect(vc_conn:BSSAP_PROC, g_bssap[0].vc_BSSMAP: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 */
	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);

	/* 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));
	return vc_conn;
}

function f_start_handler(void_fn fn, integer imsi_suffix) runs on MTC_CT return BSC_ConnHdlr {
	return f_start_handler_with_pars(fn, f_init_pars(imsi_suffix));
}

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 */
private 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_bssap_compl_l3(l3_lu);
	GSUP.receive(tr_GSUP_UL_REQ(g_pars.imsi));
	GSUP.send(ts_GSUP_UL_ERR(g_pars.imsi, 23));
	alt {
		[] BSSAP.receive(tr_PDU_DTAP_MT(tr_ML3_MT_LU_Rej(int2oct(23,1)))) {
			f_expect_clear();
			}
		[] BSSAP.receive(tr_PDU_DTAP_MT(tr_ML3_MT_LU_Acc)) {
			setverdict(fail, "Expecting LU REJ, but got ACCEPT");
			self.stop;
		}
	}
	f_expect_clear();
}
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);
	vc_conn.done;
}

/* Do LU by IMSI, timeout on GSUP */
private 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_bssap_compl_l3(l3_lu);
	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 */
		[] BSSAP.receive(tr_PDU_DTAP_MT(tr_ML3_MT_LU_Rej)) {
			f_expect_clear();
			}
		[] BSSAP.receive(tr_PDU_DTAP_MT(tr_ML3_MT_LU_Acc)) {
			setverdict(fail, "Expecting LU REJ, but got ACCEPT");
			self.stop;
		}
	}
	f_expect_clear();
}
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);
	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;
}


/* Send CM SERVICE REQ for IMSI that has never performed LU before */
private 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_bssap_compl_l3(l3_info);

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

	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);
	vc_conn.done;
}

private 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('12345'H, 0));
	cpars.bss_rtp_port := 1110;
	cpars.mgcp_connection_id_bss := '22222'H;
	cpars.mgcp_connection_id_mss := '33333'H;
	cpars.mgcp_ep := "rtpbridge/1@mgw";

	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;
}

/* Test LU (with authentication enabled), where HLR times out sending SAI response */
private 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_bssap_compl_l3(l3_lu);

	/* Send Early Classmark, just for the fun of it */
	BSSAP.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. */

	BSSAP.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);
	vc_conn.done;
}

/* Test LU (with authentication enabled), where HLR rejects sending SAI error */
private 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_bssap_compl_l3(l3_lu);

	/* Send Early Classmark, just for the fun of it */
	BSSAP.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));

	BSSAP.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);
	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_bssap_compl_l3(l3_lu);

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

	f_sleep(1.0);
	/* send clear request in the middle of the LU */
	BSSAP.send(ts_BSSMAP_ClearRequest(0));
	alt {
	[] BSSAP.receive(tr_PDU_DTAP_MT(tr_ML3_MT_LU_Rej)) { repeat; }
	[] BSSAP.receive(tr_BSSMAP_ClearCommand) {}
	}
	BSSAP.send(ts_BSSMAP_ClearComplete);
	alt {
	/* See https://osmocom.org/issues/2862 */
	[] BSSAP.receive(tr_BSSMAP_ClearCommand) {
			setverdict(fail, "Got a second Clear Command, only one expected");
			repeat;
		}
	[] BSSAP.receive(BSSAP_Conn_Prim: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 LU but BSC will send a clear request in the middle */
private 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_bssap_compl_l3(l3_lu);

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

	f_sleep(1.0);
	/* send clear request in the middle of the LU */
	BSSAP.send(BSSAP_Conn_Prim:MSC_CONN_PRIM_DISC_REQ);
	setverdict(pass);
}
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 */
private 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_bssap_compl_l3(l3_lu);

	/* Send Early Classmark, just for the fun of it */
	BSSAP.send(ts_BSSMAP_ClassmarkUpd(g_pars.cm2, g_pars.cm3));
	/* wait for LU reject, ignore any ID REQ */
	alt {
	[] BSSAP.receive(tr_PDU_DTAP_MT(tr_ML3_MT_LU_Rej)) { }
	[] BSSAP.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);
	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_bssap_compl_l3(l3_lu);

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

	/* Wait for + respond to ID REQ (IMSI) */
	BSSAP.receive(tr_PDU_DTAP_MT(tr_ML3_MT_MM_ID_Req('001'B)));
	BSSAP.send(ts_PDU_DTAP_MO(ts_ML3_MO_MM_ID_Rsp_IMSI(overlong_imsi))); /* test for OS#2864 */
	BSSAP.send(ts_PDU_DTAP_MO(ts_ML3_MO_MM_ID_Rsp_IMSI(g_pars.imsi)));

	/* 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 {
	[] BSSAP.receive(tr_PDU_DTAP_MT(tr_ML3_MT_LU_Acc)) {
		BSSAP.send(ts_PDU_DTAP_MO(ts_ML3_MO_TmsiRealloc_Cmpl));
		}
	[] BSSAP.receive(tr_PDU_DTAP_MT(tr_ML3_MT_LU_Rej)) {
		setverdict(fail, "Expected LU ACK, but received REJ");
		}
	}

	/* 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 IMSI DETACH (MI=IMSI) */
private function f_tc_imsi_detach_by_imsi(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);

	var MobileIdentityLV mi := valueof(ts_MI_IMSI_LV(g_pars.imsi));

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

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

	/* wait for normal teardown */
	f_expect_clear();
}
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);
	vc_conn.done;
}

/* Test IMSI DETACH (MI=TMSI) */
private 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_bssap_compl_l3(valueof(ts_ML3_MO_MM_IMSI_DET_Ind(mi)));

	/* Send Early Classmark, just for the fun of it? */
	BSSAP.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);
	vc_conn.done;
}

/* Test IMSI DETACH (MI=IMEI), which is illegal */
private 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_bssap_compl_l3(valueof(ts_ML3_MO_MM_IMSI_DET_Ind(mi)));

	/* Send Early Classmark, just for the fun of it? */
	BSSAP.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);
	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;
	cpars.mgcp_ep := "rtpbridge/1@mgw";

	f_mo_call(cpars);
}

/* establish an emergency call by IMEI, no SIM inserted (and hence no IMSI) */
private 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_bssap_compl_l3(l3_info);
	BSSAP.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);
	vc_conn.done;
}

/* establish an emergency call by IMSI, SIM inserted (and hence IMSI) */
private 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_bssap_compl_l3(l3_info);
	BSSAP.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_bssap_compl_l3(l3_info);
	BSSAP.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_bssap_compl_l3(l3_info);
	BSSAP.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_bssap_compl_l3(l3_info);
	BSSAP.receive(tr_PDU_DTAP_MT(tr_CM_SERV_REJ(int2oct(32,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_bssap_compl_l3(l3_lu);

	/* Send Early Classmark, just for the fun of it */
	BSSAP.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));

	BSSAP.receive(tr_PDU_DTAP_MT(tr_ML3_MT_MM_AUTH_REQ(vec.rand)));
	/* Send back wrong auth response */
	BSSAP.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 */
	BSSAP.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);
	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 */
	BSSAP.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 {
	[] BSSAP.receive(BSSAP_Conn_Prim:MSC_CONN_PRIM_DISC_IND) {}
	/* Expect LU REJECT with Cause == Illegal MS */
	[] BSSAP.receive(tr_PDU_DTAP_MT(?)) { repeat; }
	[] BSSAP.receive(BSSAP_Conn_Prim:MSC_CONN_PRIM_CONF_IND) { repeat; }
	[] as_clear_cmd_compl_disc();
	[] T.timeout {
		setverdict(fail, "Timeout waiting for ClearCommand or SCCP Release");
		self.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);

	var integer len := float2int(rnd() * 256.0);
	var octetstring payl := f_rnd_octstring(len);

	/* Send Complete L3 Info with empty L3 frame */
	BSSAP.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 */
	[] BSSAP.receive(BSSAP_Conn_Prim:MSC_CONN_PRIM_DISC_IND) {}
	[] BSSAP.receive(tr_PDU_DTAP_MT(?)) { repeat; }
	[] BSSAP.receive(BSSAP_Conn_Prim:MSC_CONN_PRIM_CONF_IND) { repeat; }
	[] as_clear_cmd_compl_disc();
	[] T.timeout {
		setverdict(fail, "Timeout waiting for ClearCommand or SCCP Release");
		self.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 */
private 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 */
private function f_tc_mo_setup_and_nothing(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_establish_fully();
	f_create_mncc_expect(hex2str(cpars.called_party));
	f_create_mgcp_expect(ExpectCriteria:{omit,omit,omit});

	BSSAP.send(ts_PDU_DTAP_MO(ts_ML3_MO_CC_SETUP(cpars.transaction_id, cpars.called_party)));

	f_expect_clear(30.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 */
private 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();

	f_establish_fully();
	f_create_mncc_expect(hex2str(cpars.called_party));
	f_create_mgcp_expect(ExpectCriteria:{omit,omit,omit});

	BSSAP.send(ts_PDU_DTAP_MO(ts_ML3_MO_CC_SETUP(cpars.transaction_id, cpars.called_party)));
	MNCC.receive(tr_MNCC_SETUP_ind(?, tr_MNCC_number(hex2str(cpars.called_party)))) -> value mncc;
	cpars.mncc_callref := mncc.u.signal.callref;
	MNCC.send(ts_MNCC_CALL_PROC_req(cpars.mncc_callref, cpars.mncc_bearer_cap));
	BSSAP.receive(tr_PDU_DTAP_MT(tr_ML3_MT_CC_CALL_PROC(cpars.transaction_id)));

	MGCP.receive(tr_CRCX) -> value mgcp_cmd;
	cpars.mgcp_call_id := f_MgcpCmd_extract_call_id(mgcp_cmd);
	cpars.mgcp_ep := mgcp_cmd.line.ep;
	/* never respond to this */

	/* When the connection with the MGW fails, the MSC will first request
	 * a release via call control. We will answer this request normally. */
	BSSAP.receive(tr_PDU_DTAP_MT(tr_ML3_MT_CC_RELEASE(cpars.transaction_id)));
	BSSAP.send(ts_PDU_DTAP_MO(ts_ML3_MO_CC_REL_COMPL(cpars.transaction_id)));

	f_expect_clear(30.0);
}
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 */
private 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));
	var MNCC_PDU mncc;
	var MgcpCommand mgcp_cmd;

	f_perform_lu();

	f_establish_fully();
	f_create_mncc_expect(hex2str(cpars.called_party));
	f_create_mgcp_expect(ExpectCriteria:{omit,omit,omit});

	BSSAP.send(ts_PDU_DTAP_MO(ts_ML3_MO_CC_SETUP(cpars.transaction_id, cpars.called_party)));
	MNCC.receive(tr_MNCC_SETUP_ind(?, tr_MNCC_number(hex2str(cpars.called_party)))) -> value mncc;
	cpars.mncc_callref := mncc.u.signal.callref;
	MNCC.send(ts_MNCC_CALL_PROC_req(cpars.mncc_callref, cpars.mncc_bearer_cap));
	BSSAP.receive(tr_PDU_DTAP_MT(tr_ML3_MT_CC_CALL_PROC(cpars.transaction_id)));

	MGCP.receive(tr_CRCX) -> value 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;
	}

	cpars.mgcp_call_id := f_MgcpCmd_extract_call_id(mgcp_cmd);

	/* 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"); self.stop; }
	[] BSSAP.receive(tr_PDU_DTAP_MT(tr_ML3_MT_CC_RELEASE(cpars.transaction_id))) {
		BSSAP.send(ts_PDU_DTAP_MO(ts_ML3_MO_CC_REL_COMPL(cpars.transaction_id)));
		repeat;
		}
	[] MNCC.receive { repeat; }
	[] GSUP.receive { repeat; }
	/* Note: As we did not respond properly to the CRCX from the MSC we
	 * expect the MSC to omit any further MGCP operation (At least in the
	 * the current implementation, there is no recovery mechanism implemented
	 * and a DLCX can not be performed as the MSC does not know a specific
	 * endpoint yet. */
	[] MGCP.receive { setverdict(fail, "Unexpected MGCP message"); self.stop; }
	[] as_clear_cmd_compl_disc();
	}
}
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;
	var OCT4 tmsi;

	f_perform_lu();
	if (isvalue(g_pars.tmsi)) {
		tmsi := g_pars.tmsi;
	} else {
		tmsi := 'FFFFFFFF'O;
	}
	f_bssmap_register_imsi(g_pars.imsi, 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 */
	BSSAP.receive(tr_BSSMAP_Paging(g_pars.imsi));
	/* MS -> MSC: PAGING RESPONSE */
	f_establish_fully(EST_TYPE_PAG_RESP);

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

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

/* Test MT Call */
private 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 */
	BSSAP.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"); self.stop; }
	[] BSSAP.receive { repeat; }
	[] 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_clear_cmd_compl_disc();
	}
}
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 */
private function f_tc_mt_t310(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars, 200.0);
	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 */
	BSSAP.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);
	cpars.mgcp_ep := mgcp_cmd.line.ep;
	/* FIXME: Respond to CRCX */

	/* old libosmocore T310 default timeout is 180s. so let's wait 190 */
	timer T := 190.0;
	T.start;
	alt {
	[] T.timeout { setverdict(fail, "Timeout waiting for T310"); self.stop; }
	[] MNCC.receive(tr_MNCC_DISC_ind(cpars.mncc_callref)) {
		MNCC.send(ts_MNCC_REL_req(cpars.mncc_callref, valueof(ts_MNCC_cause(23))));
		}
	}
	BSSAP.receive(tr_PDU_DTAP_MT(tr_ML3_MT_CC_DISC(cpars.transaction_id)));
	BSSAP.receive(tr_PDU_DTAP_MT(tr_ML3_MT_CC_RELEASE(cpars.transaction_id)));
	/* FIXME: We're sending this with TIflag 0: allocated by sender, which is wrong */
	BSSAP.send(ts_PDU_DTAP_MO(ts_ML3_MO_CC_REL_COMPL(cpars.transaction_id)));

	alt {
	[] 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;
		}
	[] as_clear_cmd_compl_disc();
	}
}
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 */
private 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));
	cpars.bss_rtp_port := 1110;
	cpars.mgcp_connection_id_bss := '22222'H;
	cpars.mgcp_connection_id_mss := '33333'H;

	/* 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");
		self.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_bssap_compl_l3(l3_info);
	alt {
	[] BSSAP.receive(tr_PDU_DTAP_MT(tr_CM_SERV_REJ)) { }
	[] BSSAP.receive {
		setverdict(fail, "Received unexpected BSSAP instead of CM SERV REJ");
		self.stop;
		}
	}
	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);
	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_bssap_compl_l3(l3_lu);
	if (pars.send_early_cm) {
		BSSAP.send(ts_BSSMAP_ClassmarkUpd(g_pars.cm2, g_pars.cm3));
	} else {
		pars.cm1.esind := '0'B;
	}
	f_mm_auth();
	alt {
	[] BSSAP.receive(tr_PDU_DTAP_MT(tr_ML3_MT_LU_Rej)) {
		f_expect_clear();
		}
	[] BSSAP.receive(tr_BSSMAP_CipherModeCmd(?,?)) {
		setverdict(fail, "CipherModeCommand despite no A5 intersection");
		self.stop;
		}
	[] BSSAP.receive {
		setverdict(fail, "Unknown/unexpected BSSAP received");
		self.stop;
		}
	}
	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);
	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);
	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);
	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_bssap_compl_l3(l3_lu);
	BSSAP.send(ts_BSSMAP_ClassmarkUpd(g_pars.cm2, g_pars.cm3));
	f_mm_auth();
	alt {
	[] BSSAP.receive(tr_PDU_DTAP_MT(tr_ML3_MT_LU_Rej)) {
		f_expect_clear();
		}
	[] BSSAP.receive(tr_BSSMAP_CipherModeCmd(?,?)) {
		setverdict(fail, "CipherModeCommand despite no A5 intersection");
		self.stop;
		}
	[] BSSAP.receive {
		setverdict(fail, "Unknown/unexpected BSSAP received");
		self.stop;
		}
	}
	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);
	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) */
private function f_tc_lu_and_mt_call(charstring id, BSC_ConnHdlrPars pars) runs on BSC_ConnHdlr {
	f_init_handler(pars);
	//FIXME: odd digits var CallParameters cpars := valueof(t_CallParams('12345'H, 0));
	var CallParameters cpars := valueof(t_CallParams('123456'H, 0));
	cpars.bss_rtp_port := 1110;
	cpars.mgcp_connection_id_bss := '10004'H;
	cpars.mgcp_connection_id_mss := '10005'H;

	/* Note: This is an optional parameter. When the call-agent (MSC) does
	 * supply a full endpoint name this setting will be overwritten. */
	cpars.mgcp_ep := "rtpbridge/1@mgw";

	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;
}

/* 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));
	cpars.bss_rtp_port := 1110;
	cpars.mgcp_connection_id_bss := '22222'H;
	cpars.mgcp_connection_id_mss := '33333'H;

	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();

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

	/* Send a BSSMAP reset */
	BSSAP_DIRECT.send(ts_BSSAP_UNITDATA_req(g_bssap[0].sccp_addr_peer, g_bssap[0].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].sccp_addr_peer, g_bssap[0].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!");
	}
	}	
}

/* Test MO Call with no response to RAN-side CRCX or DTAP Release */
private 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;

	f_perform_lu();

	f_establish_fully();
	f_create_mncc_expect(hex2str(cpars.called_party));
	f_create_mgcp_expect(ExpectCriteria:{omit,omit,omit});

	BSSAP.send(ts_PDU_DTAP_MO(ts_ML3_MO_CC_SETUP(cpars.transaction_id, cpars.called_party)));
	MNCC.receive(tr_MNCC_SETUP_ind(?, tr_MNCC_number(hex2str(cpars.called_party)))) -> value mncc;
	cpars.mncc_callref := mncc.u.signal.callref;
	MNCC.send(ts_MNCC_CALL_PROC_req(cpars.mncc_callref, cpars.mncc_bearer_cap));
	BSSAP.receive(tr_PDU_DTAP_MT(tr_ML3_MT_CC_CALL_PROC(cpars.transaction_id)));

	/* Drop CRCX */
	MGCP.receive(tr_CRCX) -> value mgcp_cmd;

	/* Drop DTAP Release */
	BSSAP.receive(tr_PDU_DTAP_MT(tr_ML3_MT_CC_RELEASE(cpars.transaction_id)));

	/* Drop resent DTAP Release */
	BSSAP.receive(tr_PDU_DTAP_MT(tr_ML3_MT_CC_RELEASE(cpars.transaction_id)));

	f_expect_clear(60.0);
}
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);
	//FIXME: odd digits var CallParameters cpars := valueof(t_CallParams('12345'H, 0));
	var CallParameters cpars := valueof(t_CallParams('123456'H, 0));
	cpars.bss_rtp_port := 1110;
	cpars.mgcp_connection_id_bss := '10004'H;
	cpars.mgcp_connection_id_mss := '10005'H;

	/* Note: This is an optional parameter. When the call-agent (MSC) does
	 * supply a full endpoint name this setting will be overwritten. */
	cpars.mgcp_ep := "rtpbridge/1@mgw";

	/* 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);
}

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

/* LU followed by MO SMS */
private 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 MTC_CT {
	f_vty_transceive(MSCVTY, "subscriber imsi "&imsi&" sms sender msisdn "&msisdn&" send "&text);
}

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

	f_init_handler(pars);

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

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

	/* FIXME: actually cause MSC to send a SMS via VTY or SMPP */

	/* MSC->BSC: expect PAGING from MSC */
	BSSAP.receive(tr_BSSMAP_Paging(g_pars.imsi));
	/* 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() 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);
	f_sleep(2.0);
	f_vty_sms_send(hex2str(pars.imsi), "2342", "Hello SMS");
	vc_conn.done;
}

/* mobile originated SMS from MS/BTS/BSC side to SMPP */
private 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();
	f_establish_fully(EST_TYPE_MO_SMS);

	f_mo_sms(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; }
	}

	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");
}

/* 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);
	self.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);
	self.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 */
	BSSAP.receive(tr_BSSMAP_Paging(g_pars.imsi));
	/* 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) */
	var OCT4 tmsi;
	if (isvalue(g_pars.tmsi)) {
		tmsi := g_pars.tmsi;
	} else {
		tmsi := 'FFFFFFFF'O;
	}
	f_bssmap_register_imsi(g_pars.imsi, 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);
}
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
 ***********************************************************************/

/* LU followed by MO USSD request */
private 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);

	/* 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 := 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#"
		)
	);

	/* 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 := 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"
		)
	);

	/* Request own number request */
	BSSAP.send(ts_PDU_DTAP_MO(ussd_req));
	alt {
	/* We expect RELEASE_COMPLETE message with the response */
	[] BSSAP.receive(tr_PDU_DTAP_MT(ussd_rsp)) {
		setverdict(pass);
		}
	[] BSSAP.receive {
		setverdict(fail, "Unknown/unexpected BSSAP received");
		self.stop;
		}
	}

	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 call and MO USSD request during this call */
private 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));
	cpars.mgcp_connection_id_bss := '10004'H;
	cpars.mgcp_connection_id_mss := '10005'H;
	cpars.mgcp_ep := "rtpbridge/1@mgw";
	cpars.bss_rtp_port := 1110;

	/* 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);

	/* 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 := f_USSD_FACILITY_IE_INVOKE(
			op_code := SS_OP_CODE_PROCESS_USS_REQ,
			ussd_string := "*#100#"
		)
	);

	/* 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 := f_USSD_FACILITY_IE_RETURN_RESULT(
			op_code := SS_OP_CODE_PROCESS_USS_REQ,
			ussd_string := "Your extension is " & hex2str(g_pars.msisdn) & "\r"
		)
	);

	/* Request own number request */
	BSSAP.send(ts_PDU_DTAP_MO(ussd_req));
	alt {
	/* We expect RELEASE_COMPLETE message with the response */
	[] BSSAP.receive(tr_PDU_DTAP_MT(ussd_rsp)) {
		setverdict(pass);
		}
	[] BSSAP.receive {
		setverdict(fail, "Unknown/unexpected BSSAP received");
		self.stop;
		}
	}

	/* 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;
}

/* 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
 */


control {
	execute( TC_cr_before_reset() );
	execute( TC_lu_imsi_noauth_tmsi() );
	execute( TC_lu_imsi_noauth_notmsi() );
	execute( TC_lu_imsi_reject() );
	execute( TC_lu_imsi_timeout_gsup() );
	execute( TC_lu_imsi_auth_tmsi() );
	execute( TC_cmserv_imsi_unknown() );
	execute( TC_lu_and_mo_call() );
	execute( TC_lu_auth_sai_timeout() );
	execute( TC_lu_auth_sai_err() );
	execute( TC_lu_clear_request() );
	execute( TC_lu_disconnect() );
	execute( TC_lu_by_imei() );
	execute( TC_lu_by_tmsi_noauth_unknown() );
	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_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_mo_sms() );
	execute( TC_lu_and_mt_sms() );
	execute( TC_smpp_mo_sms() );
	execute( TC_smpp_mt_sms() );

	execute( TC_lu_and_mo_ussd_single_request() );
	execute( TC_lu_and_mo_ussd_during_mt_call() );

	/* Run this last: at the time of writing this test crashes the MSC */
	execute( TC_lu_imsi_auth_tmsi_encr_3_1_log_msc_debug() );
}


}