summaryrefslogtreecommitdiffstats
path: root/sgsn/SGSN_Tests.ttcn
blob: 0112483f8cd4af298c6d5ba863d3fa347468c1df (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
module SGSN_Tests {

import from General_Types all;
import from Osmocom_Types all;
import from Native_Functions all;
import from NS_Types all;
import from NS_Emulation all;
import from BSSGP_Types all;
import from BSSGP_Emulation all;
import from Osmocom_Gb_Types all;

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

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

import from GTP_Emulation all;
import from GTP_Templates all;
import from GTP_CodecPort all;
import from GTPC_Types all;
import from GTPU_Types all;

import from LLC_Types all;
import from LLC_Templates all;

import from SNDCP_Types all;

import from TELNETasp_PortType all;
import from Osmocom_VTY_Functions all;

import from GSM_RR_Types all;

import from MobileL3_MM_Types all;


modulepar {
	/* IP/port on which we run our internal GSUP/HLR emulation */
	charstring mp_hlr_ip := "127.0.0.1";
	integer mp_hlr_port := 4222;
	charstring mp_ggsn_ip := "127.0.0.2";

	NSConfigurations mp_nsconfig := {
		{
			local_udp_port := 21010,
			local_ip := "127.0.0.1",
			remote_udp_port := 23000,
			remote_ip := "127.0.0.1",
			nsvci := 97,
			nsei := 96
		},
		{
			local_udp_port := 21011,
			local_ip := "127.0.0.1",
			remote_udp_port := 23000,
			remote_ip := "127.0.0.1",
			nsvci := 98,
			nsei := 97
		},
		{
			local_udp_port := 21012,
			local_ip := "127.0.0.1",
			remote_udp_port := 23000,
			remote_ip := "127.0.0.1",
			nsvci := 99,
			nsei := 98
		}
	};
};

type record GbInstance {
	NS_CT vc_NS,
	BSSGP_CT vc_BSSGP,
	BssgpConfig cfg
};

type record length(3) of GbInstance GbInstances;
type record length(3) of NSConfiguration NSConfigurations;
type record length(3) of BssgpCellId BssgpCellIds;

type component test_CT {
	var GbInstances g_gb;

	var GSUP_Emulation_CT vc_GSUP;
	var IPA_Emulation_CT vc_GSUP_IPA;
	/* only to get events from IPA underneath GSUP */
	port IPA_CTRL_PT GSUP_IPA_EVENT;

	var GTP_Emulation_CT vc_GTP;

	port TELNETasp_PT SGSNVTY;

	var boolean g_initialized := false;
	var boolean g_use_echo := false;
};

type component BSSGP_ConnHdlr extends BSSGP_Client_CT, GSUP_ConnHdlr, GTP_ConnHdlr {
	var BSSGP_ConnHdlrPars g_pars;
	timer g_Tguard;
	var LLC_Entities llc;
}

type record SGSN_ConnHdlrNetworkPars {
	boolean expect_ptmsi,
	boolean expect_auth,
	boolean expect_ciph
};

type record BSSGP_ConnHdlrPars {
	/* IMEI of the simulated ME */
	hexstring imei,
	/* IMSI of the simulated MS */
	hexstring imsi,
	/* MSISDN of the simulated MS (probably unused) */
	hexstring msisdn,
	/* P-TMSI allocated to the simulated MS */
	OCT4 p_tmsi optional,
	OCT3 p_tmsi_sig optional,
	/* TLLI of the simulated MS */
	OCT4 tlli,
	OCT4 tlli_old optional,
	RoutingAreaIdentificationV ra optional,
	BssgpCellIds bssgp_cell_id,
	AuthVector vec optional,
	SGSN_ConnHdlrNetworkPars net,
	float t_guard
};

private function f_cellid_to_RAI(in BssgpCellId cell_id) return RoutingAreaIdentificationV {
	var BcdMccMnc mcc_mnc := cell_id.ra_id.lai.mcc_mnc;

        var RoutingAreaIdentificationV ret := {
                mccDigit1 := mcc_mnc[0],
                mccDigit2 := mcc_mnc[1],
                mccDigit3 := mcc_mnc[2],
                mncDigit3 := mcc_mnc[5],
                mncDigit1 := mcc_mnc[3],
                mncDigit2 := mcc_mnc[4],
                lac := int2oct(cell_id.ra_id.lai.lac, 16),
                rac := int2oct(cell_id.ra_id.rac, 8)
        }
        return ret;
};

private function f_init_gb(inout GbInstance gb, charstring id, integer offset) runs on test_CT {
	gb.vc_NS := NS_CT.create(id & "-NS" & int2str(offset));
	gb.vc_BSSGP := BSSGP_CT.create(id & "-BSSGP" & int2str(offset));
	/* connect lower end of BSSGP emulation with NS upper port */
	connect(gb.vc_BSSGP:BSCP, gb.vc_NS:NS_SP);
	/* connect lower end of NS emulation to NS codec port (on top of IPL4) */
	map(gb.vc_NS:NSCP, system:NS_CODEC_PORT);

	gb.vc_NS.start(NSStart(mp_nsconfig[offset]));
	gb.vc_BSSGP.start(BssgpStart(gb.cfg));
}

private function f_init_gsup(charstring id) runs on test_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");
			mtc.stop;
		}
	}
}

private function f_init_gtp(charstring id) runs on test_CT {
	id := id & "-GTP";

	var GtpEmulationCfg gtp_cfg := {
		gtpc_bind_ip := mp_ggsn_ip,
		gtpc_bind_port := GTP1C_PORT,
		gtpu_bind_ip := mp_ggsn_ip,
		gtpu_bind_port := GTP1U_PORT,
		sgsn_role := false
	};

	vc_GTP := GTP_Emulation_CT.create(id);
	vc_GTP.start(GTP_Emulation.main(gtp_cfg));
}

private function f_init_vty() runs on test_CT {
	map(self:SGSNVTY, system:SGSNVTY);
	f_vty_set_prompts(SGSNVTY);
	f_vty_transceive(SGSNVTY, "enable");
	f_vty_transceive(SGSNVTY, "reset sgsn state");
	f_vty_config(SGSNVTY, "sgsn", "auth-policy remote");
}

private function f_vty_enable_echo_interval(boolean enable) runs on test_CT {
	if (enable) {
		f_vty_config(SGSNVTY, "sgsn", "ggsn 0 echo-interval 5");
	} else {
		f_vty_config(SGSNVTY, "sgsn", "ggsn 0 no echo-interval");
	}
}


function f_init(BcdMccMnc mcc_mnc := '26242F'H) runs on test_CT {
	if (g_initialized == true) {
		return;
	}
	g_initialized := true;
	g_gb[0].cfg := {
		nsei := 96,
		bvci := 196,
		cell_id := {
			ra_id := {
				lai := {
					mcc_mnc := mcc_mnc, lac := 13135},
					rac := 0
				},
			cell_id := 20960
		},
		sgsn_role := false
	};
	g_gb[1].cfg := {
		nsei := 97,
		bvci := 210,
		cell_id := {
			ra_id := {
				lai := {
					mcc_mnc := mcc_mnc, lac := 13200},
					rac := 0
				},
			cell_id := 20961
		},
		sgsn_role := false
	};
	g_gb[2].cfg := {
		nsei := 98,
		bvci := 220,
		cell_id := {
			ra_id := {
				lai := {
					mcc_mnc := mcc_mnc, lac := 13300},
					rac := 0
				},
			cell_id := 20962
		},
		sgsn_role := false
	};

	f_init_vty();
	f_init_gb(g_gb[0], "SGSN_Test-Gb0", 0);
	f_init_gb(g_gb[1], "SGSN_Test-Gb1", 1);
	f_init_gb(g_gb[2], "SGSN_Test-Gb2", 2);
	f_init_gsup("SGSN_Test");
	f_init_gtp("SGSN_Test");
	f_vty_enable_echo_interval(g_use_echo);
}

type function void_fn(charstring id) runs on BSSGP_ConnHdlr;

/* helper function to create, connect and start a BSSGP_ConnHdlr component */
function f_start_handler(void_fn fn, charstring id, GbInstances gb, integer imsi_suffix,
			 float t_guard := 30.0)
runs on test_CT return BSSGP_ConnHdlr {
	var BSSGP_ConnHdlr vc_conn;
	var SGSN_ConnHdlrNetworkPars net_pars := {
		expect_ptmsi := true,
		expect_auth := true,
		expect_ciph := false
	};
	var BSSGP_ConnHdlrPars pars := {
		imei := f_gen_imei(imsi_suffix),
		imsi := f_gen_imsi(imsi_suffix),
		msisdn := f_gen_msisdn(imsi_suffix),
		p_tmsi := omit,
		p_tmsi_sig := omit,
		tlli := f_gprs_tlli_random(),
		tlli_old := omit,
		ra := omit,
		bssgp_cell_id := { gb[0].cfg.cell_id, gb[1].cfg.cell_id, gb[2].cfg.cell_id },
		vec := omit,
		net := net_pars,
		t_guard := t_guard
	};

	vc_conn := BSSGP_ConnHdlr.create(id);
	connect(vc_conn:BSSGP[0], gb[0].vc_BSSGP:BSSGP_SP);
	connect(vc_conn:BSSGP_PROC[0], gb[0].vc_BSSGP:BSSGP_PROC);
	connect(vc_conn:BSSGP[1], gb[1].vc_BSSGP:BSSGP_SP);
	connect(vc_conn:BSSGP_PROC[1], gb[1].vc_BSSGP:BSSGP_PROC);
	connect(vc_conn:BSSGP[2], gb[2].vc_BSSGP:BSSGP_SP);
	connect(vc_conn:BSSGP_PROC[2], gb[2].vc_BSSGP:BSSGP_PROC);

	connect(vc_conn:GSUP, vc_GSUP:GSUP_CLIENT);
	connect(vc_conn:GSUP_PROC, vc_GSUP:GSUP_PROC);

	connect(vc_conn:GTP, vc_GTP:CLIENT);
	connect(vc_conn:GTP_PROC, vc_GTP:CLIENT_PROC);

	vc_conn.start(f_handler_init(fn, id, pars));
	return vc_conn;
}

private altstep as_Tguard() runs on BSSGP_ConnHdlr {
	[] g_Tguard.timeout {
		setverdict(fail, "Tguard timeout");
		mtc.stop;
	}
}

/* first function called in every ConnHdlr */
private function f_handler_init(void_fn fn, charstring id, BSSGP_ConnHdlrPars pars)
runs on BSSGP_ConnHdlr {
	/* do some common stuff like setting up g_pars */
	g_pars := pars;

	llc := f_llc_create(false);

	/* register with BSSGP core */
	f_bssgp_client_register(g_pars.imsi, g_pars.tlli, g_pars.bssgp_cell_id[0]);
	/* tell GSUP dispatcher to send this IMSI to us */
	f_create_gsup_expect(hex2str(g_pars.imsi));
	/* tell GTP dispatcher to send this IMSI to us */
	f_gtp_register_imsi(g_pars.imsi);

	g_Tguard.start(pars.t_guard);
	activate(as_Tguard());

	/* call the user-supplied test case function */
	fn.apply(id);
	f_bssgp_client_unregister(g_pars.imsi);
}

/* TODO:
   * Detach without Attach
   * SM procedures without attach / RAU
   * ATTACH / RAU
   ** with / without authentication
   ** with / without P-TMSI allocation
   * re-transmissions of LLC frames
   * PDP Context activation
   ** with different GGSN config in SGSN VTY
   ** with different PDP context type (v4/v6/v46)
   ** timeout from GGSN
   ** multiple / secondary PDP context
 */

testcase TC_wait_ns_up() runs on test_CT {
	f_init();
	f_sleep(20.0);
}

function f_send_l3_gmm_llc(template PDU_L3_MS_SGSN l3_mo, integer gb_index := 0) runs on BSSGP_ConnHdlr {
	var octetstring l3_enc := enc_PDU_L3_MS_SGSN(valueof(l3_mo));
	var BIT4 sapi := f_llc_sapi_by_l3_mo(valueof(l3_mo));
	var integer n_u := f_llc_get_n_u_tx(llc[bit2int(sapi)]);
	var octetstring llc_enc := enc_PDU_LLC(valueof(ts_LLC_UI(l3_enc, sapi, '0'B, n_u)));
	BSSGP[gb_index].send(ts_BSSGP_UL_UD(g_pars.tlli, g_pars.bssgp_cell_id[gb_index], llc_enc));
}

altstep as_mm_identity() runs on BSSGP_ConnHdlr {
	var MobileL3_CommonIE_Types.MobileIdentityLV mi;
	[] BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_ID_REQ('001'B))) {
		mi := valueof(ts_MI_IMSI_LV(g_pars.imsi));
		f_send_l3_gmm_llc(ts_GMM_ID_RESP(mi));
		repeat;
	}
	[] BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_ID_REQ('010'B))) {
		mi := valueof(ts_MI_IMEI_LV(g_pars.imei));
		f_send_l3_gmm_llc(ts_GMM_ID_RESP(mi));
		repeat;
	}
}

/* perform GMM authentication (if expected).
 * Note, for umts_aka_challenge to work, the revisionLevelIndicatior needs to
 * be 1 to mark R99 capability, in the GMM Attach Request, see f_gmm_attach(). */
function f_gmm_auth (boolean umts_aka_challenge := false, boolean force_gsm_sres := false) runs on BSSGP_ConnHdlr {
	var BssgpDecoded bd;
	var PDU_L3_MS_SGSN l3_mo;
	var PDU_L3_SGSN_MS l3_mt;
	var default di := activate(as_mm_identity());
	if (g_pars.net.expect_auth) {
		var GSUP_IE auth_tuple;
		var template AuthenticationParameterAUTNTLV autn;

		if (umts_aka_challenge) {
			g_pars.vec := f_gen_auth_vec_3g();
			autn := {
				elementIdentifier := '28'O,
				lengthIndicator := lengthof(g_pars.vec.autn),
				autnValue := g_pars.vec.autn
				};

			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));
			log("GSUP sends 2G and 3G auth tuples", auth_tuple);
		} else {
			g_pars.vec := f_gen_auth_vec_2g();
			autn := omit;
			auth_tuple := valueof(ts_GSUP_IE_AuthTuple2G(g_pars.vec.rand,
								     g_pars.vec.sres,
								     g_pars.vec.kc));
			log("GSUP sends only 2G auth tuple", auth_tuple);
		}
		GSUP.receive(tr_GSUP_SAI_REQ(g_pars.imsi));
		GSUP.send(ts_GSUP_SAI_RES(g_pars.imsi, auth_tuple));

		var template PDU_L3_SGSN_MS auth_ciph_req := tr_GMM_AUTH_REQ(g_pars.vec.rand);
		auth_ciph_req.msgs.gprs_mm.authenticationAndCipheringRequest.authenticationParameterAUTN := autn;
		BSSGP[0].receive(tr_BD_L3_MT(auth_ciph_req)) -> value bd;
		l3_mt := bd.l3_mt;
		var BIT4 ac_ref := l3_mt.msgs.gprs_mm.authenticationAndCipheringRequest.acReferenceNumber.valueField;
		var template PDU_L3_MS_SGSN auth_ciph_resp := ts_GMM_AUTH_RESP_2G(ac_ref, g_pars.vec.sres);

		if (umts_aka_challenge and not force_gsm_sres) {
			/* set UMTS response instead */
			auth_ciph_resp.msgs.gprs_mm.authenticationAndCipheringResponse.authenticationParResp := {
				valueField := substr(g_pars.vec.res, 0, 4)
			};
			auth_ciph_resp.msgs.gprs_mm.authenticationAndCipheringResponse.authenticationRespParExt := {
				elementIdentifier := '21'O,
				lengthIndicator := lengthof(g_pars.vec.res) - 4,
				valueField := substr(g_pars.vec.res, 4, lengthof(g_pars.vec.res) - 4)
			};
		}

		l3_mo := valueof(auth_ciph_resp);
		if (ispresent(l3_mt.msgs.gprs_mm.authenticationAndCipheringRequest.imeisvRequest) and
		    l3_mt.msgs.gprs_mm.authenticationAndCipheringRequest.imeisvRequest.valueField == '001'B) {
			l3_mo.msgs.gprs_mm.authenticationAndCipheringResponse.imeisv :=
						valueof(ts_MI_IMEISV_TLV(g_pars.imei & '0'H));
		}
		f_send_l3_gmm_llc(l3_mo);
	} else {
		/* wait for identity procedure */
		f_sleep(1.0);
	}

	deactivate(di);
}

function f_upd_ptmsi_and_tlli(OCT4 p_tmsi, integer bssgp_index := 0) runs on BSSGP_ConnHdlr {
	g_pars.p_tmsi := p_tmsi;
	/* update TLLI */
	g_pars.tlli_old := g_pars.tlli;
	g_pars.tlli := g_pars.p_tmsi or4b 'c0000000'O;
	f_bssgp_client_llgmm_assign(g_pars.tlli_old, g_pars.tlli, BSSGP_PROC[bssgp_index]);
}

function f_process_attach_accept(PDU_GMM_AttachAccept aa) runs on BSSGP_ConnHdlr {
	/* mandatory IE */
	var hexstring aa_plmn := f_RAI_to_plmn_hexstr(aa.routingAreaIdentification);
	if (not (g_pars.bssgp_cell_id[0].ra_id.lai.mcc_mnc == aa_plmn)) {
		  setverdict(fail, "mismatching PLMN in Attach Accept: " & hex2str(aa_plmn)
				   & "; expected " & hex2str(g_pars.bssgp_cell_id[0].ra_id.lai.mcc_mnc));
		  mtc.stop;
	}
	g_pars.ra := aa.routingAreaIdentification;
	if (ispresent(aa.allocatedPTMSI)) {
		if (not g_pars.net.expect_ptmsi) {
			setverdict(fail, "unexpected P-TMSI allocation");
			mtc.stop;
		}
		f_upd_ptmsi_and_tlli(aa.allocatedPTMSI.mobileIdentityLV.mobileIdentityV.oddEvenInd_identity.tmsi_ptmsi.octets);
	}
	if (ispresent(aa.msIdentity)) {
		setverdict(fail, "unexpected TMSI allocation in non-combined attach");
		mtc.stop;
	}
	/* P-TMSI.sig */
	if (ispresent(aa.ptmsiSignature)) {
		g_pars.p_tmsi_sig := aa.ptmsiSignature.valueField;
	}
	/* updateTimer */
	// aa.readyTimer
	/* T3302, T3319, T3323, T3312_ext, T3324 */
}

function f_process_rau_accept(PDU_GMM_RoutingAreaUpdateAccept ra, integer bssgp_index := 0) runs on BSSGP_ConnHdlr {
	/* mandatory IE */
	g_pars.ra := ra.routingAreaId;
	if (ispresent(ra.allocatedPTMSI)) {
		if (not g_pars.net.expect_ptmsi) {
			setverdict(fail, "unexpected P-TMSI allocation");
			mtc.stop;
		}
		f_upd_ptmsi_and_tlli(ra.allocatedPTMSI.mobileIdentityLV.mobileIdentityV.oddEvenInd_identity.tmsi_ptmsi.octets, bssgp_index);
	}
	if (ispresent(ra.msIdentity)) {
		setverdict(fail, "unexpected TMSI allocation in non-combined attach");
		mtc.stop;
	}
	/* P-TMSI.sig */
	if (ispresent(ra.ptmsiSignature)) {
		g_pars.p_tmsi_sig := ra.ptmsiSignature.valueField;
	}
	/* updateTimer */
	// aa.readyTimer
	/* T3302, T3319, T3323, T3312_ext, T3324 */
}


function f_random_RAI(HEX0_3n mcc := '262'H, HEX0_3n mnc := '42'H) return RoutingAreaIdentificationV {
	return f_RAI(mcc, mnc, f_rnd_octstring(2), f_rnd_octstring(1));
}

/* return a MobileIdentityLV: P-TMSI if we have one, IMSI otherwise */
private function f_mi_get_lv() runs on BSSGP_ConnHdlr return MobileL3_CommonIE_Types.MobileIdentityLV {
	if (ispresent(g_pars.p_tmsi)) {
		return valueof(ts_MI_TMSI_LV(g_pars.p_tmsi));
	} else {
		return valueof(ts_MI_IMSI_LV(g_pars.imsi));
	}
}

private function f_gmm_gsup_lu_isd() runs on BSSGP_ConnHdlr {
	var GSUP_PDU gsup;
	/* Expect MSC to perform LU with HLR */
	GSUP.receive(tr_GSUP_UL_REQ(g_pars.imsi));
	gsup := valueof(ts_GSUP_ISD_REQ(g_pars.imsi, g_pars.msisdn));
	gsup.ies := gsup.ies & { valueof(ts_GSUP_IE_PdpInfo(char2oct("*"), '0121'O, ''O)) };
	GSUP.send(gsup);
	GSUP.receive(tr_GSUP_ISD_RES(g_pars.imsi));
	GSUP.send(ts_GSUP_UL_RES(g_pars.imsi));
}

private function f_gmm_attach(boolean umts_aka_challenge, boolean force_gsm_sres) runs on BSSGP_ConnHdlr {
	var BssgpDecoded bd;
	var RoutingAreaIdentificationV old_ra := f_random_RAI();
	var template PDU_L3_MS_SGSN attach_req := ts_GMM_ATTACH_REQ(f_mi_get_lv(), old_ra, false, false, omit, omit);

	/* indicate R99 capability of the MS to enable UMTS AKA in presence of
	 * 3G auth vectors */
	attach_req.msgs.gprs_mm.attachRequest.msNetworkCapability.msNetworkCapabilityV.revisionLevelIndicatior := '1'B;
	/* The thing is, if the solSACapability is 'omit', then the
	 * revisionLevelIndicatior is at the wrong place! */
	attach_req.msgs.gprs_mm.attachRequest.msNetworkCapability.msNetworkCapabilityV.solSACapability := '0'B;

	f_send_l3_gmm_llc(attach_req);
	f_gmm_auth(umts_aka_challenge, force_gsm_sres);
	/* Expect SGSN to perform LU with HLR */
	f_gmm_gsup_lu_isd();

	BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_ATTACH_ACCEPT('001'B, ?, ?))) -> value bd {
		f_process_attach_accept(bd.l3_mt.msgs.gprs_mm.attachAccept);
	}
	/* FIXME: Extract P-TMSI, if any. Only send Complete if necessary */
	f_send_l3_gmm_llc(ts_GMM_ATTACH_COMPL);
}

private function f_TC_attach(charstring id) runs on BSSGP_ConnHdlr {
	f_gmm_attach(false, false);
	setverdict(pass);
}

testcase TC_attach() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_TC_attach), testcasename(), g_gb, 1);
	vc_conn.done;
}

testcase TC_attach_mnc3() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init('023042'H);
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_TC_attach), testcasename(), g_gb, 1001);
	vc_conn.done;
}

private function f_TC_attach_umts_aka_umts_res(charstring id) runs on BSSGP_ConnHdlr {
	f_gmm_attach(true, false);
	setverdict(pass);
}
testcase TC_attach_umts_aka_umts_res() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_TC_attach_umts_aka_umts_res), testcasename(), g_gb, 1002);
	vc_conn.done;
}

private function f_TC_attach_umts_aka_gsm_sres(charstring id) runs on BSSGP_ConnHdlr {
	f_gmm_attach(true, true);
	setverdict(pass);
}
testcase TC_attach_umts_aka_gsm_sres() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_TC_attach_umts_aka_gsm_sres), testcasename(), g_gb, 1003);
	vc_conn.done;
}

/* MS never responds to ID REQ, expect ATTACH REJECT */
private function f_TC_attach_auth_id_timeout(charstring id) runs on BSSGP_ConnHdlr {
	var RoutingAreaIdentificationV old_ra := f_random_RAI();

	f_send_l3_gmm_llc(ts_GMM_ATTACH_REQ(f_mi_get_lv(), old_ra, false, false, omit, omit));
	alt {
	[] BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_ID_REQ(?))) {
		/* don't send ID Response */
		repeat;
		}
	[] BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_ATTACH_REJECT('09'O))) {
		setverdict(pass);
		}
	[] BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_ATTACH_REJECT(?))) {
		setverdict(fail, "Wrong Attach Reject Cause");
		mtc.stop;
		}
	}
}
testcase TC_attach_auth_id_timeout() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_TC_attach_auth_id_timeout), testcasename(), g_gb, 2, 40.0);
	vc_conn.done;
}

/* HLR never responds to SAI REQ, expect ATTACH REJECT */
private function f_TC_attach_auth_sai_timeout(charstring id) runs on BSSGP_ConnHdlr {
	var RoutingAreaIdentificationV old_ra := f_random_RAI();

	f_send_l3_gmm_llc(ts_GMM_ATTACH_REQ(f_mi_get_lv(), old_ra, false, false, omit, omit));
	alt {
	[] as_mm_identity();
	[] GSUP.receive(tr_GSUP_SAI_REQ(g_pars.imsi)); { }
	}
	/* don't send SAI-response from HLR */
	BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_ATTACH_REJECT(?)));
	setverdict(pass);
}
testcase TC_attach_auth_sai_timeout() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_TC_attach_auth_sai_timeout), testcasename(), g_gb, 3);
	vc_conn.done;
}

/* HLR rejects SAI, expect ATTACH REJECT */
private function f_TC_attach_auth_sai_reject(charstring id) runs on BSSGP_ConnHdlr {
	var RoutingAreaIdentificationV old_ra := f_random_RAI();

	f_send_l3_gmm_llc(ts_GMM_ATTACH_REQ(f_mi_get_lv(), old_ra, false, false, omit, omit));
	alt {
	[] as_mm_identity();
	[] GSUP.receive(tr_GSUP_SAI_REQ(g_pars.imsi)); {
		GSUP.send(ts_GSUP_SAI_ERR(g_pars.imsi, 23));
		}
	}
	BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_ATTACH_REJECT(?)));
	setverdict(pass);
}
testcase TC_attach_auth_sai_reject() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_TC_attach_auth_sai_reject), testcasename(), g_gb, 4);
	vc_conn.done;
}

/* HLR never responds to UL REQ, expect ATTACH REJECT */
private function f_TC_attach_gsup_lu_timeout(charstring id) runs on BSSGP_ConnHdlr {
	var BssgpDecoded bd;
	var RoutingAreaIdentificationV old_ra := f_random_RAI();

	f_send_l3_gmm_llc(ts_GMM_ATTACH_REQ(f_mi_get_lv(), old_ra, false, false, omit, omit));
	f_gmm_auth();
	/* Expect MSC to perform LU with HLR */
	GSUP.receive(tr_GSUP_UL_REQ(g_pars.imsi));
	/* Never follow-up with ISD_REQ or UL_RES */
	alt {
	[] BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_ATTACH_REJECT(?))) {
		setverdict(pass);
		}
	[] BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_ATTACH_ACCEPT('001'B, ?, ?))) -> value bd {
		f_process_attach_accept(bd.l3_mt.msgs.gprs_mm.attachAccept);
		setverdict(fail);
		mtc.stop;
		}
	}
}
testcase TC_attach_gsup_lu_timeout() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_TC_attach_gsup_lu_timeout), testcasename(), g_gb, 5);
	vc_conn.done;
}

/* HLR rejects UL REQ, expect ATTACH REJECT */
private function f_TC_attach_gsup_lu_reject(charstring id) runs on BSSGP_ConnHdlr {
	var BssgpDecoded bd;
	var RoutingAreaIdentificationV old_ra := f_random_RAI();

	f_send_l3_gmm_llc(ts_GMM_ATTACH_REQ(f_mi_get_lv(), old_ra, false, false, omit, omit));
	f_gmm_auth();
	/* Expect MSC to perform LU with HLR */
	GSUP.receive(tr_GSUP_UL_REQ(g_pars.imsi)) {
		GSUP.send(ts_GSUP_UL_ERR(g_pars.imsi, 0));
	}
	alt {
	[] BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_ATTACH_REJECT(?))) {
		setverdict(pass);
		}
	[] BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_ATTACH_ACCEPT('001'B, ?, ?))) -> value bd {
		f_process_attach_accept(bd.l3_mt.msgs.gprs_mm.attachAccept);
		setverdict(fail);
		mtc.stop;
		}
	}
}
testcase TC_attach_gsup_lu_reject() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_TC_attach_gsup_lu_reject), testcasename(), g_gb, 6);
	vc_conn.done;
}


/* Attempt of combined GPRS + IMSI attach: network should ACK only GPRS attach  */
private function f_TC_attach_combined(charstring id) runs on BSSGP_ConnHdlr {
	var BssgpDecoded bd;
	var RoutingAreaIdentificationV old_ra := f_random_RAI();

	f_send_l3_gmm_llc(ts_GMM_ATTACH_REQ(f_mi_get_lv(), old_ra, true, false, omit, omit));
	f_gmm_auth();
	/* Expect MSC to perform LU with HLR */
	f_gmm_gsup_lu_isd();

	BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_ATTACH_ACCEPT('001'B, ?, ?))) -> value bd {
		f_process_attach_accept(bd.l3_mt.msgs.gprs_mm.attachAccept);
	}
	f_send_l3_gmm_llc(ts_GMM_ATTACH_COMPL);
	setverdict(pass);
}
testcase TC_attach_combined() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_TC_attach_combined), testcasename(), g_gb, 7);
	vc_conn.done;
}

/* Attempt of GPRS ATTACH in 'accept all' mode */
private function f_TC_attach_accept_all(charstring id) runs on BSSGP_ConnHdlr {
	var BssgpDecoded bd;
	var RoutingAreaIdentificationV old_ra := f_random_RAI();

	g_pars.net.expect_auth := false;

	f_send_l3_gmm_llc(ts_GMM_ATTACH_REQ(f_mi_get_lv(), old_ra, false, false, omit, omit));
	f_gmm_auth();
	BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_ATTACH_ACCEPT('001'B, ?, ?))) -> value bd {
		f_process_attach_accept(bd.l3_mt.msgs.gprs_mm.attachAccept);
	}
	f_send_l3_gmm_llc(ts_GMM_ATTACH_COMPL);
	setverdict(pass);
}
testcase TC_attach_accept_all() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	f_sleep(1.0);
	f_vty_config(SGSNVTY, "sgsn", "auth-policy accept-all");
	vc_conn := f_start_handler(refers(f_TC_attach_accept_all), testcasename(), g_gb, 8);
	vc_conn.done;
}

/* Attempt of GPRS ATTACH in 'accept all' mode */
private function f_TC_attach_closed_foreign(charstring id) runs on BSSGP_ConnHdlr {
	var RoutingAreaIdentificationV old_ra := f_random_RAI();

	/* Simulate a foreign IMSI */
	g_pars.imsi := '001010123456789'H;
	f_bssgp_client_register(g_pars.imsi, g_pars.tlli, g_pars.bssgp_cell_id[0]);

	g_pars.net.expect_auth := false;

	f_send_l3_gmm_llc(ts_GMM_ATTACH_REQ(f_mi_get_lv(), old_ra, false, false, omit, omit));
	alt {
	[] as_mm_identity();
	[] BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_ATTACH_REJECT('07'O))) {
		setverdict(pass);
		}
	[] BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_ATTACH_REJECT(?))) {
		setverdict(pass);
		}
	[] BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_ATTACH_ACCEPT(*, *, *))) {
		setverdict(fail);
		mtc.stop;
		}
	}
}
testcase TC_attach_closed() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	f_sleep(1.0);
	f_vty_config(SGSNVTY, "sgsn", "auth-policy closed");
	/* test with foreign IMSI: Must Reject */
	vc_conn := f_start_handler(refers(f_TC_attach_closed_foreign), testcasename(), g_gb, 9);
	vc_conn.done;
	/* test with home IMSI: Must Accept */
	vc_conn := f_start_handler(refers(f_TC_attach_accept_all), testcasename(), g_gb, 10);
	vc_conn.done;
}

/* Routing Area Update from Unknown TLLI -> REJECT */
private function f_TC_rau_unknown(charstring id) runs on BSSGP_ConnHdlr {
	var RoutingAreaIdentificationV old_ra := f_random_RAI();

	f_send_l3_gmm_llc(ts_GMM_RAU_REQ(f_mi_get_lv(), GPRS_UPD_T_RA, old_ra, false, omit, omit));
	alt {
	[] BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_RAU_REJECT('0a'O))) {
		setverdict(pass);
		}
	/* FIXME: Expect XID RESET? */
	[] BSSGP[0].receive { repeat; }
	}
}
testcase TC_rau_unknown() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_TC_rau_unknown), testcasename(), g_gb, 11);
	vc_conn.done;
}

private function f_TC_attach_rau(charstring id) runs on BSSGP_ConnHdlr {
	var BssgpDecoded bd;

	/* first perform regular attach */
	f_TC_attach(id);

	f_routing_area_update(g_pars.ra);

}
testcase TC_attach_rau() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_TC_attach_rau), testcasename(), g_gb, 12);
	vc_conn.done;
}

/* general GPRS DETACH helper */
function f_detach_mo(BIT3 detach_type, boolean power_off, boolean expect_purge, integer bssgp_index := 0) runs on BSSGP_ConnHdlr {
	var BssgpDecoded bd;
	timer T := 5.0;
	f_send_l3_gmm_llc(ts_GMM_DET_REQ_MO(detach_type, power_off), bssgp_index);
	if (expect_purge) {
		GSUP.receive(tr_GSUP_PURGE_MS_REQ(g_pars.imsi, OSMO_GSUP_CN_DOMAIN_PS));
		GSUP.send(ts_GSUP_PURGE_MS_RES(g_pars.imsi));
	}
	T.start;
	alt {
	[not expect_purge] GSUP.receive(tr_GSUP_PURGE_MS_REQ(?)) {
		setverdict(fail, "Unexpected GSUP PURGE MS for unregistered TLLI");
		mtc.stop;
		}
	[power_off] BSSGP[bssgp_index].receive(tr_BD_L3_MT(tr_GMM_DET_ACCEPT_MT)) -> value bd {
		g_pars.ra := omit;
		setverdict(fail, "Unexpected ATTACH ACCEPT in no-power-off DETACH");
		mtc.stop;
		/* TODO: check if any PDP contexts are deactivated on network side? */
		}
	[power_off] T.timeout {
		setverdict(pass);
		}
	[not power_off] BSSGP[bssgp_index].receive(tr_BD_L3_MT(tr_GMM_DET_ACCEPT_MT)) -> value bd {
		g_pars.ra := omit;
		setverdict(pass);
		/* TODO: check if any PDP contexts are deactivated on network side? */
		}
	[] BSSGP[bssgp_index].receive { repeat; }
	}
}

/* IMSI DETACH (non-power-off) for unknown TLLI */
private function f_TC_detach_unknown_nopoweroff(charstring id) runs on BSSGP_ConnHdlr {
	f_detach_mo(c_GMM_DTT_MO_GPRS, false, false);
}
testcase TC_detach_unknown_nopoweroff() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_TC_detach_unknown_nopoweroff), testcasename(), g_gb, 13);
	vc_conn.done;
}

/* IMSI DETACH (power-off) for unknown TLLI */
private function f_TC_detach_unknown_poweroff(charstring id) runs on BSSGP_ConnHdlr {
	f_detach_mo(c_GMM_DTT_MO_GPRS,  true, false);
}
testcase TC_detach_unknown_poweroff() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_TC_detach_unknown_poweroff), testcasename(), g_gb, 14);
	vc_conn.done;
}

/* IMSI DETACH (non-power-off) for known TLLI */
private function f_TC_detach_nopoweroff(charstring id) runs on BSSGP_ConnHdlr {
	/* first perform regular attach */
	f_TC_attach(id);

	f_detach_mo(c_GMM_DTT_MO_GPRS, false, true);
}
testcase TC_detach_nopoweroff() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_TC_detach_nopoweroff), testcasename(), g_gb, 15);
	vc_conn.done;
}

/* IMSI DETACH (power-off) for known TLLI */
private function f_TC_detach_poweroff(charstring id) runs on BSSGP_ConnHdlr {
	/* first perform regular attach */
	f_TC_attach(id);

	f_detach_mo(c_GMM_DTT_MO_GPRS, true, true);
}
testcase TC_detach_poweroff() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_TC_detach_poweroff), testcasename(), g_gb, 16);
	vc_conn.done;
}

type record PdpActPars {
	BIT3			tid,				/* L3 Transaction ID */
	BIT4			nsapi,				/* SNDCP NSAPI */
	BIT4			sapi,				/* LLC SAPI */
	QoSV			qos,				/* QoS parameters */
	PDPAddressV		addr,				/* IP address */
	octetstring		apn optional,			/* APN name */
	ProtocolConfigOptionsV	pco optional,			/* protoco config opts */
	OCT1			exp_rej_cause optional,		/* expected SM reject cause */
	OCT1			gtp_resp_cause,			/* GTP response cause */
	OCT4			chg_id,				/* GTP Charging Identifier */

	OCT4			ggsn_tei_c,			/* GGSN TEI Control*/
	OCT4			ggsn_tei_u,			/* GGSN TEI User */
	octetstring		ggsn_ip_c,			/* GGSN IP Control */
	octetstring		ggsn_ip_u,			/* GGSN IP User */
	OCT1			ggsn_restart_ctr,		/* GGSN Restart Counter */

	OCT4			sgsn_tei_c optional,		/* SGSN TEI Control */
	OCT4			sgsn_tei_u optional,		/* SGSN TEI User */
	octetstring		sgsn_ip_c optional,		/* SGSN IP Control */
	octetstring		sgsn_ip_u optional		/* SGSN IP USer */
};


private function f_process_gtp_ctx_act_req(inout PdpActPars apars, PDU_GTPC gtpc) runs on BSSGP_ConnHdlr {
	var GTPC_PDUs gtpc_rx := gtpc.gtpc_pdu;
	apars.sgsn_tei_c := gtpc_rx.createPDPContextRequest.teidControlPlane.teidControlPlane;
	apars.sgsn_tei_u := gtpc_rx.createPDPContextRequest.teidDataI.teidDataI;
	apars.sgsn_ip_c := gtpc_rx.createPDPContextRequest.sgsn_addr_signalling.addressf;
	apars.sgsn_ip_u := gtpc_rx.createPDPContextRequest.sgsn_addr_traffic.addressf;
	f_gtp_register_teid(apars.ggsn_tei_c);
	f_gtp_register_teid(apars.ggsn_tei_u);
}

function f_pdp_ctx_act(inout PdpActPars apars, boolean send_recovery := false) runs on BSSGP_ConnHdlr {
	var boolean exp_rej := ispresent(apars.exp_rej_cause);
	var Gtp1cUnitdata g_ud;
	var template Recovery_gtpc recovery := omit;

	if (send_recovery) {
		recovery := ts_Recovery(apars.ggsn_restart_ctr);
	}

	f_send_l3_gmm_llc(ts_SM_ACT_PDP_REQ(apars.tid, apars.nsapi, apars.sapi, apars.qos, apars.addr,
				     apars.apn, apars.pco));
	GTP.receive(tr_GTPC_MsgType(?, createPDPContextRequest, ?)) -> value g_ud {
		f_process_gtp_ctx_act_req(apars, g_ud.gtpc);
		var integer seq_nr := oct2int(g_ud.gtpc.opt_part.sequenceNumber);
		GTP.send(ts_GTPC_CreatePdpResp(g_ud.peer, seq_nr,
						apars.sgsn_tei_c, apars.gtp_resp_cause,
						apars.ggsn_tei_c, apars.ggsn_tei_u,
						apars.nsapi,
						apars.ggsn_ip_c, apars.ggsn_ip_u, apars.chg_id,
						omit, recovery));
	}
	alt {
	[exp_rej] BSSGP[0].receive(tr_BD_L3_MT(tr_SM_ACT_PDP_REJ(apars.tid, apars.exp_rej_cause))) {
		setverdict(pass);
		}
	[exp_rej] BSSGP[0].receive(tr_BD_L3_MT(tr_SM_ACT_PDP_ACCEPT)) {
		setverdict(fail, "Unexpected PDP CTX ACT ACC");
		mtc.stop;
		}
	[not exp_rej] BSSGP[0].receive(tr_BD_L3_MT(tr_SM_ACT_PDP_REJ(apars.tid, ?))) {
		setverdict(fail, "Unexpected PDP CTX ACT FAIL");
		mtc.stop;
		}
	[not exp_rej] BSSGP[0].receive(tr_BD_L3_MT(tr_SM_ACT_PDP_ACCEPT(apars.tid, apars.sapi))) {
		setverdict(pass);
		}
	[] as_xid(apars);
	}
}

function f_pdp_ctx_deact_mo(inout PdpActPars apars, OCT1 cause) runs on BSSGP_ConnHdlr {
	var boolean exp_rej := ispresent(apars.exp_rej_cause);
	var Gtp1cUnitdata g_ud;

	f_send_l3_gmm_llc(ts_SM_DEACT_PDP_REQ_MO(apars.tid, cause, false, omit));
	GTP.receive(tr_GTPC_MsgType(?, deletePDPContextRequest, apars.ggsn_tei_c)) -> value g_ud {
		var integer seq_nr := oct2int(g_ud.gtpc.opt_part.sequenceNumber);
		BSSGP[0].clear;
		GTP.send(ts_GTPC_DeletePdpResp(g_ud.peer, seq_nr, apars.sgsn_tei_c, '7F'O));
	}
	alt {
	[] BSSGP[0].receive(tr_BD_L3_MT(tr_SM_DEACT_PDP_ACCEPT_MT(apars.tid))) {
		setverdict(pass);
		}
	[] as_xid(apars);
	}
}

function f_pdp_ctx_deact_mt(inout PdpActPars apars, boolean error_ind := false) runs on BSSGP_ConnHdlr {
	var Gtp1cUnitdata g_ud;
	var integer seq_nr := 23;
	var GtpPeer peer := valueof(ts_GtpPeerC(apars.sgsn_ip_c));

	BSSGP[0].clear;
	if (error_ind) {
		GTP.send(ts_GTPU_ErrorIndication(peer, 0 /* seq */, apars.ggsn_tei_u, apars.ggsn_ip_u));
	} else {
		GTP.send(ts_GTPC_DeletePDP(peer, seq_nr, apars.sgsn_tei_c, apars.nsapi, '1'B));
	}

	timer T := 5.0;
	T.start;

	alt {
	[] BSSGP[0].receive(tr_BD_L3_MT(tr_SM_DEACT_PDP_REQ_MT(apars.tid, ?, true))) {
		f_send_l3_gmm_llc(ts_SM_DEACT_PDP_ACCEPT_MO(apars.tid));
		}
	[not error_ind] GTP.receive(tr_GTPC_MsgType(?, deletePDPContextResponse, apars.ggsn_tei_c)) {
		repeat;
		}
	[] T.timeout {
		setverdict(fail, "Waiting for SM_DEACT_PDP_REQ_MT");
		}
	}
}


/* Table 10.5.156/3GPP TS 24.008 */
template (value) QoSV t_QosDefault := {
	reliabilityClass := '011'B, /* unacknowledged GTP+LLC, acknowledged RLC */
	delayClass := '100'B,	/* best effort */
	spare1 := '00'B,
	precedenceClass := '010'B, /* normal */
	spare2 := '0'B,
	peakThroughput := '0000'B, /* subscribed */
	meanThroughput := '00000'B, /* subscribed */
	spare3 := '000'B,
	deliverErroneusSDU := omit,
	deliveryOrder := omit,
	trafficClass := omit,
	maxSDUSize := omit,
	maxBitrateUplink := omit,
	maxBitrateDownlink := omit,
	sduErrorRatio := omit,
	residualBER := omit,
	trafficHandlingPriority := omit,
	transferDelay := omit,
	guaranteedBitRateUplink := omit,
	guaranteedBitRateDownlink := omit,
	sourceStatisticsDescriptor := omit,
	signallingIndication := omit,
	spare4 := omit,
	maxBitrateDownlinkExt := omit,
	guaranteedBitRateDownlinkExt := omit,
	maxBitrateUplinkExt := omit,
	guaranteedBitRateUplinkExt := omit,
	maxBitrateDownlinkExt2 := omit,
	guaranteedBitRateDownlinkExt2 := omit,
	maxBitrateUplinkExt2 := omit,
	guaranteedBitRateUplinkExt2 := omit
}

/* 10.5.6.4 / 3GPP TS 24.008 */
template (value) PDPAddressV t_AddrIPv4dyn := {
	pdpTypeOrg := '0001'B, /* IETF */
	spare := '0000'B,
	pdpTypeNum := '21'O, /* IPv4 */
	addressInfo := omit
}
template (value) PDPAddressV t_AddrIPv6dyn := {
	pdpTypeOrg := '0001'B, /* IETF */
	spare := '0000'B,
	pdpTypeNum := '53'O, /* IPv6 */
	addressInfo := omit
}

template (value) PdpActPars t_PdpActPars(charstring ggsn_ip) := {
	tid := '000'B,
	nsapi := '0101'B, /* < 5 are reserved */
	sapi := '0011'B, /* 3/5/9/11 */
	qos := t_QosDefault,
	addr := t_AddrIPv4dyn,
	apn := omit,
	pco := omit,
	exp_rej_cause := omit,
	gtp_resp_cause := int2oct(128, 1),
	chg_id := f_rnd_octstring(4),

	/* FIXME: make below dynamic !! */
	ggsn_tei_c := f_rnd_octstring(4),
	ggsn_tei_u := f_rnd_octstring(4),
	ggsn_ip_c := f_inet_addr(ggsn_ip),
	ggsn_ip_u := f_inet_addr(ggsn_ip),
	ggsn_restart_ctr := int2oct(2, 1),

	sgsn_tei_c := omit,
	sgsn_tei_u := omit,
	sgsn_ip_c := omit,
	sgsn_ip_u := omit
}

template (value) GtpPeer ts_GtpPeerU(octetstring ip) := {
	connId := 1,
	remName := f_inet_ntoa(ip),
	remPort := GTP1U_PORT
}

template (value) GtpPeer ts_GtpPeerC(octetstring ip) := {
	connId := 1,
	remName := f_inet_ntoa(ip),
	remPort := GTP1C_PORT
}

private function f_gtpu_send(inout PdpActPars apars, octetstring payload) runs on BSSGP_ConnHdlr {
	var GtpPeer peer := valueof(ts_GtpPeerU(apars.sgsn_ip_u));
	GTP.send(ts_GTP1U_GPDU(peer, 0 /*seq*/, apars.sgsn_tei_u, payload));
}

private altstep as_xid(PdpActPars apars) runs on BSSGP_ConnHdlr {
	[] BSSGP[0].receive(tr_BD_LLC(tr_LLC_XID(?, apars.sapi))) {
		repeat;
	}
}

template PDU_SN tr_SN_UD(template BIT4 nsapi, template octetstring payload) := {
	pDU_SN_UNITDATA := {
		nsapi := nsapi,
		moreBit := ?,
		snPduType := '1'B,
		firstSegmentIndicator := ?,
		spareBit := ?,
		pcomp := ?,
		dcomp := ?,
		npduNumber := ?,
		segmentNumber := ?,
		npduNumberContinued := ?,
		dataSegmentSnUnitdataPdu := payload
	}
}

/* simple case: single segment, no compression */
template (value) PDU_SN ts_SN_UD(BIT4 nsapi, octetstring payload) := {
	pDU_SN_UNITDATA := {
		nsapi := nsapi,
		moreBit := '0'B,
		snPduType := '1'B,
		firstSegmentIndicator := '1'B,
		spareBit := '0'B,
		pcomp := '0000'B,
		dcomp := '0000'B,
		npduNumber := '0000'B,
		segmentNumber := '0000'B,
		npduNumberContinued := '00'O,
		dataSegmentSnUnitdataPdu := payload
	}
}

/* Transceive given 'payload' as MT message from GTP -> OsmoSGSN -> Gb */
private function f_gtpu_xceive_mt(inout PdpActPars apars, octetstring payload) runs on BSSGP_ConnHdlr {
	/* Send PDU via GTP from our simulated GGSN to the SGSN */
	f_gtpu_send(apars, payload);
	/* Expect PDU via BSSGP/LLC on simulated PCU from SGSN */
	alt {
	[] as_xid(apars);
	[] BSSGP[0].receive(tr_BD_SNDCP(apars.sapi, tr_SN_UD(apars.nsapi, payload)));
	}
}

/* Transceive given 'payload' as MT message from Gb -> OsmoSGSN -> GTP */
private function f_gtpu_xceive_mo(inout PdpActPars apars, octetstring payload) runs on BSSGP_ConnHdlr {
	/* Send PDU via SNDCP/LLC/BSSGP/NS via simulated MS/PCU to the SGSN */
	var GtpPeer peer := valueof(ts_GtpPeerU(apars.sgsn_ip_u));
	var PDU_SN sndcp := valueof(ts_SN_UD(apars.nsapi, payload));
	BSSGP[0].send(ts_LLC_UI(enc_PDU_SN(sndcp), apars.sapi, '0'B, 0));
	/* Expect PDU via GTP from SGSN on simulated GGSN */
	alt {
	[] GTP.receive(tr_GTPU_GPDU(peer, apars.ggsn_tei_u, payload));
	}
}

private function f_TC_attach_pdp_act(charstring id) runs on BSSGP_ConnHdlr {
	var PdpActPars apars := valueof(t_PdpActPars(mp_ggsn_ip));

	/* first perform regular attach */
	f_TC_attach(id);

	f_pdp_ctx_act(apars);
}
testcase TC_attach_pdp_act() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_TC_attach_pdp_act), testcasename(), g_gb, 17);
	vc_conn.done;
}

/* PDP Context activation for not-attached subscriber; expect fail */
private function f_TC_pdp_act_unattached(charstring id) runs on BSSGP_ConnHdlr {
	var PdpActPars apars := valueof(t_PdpActPars(mp_ggsn_ip));
	f_send_l3_gmm_llc(ts_SM_ACT_PDP_REQ(apars.tid, apars.nsapi, apars.sapi, apars.qos, apars.addr,
				     apars.apn, apars.pco));
	alt {
	/* We might want toalso actually expect a PDPC CTX ACT REJ? */
	[] BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_DET_REQ_MT(?, ?))) {
		setverdict(pass);
		}
	[] GTP.receive(tr_GTPC_MsgType(?, createPDPContextRequest, ?)) {
		setverdict(fail, "Unexpected GTP PDP CTX ACT");
		mtc.stop;
		}
	[] BSSGP[0].receive(tr_BD_L3_MT(tr_SM_ACT_PDP_ACCEPT(?, ?))) {
		setverdict(fail, "Unexpected SM PDP CTX ACT ACK");
		mtc.stop;
		}
	[] BSSGP[0].receive { repeat; }
	}
}
testcase TC_pdp_act_unattached() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_TC_pdp_act_unattached), testcasename(), g_gb, 18);
	vc_conn.done;
}

/* ATTACH + PDP CTX ACT + user plane traffic */
private function f_TC_attach_pdp_act_user(charstring id) runs on BSSGP_ConnHdlr {
	var PdpActPars apars := valueof(t_PdpActPars(mp_ggsn_ip));

	/* first perform regular attach */
	f_TC_attach(id);
	/* then activate PDP context */
	f_pdp_ctx_act(apars);
	/* then transceive a downlink PDU */
	f_gtpu_xceive_mt(apars, f_rnd_octstring(100));
	f_gtpu_xceive_mo(apars, f_rnd_octstring(200));
}
testcase TC_attach_pdp_act_user() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_TC_attach_pdp_act_user), testcasename(), g_gb, 19);
	vc_conn.done;
}

/* ATTACH + PDP CTX ACT; reject from GGSN */
private function f_TC_attach_pdp_act_ggsn_reject(charstring id) runs on BSSGP_ConnHdlr {
	var PdpActPars apars := valueof(t_PdpActPars(mp_ggsn_ip));

	apars.gtp_resp_cause := int2oct(199, 1);	/* no resources available */
	apars.exp_rej_cause := '1a'O;			/* insufficient resources */

	/* first perform regular attach */
	f_TC_attach(id);
	/* then activate PDP context */
	f_pdp_ctx_act(apars);
}
testcase TC_attach_pdp_act_ggsn_reject() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_TC_attach_pdp_act_ggsn_reject), testcasename(), g_gb, 20);
	vc_conn.done;
}

/* ATTACH + PDP CTX ACT + user plane traffic + PDP CTX DEACT in MO direction */
private function f_TC_attach_pdp_act_user_deact_mo(charstring id) runs on BSSGP_ConnHdlr {
	var PdpActPars apars := valueof(t_PdpActPars(mp_ggsn_ip));

	/* first perform regular attach */
	f_TC_attach(id);
	/* then activate PDP context */
	f_pdp_ctx_act(apars);
	/* then transceive a downlink PDU */
	f_gtpu_xceive_mt(apars, f_rnd_octstring(100));
	f_gtpu_xceive_mo(apars, f_rnd_octstring(200));

	f_pdp_ctx_deact_mo(apars, '00'O);
}
testcase TC_attach_pdp_act_user_deact_mo() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_TC_attach_pdp_act_user_deact_mo), testcasename(), g_gb, 21);
	vc_conn.done;
}

/* ATTACH + PDP CTX ACT + user plane traffic + PDP CTX DEACT in MT direction */
private function f_TC_attach_pdp_act_user_deact_mt(charstring id) runs on BSSGP_ConnHdlr {
	var PdpActPars apars := valueof(t_PdpActPars(mp_ggsn_ip));

	/* first perform regular attach */
	f_TC_attach(id);
	/* then activate PDP context */
	f_pdp_ctx_act(apars);
	/* then transceive a downlink PDU */
	f_gtpu_xceive_mt(apars, f_rnd_octstring(100));
	f_gtpu_xceive_mo(apars, f_rnd_octstring(200));

	f_pdp_ctx_deact_mt(apars, false);
}
testcase TC_attach_pdp_act_user_deact_mt() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_TC_attach_pdp_act_user_deact_mt), testcasename(), g_gb, 22);
	vc_conn.done;
}

/* ATTACH + ATTACH (2nd) */
private function f_TC_attach_forget_tlli_attach(charstring id) runs on BSSGP_ConnHdlr {
	g_pars.t_guard  := 5.0;

	/* first perform regular attach */
	f_TC_attach(id);

	/* second to perform regular attach */
	f_TC_attach(id);
}


testcase TC_attach_second_attempt() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_TC_attach_forget_tlli_attach), testcasename(), g_gb, 22);
	vc_conn.done;
}

private function f_TC_attach_restart_ctr_echo(charstring id) runs on BSSGP_ConnHdlr {
	var Gtp1cUnitdata g_ud;
	var PdpActPars apars := valueof(t_PdpActPars(mp_ggsn_ip));

	/* first perform regular attach */
	f_TC_attach(id);
	/* Activate a pdp context against the  GGSN */
	f_pdp_ctx_act(apars);
	/* Wait to receive first echo request and send initial Restart counter */
	GTP.receive(tr_GTPC_MsgType(?, echoRequest, ?)) -> value g_ud {
		var integer seq_nr := oct2int(g_ud.gtpc.opt_part.sequenceNumber);
		GTP.send(ts_GTPC_PONG(g_ud.peer, seq_nr, apars.ggsn_restart_ctr));
	}
	/* Wait to receive second echo request and send incremented Restart
	   counter. This will fake a restarted GGSN, and pdp ctx allocated
	   should be released by SGSN */
	apars.ggsn_restart_ctr := int2oct(oct2int(apars.ggsn_restart_ctr) + 1, 1);
	GTP.receive(tr_GTPC_MsgType(?, echoRequest, ?)) -> value g_ud {
		var integer seq_nr := oct2int(g_ud.gtpc.opt_part.sequenceNumber);
		GTP.send(ts_GTPC_PONG(g_ud.peer, seq_nr, apars.ggsn_restart_ctr));
	}
	var OCT1 cause_network_failure := int2oct(38, 1)
	alt {
	[] BSSGP[0].receive(tr_BD_L3_MT(tr_SM_DEACT_PDP_REQ_MT(apars.tid, cause_network_failure, true))) {
		f_send_l3_gmm_llc(ts_SM_DEACT_PDP_ACCEPT_MO(apars.tid));
		setverdict(pass);
		}
	[] as_xid(apars);
	}
	setverdict(pass);
}
/* ATTACH + trigger Recovery procedure through EchoResp */
testcase TC_attach_restart_ctr_echo() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	g_use_echo := true
	f_init();
	vc_conn := f_start_handler(refers(f_TC_attach_restart_ctr_echo), testcasename(), g_gb, 23, 30.0);
	vc_conn.done;
	g_use_echo := false
}

private function f_TC_attach_restart_ctr_create(charstring id) runs on BSSGP_ConnHdlr {
	var Gtp1cUnitdata g_ud;
	var PdpActPars apars := valueof(t_PdpActPars(mp_ggsn_ip));
	var integer seq_nr := 23;
	var GtpPeer peer;
	/* first perform regular attach */
	f_TC_attach(id);

	/* Use this CTX ACT to send initial Restart counter to SGSN. */
	apars.gtp_resp_cause := int2oct(199, 1);	/* no resources available */
	apars.exp_rej_cause := '1a'O;			/* insufficient resources */
	f_pdp_ctx_act(apars, true);

	/* Increment restart_ctr. This will fake a restarted GGSN when CreatePdpResp is
/* received. */
	apars.ggsn_restart_ctr := int2oct(oct2int(apars.ggsn_restart_ctr) + 1, 1);

	/* FIXME: Once we can easily handle different pdp ctx simultaneously, it
	   would be great to have an active pdp context here before triggering
	   Recovery, and making sure the the DEACT request is sent by the SGSN.
	*/

	/* Activate a pdp context against the GGSN, send incremented Recovery
	   IE. This should trigger the recovery path, but still this specific
	   CTX activation should work. */
	apars.exp_rej_cause := omit; /* default value for tests */
	apars.gtp_resp_cause := int2oct(128, 1);  /* default value for tests */
	f_pdp_ctx_act(apars, true);

	setverdict(pass);
}
/* ATTACH + trigger Recovery procedure through CreatePdpResp */
testcase TC_attach_restart_ctr_create() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_TC_attach_restart_ctr_create), testcasename(), g_gb, 24, 30.0);
	vc_conn.done;
}

/* ATTACH + PDP CTX ACT + user plane traffic + PDP CTX DEACT in MT direction + trigger T3395 */
private function f_TC_attach_pdp_act_deact_mt_t3395_expire(charstring id) runs on BSSGP_ConnHdlr {
	var PdpActPars apars := valueof(t_PdpActPars(mp_ggsn_ip));
	var integer seq_nr := 23;
	var GtpPeer peer;
	var integer i;

	/* first perform regular attach */
	f_TC_attach(id);
	/* then activate PDP context */
	f_pdp_ctx_act(apars);

	BSSGP[0].clear;
	peer := valueof(ts_GtpPeerC(apars.sgsn_ip_c));
	GTP.send(ts_GTPC_DeletePDP(peer, seq_nr, apars.sgsn_tei_c, apars.nsapi, '1'B));

	for (i := 0; i < 5; i := i+1) {
		alt {
			[] BSSGP[0].receive(tr_BD_L3_MT(tr_SM_DEACT_PDP_REQ_MT(apars.tid, ?, true))) {}
			[] as_xid(apars);
		}
	}

	GTP.receive(tr_GTPC_MsgType(?, deletePDPContextResponse, apars.ggsn_tei_c)) {}

	f_send_l3_gmm_llc(ts_SM_DEACT_PDP_ACCEPT_MO(apars.tid));
	setverdict(pass);
}
testcase TC_attach_pdp_act_deact_mt_t3395_expire() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_TC_attach_pdp_act_deact_mt_t3395_expire), testcasename(), g_gb, 25, 60.0);
	vc_conn.done;
}

private function f_TC_hlr_location_cancel_request_update(charstring id) runs on BSSGP_ConnHdlr {
	/* MS: perform regular attach */
	f_TC_attach(id);

	/* HLR: cancel the location request */
	GSUP.send(ts_GSUP_CL_REQ(g_pars.imsi, OSMO_GSUP_CANCEL_TYPE_UPDATE));
	GSUP.receive(tr_GSUP_CL_RES(g_pars.imsi));

	/* ensure no Detach Request got received */
	timer T := 5.0;
	T.start;
	alt {
		[] BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_DET_REQ_MT(*, *, *))) {
			T.stop;
			setverdict(fail, "Unexpected GMM Detach Request");
			mtc.stop;
		}
		[] T.timeout {
			setverdict(pass);
			mtc.stop;
		}
		[] BSSGP[0].receive {
			repeat;
		}
	}
}

/* ATTACH + PDP CTX ACT + user plane traffic + ERROR IND in MT direction */
private function f_TC_attach_pdp_act_user_error_ind_ggsn(charstring id) runs on BSSGP_ConnHdlr {
	var PdpActPars apars := valueof(t_PdpActPars(mp_ggsn_ip));

	/* first perform regular attach */
	f_TC_attach(id);
	/* then activate PDP context */
	f_pdp_ctx_act(apars);
	/* then transceive a downlink PDU */
	f_gtpu_xceive_mo(apars, f_rnd_octstring(200));

	/* Send Error indication as response from upload PDU and expect deact towards MS */
	f_pdp_ctx_deact_mt(apars, true);
}
testcase TC_attach_pdp_act_user_error_ind_ggsn() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_TC_attach_pdp_act_user_error_ind_ggsn), testcasename(), g_gb, 26);
	vc_conn.done;
}

testcase TC_hlr_location_cancel_request_update() runs on test_CT {
	/* MS <-> SGSN: GMM Attach
	 * HLR -> SGSN: Cancel Location Request
	 * HLR <- SGSN: Cancel Location Ack
	 */
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_TC_hlr_location_cancel_request_update), testcasename(), g_gb, 31);
	vc_conn.done;
}


private function f_TC_hlr_location_cancel_request_withdraw(charstring id) runs on BSSGP_ConnHdlr {
	/* MS: perform regular attach */
	f_TC_attach(id);

	/* HLR: cancel the location request */
	GSUP.send(ts_GSUP_CL_REQ(g_pars.imsi, OSMO_GSUP_CANCEL_TYPE_WITHDRAW));
	GSUP.receive(tr_GSUP_CL_RES(g_pars.imsi));
	GSUP.send(ts_GSUP_UL_RES(g_pars.imsi));

	/* MS: receive a Detach Request */
	BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_DET_REQ_MT(c_GMM_DTT_MT_IMSI_DETACH, ?, ?)));
	f_send_l3_gmm_llc(ts_GMM_DET_ACCEPT_MO);

	setverdict(pass);
}

testcase TC_hlr_location_cancel_request_withdraw() runs on test_CT {
	/* MS <-> SGSN: GMM Attach
	 * HLR -> SGSN: Cancel Location Request
	 * HLR <- SGSN: Cancel Location Ack
	 * MS  <- SGSN: Detach Request
	 * SGSN->   MS: Detach Complete
	 */
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_TC_hlr_location_cancel_request_withdraw), testcasename(), g_gb, 29);
	vc_conn.done;
}


private function f_hlr_location_cancel_request_unknown_subscriber(
		charstring id,
		GSUP_CancelType canceltype) runs on BSSGP_ConnHdlr {

	/* HLR: cancel the location request */
	GSUP.send(ts_GSUP_CL_REQ(g_pars.imsi, canceltype));

	/* cause 2 = IMSI_UNKNOWN */
	GSUP.receive(tr_GSUP_CL_ERR(g_pars.imsi, 2));

	setverdict(pass);
}

private function f_TC_hlr_location_cancel_request_unknown_subscriber_withdraw(charstring id) runs on BSSGP_ConnHdlr {
	f_hlr_location_cancel_request_unknown_subscriber(id, OSMO_GSUP_CANCEL_TYPE_WITHDRAW);
}

testcase TC_hlr_location_cancel_request_unknown_subscriber_withdraw() runs on test_CT {
	/* HLR -> SGSN: Cancel Location Request
	 * HLR <- SGSN: Cancel Location Error
	 */

	var BSSGP_ConnHdlr vc_conn;
	f_init();
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_TC_hlr_location_cancel_request_unknown_subscriber_withdraw), testcasename(), g_gb, 30);
	vc_conn.done;
}

private function f_TC_hlr_location_cancel_request_unknown_subscriber_update(charstring id) runs on BSSGP_ConnHdlr {
	f_hlr_location_cancel_request_unknown_subscriber(id, OSMO_GSUP_CANCEL_TYPE_WITHDRAW);
}

testcase TC_hlr_location_cancel_request_unknown_subscriber_update() runs on test_CT {
	/* HLR -> SGSN: Cancel Location Request
	 * HLR <- SGSN: Cancel Location Error
	 */

	var BSSGP_ConnHdlr vc_conn;
	f_init();
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_TC_hlr_location_cancel_request_unknown_subscriber_update), testcasename(), g_gb, 30);
	vc_conn.done;
}

private function f_TC_attach_detach_check_subscriber_list(charstring id) runs on BSSGP_ConnHdlr {
	f_TC_attach(id);
	f_detach_mo(c_GMM_DTT_MO_GPRS, true, true);
}

testcase TC_attach_detach_check_subscriber_list() runs on test_CT {
	/* MS <-> SGSN: Attach
	 * MS ->  SGSN: Detach Req (Power off)
	 * VTY -> SGSN: Check if MS is NOT in subscriber cache
	 */
	var BSSGP_ConnHdlr vc_conn;
	var integer id := 33;
	var charstring imsi := hex2str(f_gen_imsi(id));

	f_init();
	vc_conn := f_start_handler(refers(f_TC_attach_detach_check_subscriber_list), testcasename(), g_gb, id);
	vc_conn.done;

	f_vty_transceive_not_match(SGSNVTY, "show subscriber cache", pattern "* IMSI: {imsi}*");
}

/* Attempt an attach, but loose the Identification Request (IMEI) */
private function f_TC_attach_no_imei_response(charstring id) runs on BSSGP_ConnHdlr {
	var integer count_req := 0;
	var MobileL3_CommonIE_Types.MobileIdentityLV mi;

	f_send_l3_gmm_llc(ts_GMM_ATTACH_REQ(f_mi_get_lv(), f_random_RAI(), true, false, omit, omit));

	alt {
		[] BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_ATTACH_REJECT(?))) {
			/* break */
		}
		[] BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_ID_REQ('001'B))) {
			mi := valueof(ts_MI_IMSI_LV(g_pars.imsi));
			f_send_l3_gmm_llc(ts_GMM_ID_RESP(mi));
			repeat;
		}
		[] BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_ID_REQ('010'B))) {
			/* ignore ID REQ IMEI */
			count_req := count_req + 1;
			repeat;
		}
	}
	if (count_req != 5) {
		setverdict(fail, "Did not received GMM ID Request Type IMEI 5 times!");
		mtc.stop;
	}
	setverdict(pass);
}

testcase TC_attach_no_imei_response() runs on test_CT {
	/* MS -> SGSN: Attach Request IMSI
	 * MS <- SGSN: Identity Request IMSI (optional)
	 * MS -> SGSN: Identity Response IMSI (optional)
	 * MS <- SGSN: Identity Request IMEI
	 * MS -x SGSN: no response
	 * MS <- SGSN: re-send: Identity Request IMEI 4x
	 * MS <- SGSN: Attach Reject
	 */
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_TC_attach_no_imei_response), testcasename(), g_gb, 32, 60.0);
	vc_conn.done;
}

/* Attempt an attach, but loose the Identification Request (IMSI) */
private function f_TC_attach_no_imsi_response(charstring id) runs on BSSGP_ConnHdlr {
	var integer count_req := 0;
	var MobileL3_CommonIE_Types.MobileIdentityLV mi;

	/* set p_tmsi to use it in Attach Req via f_mi_get_lv() */
	g_pars.p_tmsi := 'c0000035'O;

	f_send_l3_gmm_llc(ts_GMM_ATTACH_REQ(f_mi_get_lv(), f_random_RAI(), true, false, omit, omit));

	alt {
		[] BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_ATTACH_REJECT(?))) {
			/* break */
		}
		[] BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_ID_REQ('001'B))) {
			/* ignore ID REQ IMSI */
			count_req := count_req + 1;
			repeat;
		}
		[] BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_ID_REQ('010'B))) {
			mi := valueof(ts_MI_IMEI_LV(g_pars.imei));
			f_send_l3_gmm_llc(ts_GMM_ID_RESP(mi));
			repeat;
		}
	}
	if (count_req != 5) {
		setverdict(fail, "Did not received GMM ID Request Type IMSI 5 times!");
		mtc.stop;
	}
	setverdict(pass);
}

testcase TC_attach_no_imsi_response() runs on test_CT {
	/* MS -> SGSN: Attach Request TMSI (unknown)
	 * MS <- SGSN: Identity Request IMEI (optional)
	 * MS -> SGSN: Identity Response IMEI (optional)
	 * MS <- SGSN: Identity Request IMSI
	 * MS -x SGSN: no response
	 * MS <- SGSN: re-send: Identity Request IMSI 4x
	 * MS <- SGSN: Attach Reject
	 */
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_TC_attach_no_imsi_response), testcasename(), g_gb, 35, 60.0);
	vc_conn.done;
}

private function f_sgsn_vty_destroy_subscriber_imsi(TELNETasp_PT pt, charstring imsi) {
	f_vty_transceive(pt, "update-subscriber imsi " & imsi & " destroy");
}

testcase TC_attach_check_subscriber_list() runs on test_CT {
	/* MS <-> SGSN: Attach
	 * VTY -> SGSN: Check if MS is in subscriber cache
	 */
	var BSSGP_ConnHdlr vc_conn;
	var integer id := 34;
	var charstring imsi := hex2str(f_gen_imsi(id));

	f_init();
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_TC_attach), testcasename(), g_gb, id);
	vc_conn.done;

	f_vty_transceive_match(SGSNVTY, "show subscriber cache", pattern "* IMSI: {imsi}*");
	f_sgsn_vty_destroy_subscriber_imsi(SGSNVTY, imsi);
}

private function f_TC_attach_closed_imsi_added(charstring id) runs on BSSGP_ConnHdlr {
	var RoutingAreaIdentificationV old_ra := f_random_RAI();
	var BssgpDecoded bd;

	/* unregister the old IMSI */
	f_bssgp_client_unregister(g_pars.imsi);
	/* Simulate a foreign IMSI */
	g_pars.imsi := '001010123456700'H;
	f_bssgp_client_register(g_pars.imsi, g_pars.tlli, g_pars.bssgp_cell_id[0]);

	/* there is no auth */
	g_pars.net.expect_auth := false;

	f_send_l3_gmm_llc(ts_GMM_ATTACH_REQ(f_mi_get_lv(), old_ra, false, false, omit, omit));
	f_gmm_auth();
	alt {
		[] BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_ATTACH_REJECT(?))) {
			setverdict(fail, "Received unexpected GMM Attach REJECT");
			mtc.stop;
		}
		[] BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_ATTACH_ACCEPT(*, *, *))) -> value bd {
			f_process_attach_accept(bd.l3_mt.msgs.gprs_mm.attachAccept);
			f_send_l3_gmm_llc(ts_GMM_ATTACH_COMPL);
			setverdict(pass);
		}
	}
}

private function f_TC_attach_closed_add_vty(charstring id) runs on BSSGP_ConnHdlr {

	f_TC_attach_closed_foreign(id);
	f_TC_attach_closed_imsi_added(id);

}


testcase TC_attach_closed_add_vty() runs on test_CT {
	/* VTY-> SGSN: policy close
	 * MS -> SGSN: Attach Request
	 * MS <- SGSN: Identity Request IMSI
	 * MS -> SGSN: Identity Response IMSI
	 * MS <- SGSN: Attach Reject
	 * VTY-> SGSN: policy imsi-acl add IMSI
	 * MS -> SGSN: Attach Request
	 * MS <- SGSN: Identity Request IMSI
	 * MS -> SGSN: Identity Response IMSI
	 * MS <- SGSN: Identity Request IMEI
	 * MS -> SGSN: Identity Response IMEI
	 * MS <- SGSN: Attach Accept
	 */
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	f_sleep(1.0);
	f_vty_config(SGSNVTY, "sgsn", "auth-policy closed");
	f_vty_config(SGSNVTY, "sgsn", "imsi-acl del 001010123456789");
	f_vty_config(SGSNVTY, "sgsn", "imsi-acl del 001010123456700");
	f_vty_config(SGSNVTY, "sgsn", "imsi-acl add 001010123456700");
	/* test with foreign IMSI: Must Reject */
	vc_conn := f_start_handler(refers(f_TC_attach_closed_add_vty), testcasename(), g_gb, 9);
	vc_conn.done;
}

/* Attempt an attach, but never answer a Attach Complete */
private function f_TC_attach_check_complete_resend(charstring id) runs on BSSGP_ConnHdlr {
	var integer count_req := 0;

	f_send_l3_gmm_llc(ts_GMM_ATTACH_REQ(f_mi_get_lv(), f_random_RAI(), true, false, omit, omit));
	f_gmm_auth();

	timer T := 10.0;
	T.start;
	alt {
		[] T.timeout {
			/* break */
		}
		[] BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_ATTACH_ACCEPT(*, *, *))) {
			/* ignore */
			count_req := count_req + 1;
			T.start;
			repeat;
		}
	}
	if (count_req != 5) {
		setverdict(fail, "Did not received GMM Attach Complete.");
		mtc.stop;
	}
	setverdict(pass);
}

testcase TC_attach_check_complete_resend() runs on test_CT {
	/* MS -> SGSN: Attach Request IMSI
	 * MS <- SGSN: Identity Request *
	 * MS -> SGSN: Identity Response *
	 * MS <- SGSN: Attach Complete 5x
	 */
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_TC_attach_check_complete_resend), testcasename(), g_gb, 36, 60.0);
	vc_conn.done;
}

private function f_routing_area_update(RoutingAreaIdentificationV ra, integer bssgp := 0) runs on BSSGP_ConnHdlr {
	var BssgpDecoded bd;

	/* then send RAU */
	f_send_l3_gmm_llc(ts_GMM_RAU_REQ(f_mi_get_lv(), GPRS_UPD_T_RA, g_pars.ra, false, omit, omit), bssgp);
	alt {
	[] BSSGP[bssgp].receive(tr_BD_L3_MT(tr_GMM_RAU_ACCEPT)) -> value bd {
		f_process_rau_accept(bd.l3_mt.msgs.gprs_mm.routingAreaUpdateAccept, bssgp);
		f_send_l3_gmm_llc(ts_GMM_RAU_COMPL, bssgp);
		setverdict(pass);
		}
	[] BSSGP[bssgp].receive(tr_BD_L3_MT(tr_GMM_RAU_REJECT)) {
		setverdict(fail, "Unexpected RAU Reject");
		mtc.stop;
		}
	[] BSSGP[bssgp].receive { repeat; }
	}
}

private function f_TC_attach_rau_a_a(charstring id) runs on BSSGP_ConnHdlr {
	var BssgpDecoded bd;

	/* first perform regular attach */
	f_TC_attach(id);

	/* then send RAU */
	f_routing_area_update(g_pars.ra);

	/* do another RAU */
	f_routing_area_update(g_pars.ra);

	f_detach_mo(c_GMM_DTT_MO_GPRS, true, true);
}

testcase TC_attach_rau_a_a() runs on test_CT {
	/* MS <-> SGSN: Successful Attach
	 * MS  -> SGSN: Routing Area Update Request
	 * MS <-  SGSN: Routing Area Update Accept
	 * MS  -> SGSN: Routing Area Update Request
	 * MS <-  SGSN: Routing Area Update Accept
	 * MS  -> SGSN: Detach (PowerOff)
	 */
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_TC_attach_rau_a_a), testcasename(), g_gb, 37);
	vc_conn.done;
}

private function f_TC_attach_rau_a_b(charstring id) runs on BSSGP_ConnHdlr {
	var BssgpDecoded bd;

	f_TC_attach(id);

	log("attach complete sending rau");
	f_routing_area_update(g_pars.ra, 0);

	log("rau complete unregistering");
	f_bssgp_client_unregister(g_pars.imsi);
	f_bssgp_client_register(g_pars.imsi, g_pars.tlli, g_pars.bssgp_cell_id[1], BSSGP_PROC[1]);

	log("sending second RAU via different RA");
	f_routing_area_update(f_cellid_to_RAI(g_pars.bssgp_cell_id[1]), 1);

	f_detach_mo(c_GMM_DTT_MO_GPRS, true, true, 1);
}

testcase TC_attach_rau_a_b() runs on test_CT {
	/* MS <-> SGSN: Successful Attach
	 * MS  -> SGSN: Routing Area _a_ Update Request
	 * MS <-  SGSN: Routing Area _a_ Update Accept
	 * MS  -> SGSN: Routing Area _b_ Update Request
	 * MS <-  SGSN: Routing Area _b_ Update Accept
	 * MS  -> SGSN: Detach (PowerOff)
	 */
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_TC_attach_rau_a_b), testcasename(), g_gb, 38);
	vc_conn.done;
}

private function f_TC_attach_gmm_attach_req_while_gmm_attach(charstring id) runs on BSSGP_ConnHdlr {
	var integer count_req := 0;
	var MobileL3_CommonIE_Types.MobileIdentityLV mi;
	var RoutingAreaIdentificationV rand_rai := f_random_RAI();
	var BssgpDecoded bd;

	f_send_l3_gmm_llc(ts_GMM_ATTACH_REQ(f_mi_get_lv(), rand_rai, true, false, omit, omit));

	alt {
		[] BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_ATTACH_REJECT(?))) {
			setverdict(fail, "Unexpected GMM ATTACH REJECT");
			mtc.stop;
		}
		[] BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_ID_REQ('001'B))) {
			mi := valueof(ts_MI_IMSI_LV(g_pars.imsi));
			f_send_l3_gmm_llc(ts_GMM_ID_RESP(mi));
			repeat;
		}
		[] BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_ID_REQ('010'B))) {
			/* send out a second GMM_Attach Request.
			 * If the SGSN follows the rules, this 2nd ATTACH REQ should be ignored, because
			 * of the same content */
			f_send_l3_gmm_llc(ts_GMM_ATTACH_REQ(f_mi_get_lv(), rand_rai, true, false, omit, omit));
			mi := valueof(ts_MI_IMEI_LV(g_pars.imei));
			f_send_l3_gmm_llc(ts_GMM_ID_RESP(mi));
		}
	}
	f_sleep(1.0);

	/* we've sent already a IMEI answer, we should NOT asked again for IMEI */
	alt {
		[] BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_ID_REQ('001'B))) {
			mi := valueof(ts_MI_IMSI_LV(g_pars.imsi));
			f_send_l3_gmm_llc(ts_GMM_ID_RESP(mi));
			repeat;
		}
		[] BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_ID_REQ('010'B))) {
			setverdict(fail, "Unexpected GMM ID REQ (IMEI).");
			mtc.stop;
		}
		[] BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_ATTACH_REJECT(?))) {
			setverdict(fail, "Unexpected GMM ATTACH REJECT");
			mtc.stop;
		}
		[] BSSGP[0].receive(tr_BD_L3_MT(tr_GMM_ATTACH_ACCEPT('001'B, ?, ?))) -> value bd {
			f_process_attach_accept(bd.l3_mt.msgs.gprs_mm.attachAccept);
			f_send_l3_gmm_llc(ts_GMM_ATTACH_COMPL);
			setverdict(pass);
			/* FIXME: Extract P-TMSI, if any. Only send Complete if necessary */
		}
	}
}

testcase TC_attach_gmm_attach_req_while_gmm_attach() runs on test_CT {
	/* Testing if the SGSN ignore Attach Request with the exact same content */
	/* MS -> SGSN: Attach Request IMSI
	 * MS <- SGSN: Identity Request IMSI (optional)
	 * MS -> SGSN: Identity Response IMSI (optional)
	 * MS <- SGSN: Identity Request IMEI
	 * MS -> SGSN: Attach Request (2nd)
	 * MS <- SGSN: Identity Response IMEI
	 * MS <- SGSN: Attach Accept
	 * MS -> SGSN: Attach Complete
	 */
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	f_sleep(1.0);
	f_vty_config(SGSNVTY, "sgsn", "auth-policy accept-all");
	vc_conn := f_start_handler(refers(f_TC_attach_gmm_attach_req_while_gmm_attach), testcasename(), g_gb, 39);
	vc_conn.done;
}

control {
	execute( TC_attach() );
	execute( TC_attach_mnc3() );
	execute( TC_attach_umts_aka_umts_res() );
	execute( TC_attach_umts_aka_gsm_sres() );
	execute( TC_attach_auth_id_timeout() );
	execute( TC_attach_auth_sai_timeout() );
	execute( TC_attach_auth_sai_reject() );
	execute( TC_attach_gsup_lu_timeout() );
	execute( TC_attach_gsup_lu_reject() );
	execute( TC_attach_combined() );
	execute( TC_attach_accept_all() );
	execute( TC_attach_closed() );
	execute( TC_attach_no_imei_response() );
	execute( TC_attach_no_imsi_response() );
	execute( TC_attach_closed_add_vty(), 20.0 );
	execute( TC_attach_check_subscriber_list(), 20.0 );
	execute( TC_attach_detach_check_subscriber_list(), 20.0 );
	execute( TC_attach_check_complete_resend() );
	execute( TC_hlr_location_cancel_request_update(), 20.0 );
	execute( TC_hlr_location_cancel_request_withdraw(), 20.0 );
	execute( TC_hlr_location_cancel_request_unknown_subscriber_withdraw(), 20.0 );
	execute( TC_hlr_location_cancel_request_unknown_subscriber_update(), 20.0 );
	execute( TC_rau_unknown() );
	execute( TC_attach_rau() );
	execute( TC_attach_rau_a_a() );
	execute( TC_attach_rau_a_b() );
	execute( TC_detach_unknown_nopoweroff() );
	execute( TC_detach_unknown_poweroff() );
	execute( TC_detach_nopoweroff() );
	execute( TC_detach_poweroff() );
	execute( TC_attach_pdp_act() );
	execute( TC_pdp_act_unattached() );
	execute( TC_attach_pdp_act_user() );
	execute( TC_attach_pdp_act_ggsn_reject() );
	execute( TC_attach_pdp_act_user_deact_mo() );
	execute( TC_attach_pdp_act_user_deact_mt() );
	execute( TC_attach_second_attempt() );
	execute( TC_attach_restart_ctr_echo() );
	execute( TC_attach_restart_ctr_create() );
	execute( TC_attach_pdp_act_deact_mt_t3395_expire() );
	execute( TC_attach_pdp_act_user_error_ind_ggsn() );
	execute( TC_attach_gmm_attach_req_while_gmm_attach() );
}



}