aboutsummaryrefslogtreecommitdiffstats
path: root/sgsn/SGSN_Tests.ttcn
blob: 281dcc9ed199641c0ba7afcfe348e6b45af9532a (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
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
module SGSN_Tests {

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

friend module SGSN_Tests_Iu;

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 SCCPasp_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 RAN_Adapter all;
import from RAN_Emulation all;
import from RANAP_Templates all;
import from RANAP_PDU_Descriptions all;
import from RANAP_IEs 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";
	integer mp_echo_interval := 5; /* in seconds. Only used in test enabling g_use_echo  */

	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,
			role_sgsn := false,
			handle_sns := false
		},
		{
			local_udp_port := 21011,
			local_ip := "127.0.0.1",
			remote_udp_port := 23000,
			remote_ip := "127.0.0.1",
			nsvci := 98,
			nsei := 97,
			role_sgsn := false,
			handle_sns := false
		},
		{
			local_udp_port := 21012,
			local_ip := "127.0.0.1",
			remote_udp_port := 23000,
			remote_ip := "127.0.0.1",
			nsvci := 99,
			nsei := 98,
			role_sgsn := false,
			handle_sns := false
		}
	};

	RAN_Configurations mp_ranap_cfg := {
		{
			transport := RANAP_TRANSPORT_IuCS,
			sccp_service_type := "mtp3_itu",
			sctp_addr := { 23908, "127.0.0.1", 2905, "127.0.0.1" },
			own_pc := 195,
			own_ssn := 142,
			peer_pc := 188, /* 0.23.4 */
			peer_ssn := 142,
			sio := '83'O,
			rctx := 2
		}
	}
};

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

const integer NUM_GB := 3;
type record length(NUM_GB) of GbInstance GbInstances;
type record length(NUM_GB) of NSConfiguration NSConfigurations;
type record length(NUM_GB) of BssgpCellId BssgpCellIds;

const integer NUM_RNC := 1;
type record of RAN_Configuration RAN_Configurations;

type component test_CT {
	var GbInstances g_gb;
	var RAN_Adapter g_ranap[NUM_RNC];
	var boolean g_ranap_enable := false;

	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, RAN_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,
	/* Tracks the RNC state. If true next L3 message will be sent with InitiualUe */
	boolean rnc_send_initial_ue,
	AuthVector vec optional,
	SGSN_ConnHdlrNetworkPars net,
	float t_guard,
	/* only in IuPS / RANAP case */
	SCCP_PAR_Address sccp_addr_local optional,
	SCCP_PAR_Address sccp_addr_peer optional
};

private function f_cellid_to_RAI(in BssgpCellId cell_id) return RoutingAreaIdentificationV {
	/* mcc_mnc is encoded as of 24.008 10.5.5.15 */
	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[3],
                mncDigit1 := mcc_mnc[4],
                mncDigit2 := mcc_mnc[5],
                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 " & int2str(mp_echo_interval));
	} else {
		f_vty_config(SGSNVTY, "sgsn", "ggsn 0 no echo-interval");
	}
}


/* mcc_mnc is 24.008 10.5.5.15 encoded. 262 42 */
function f_init(BcdMccMnc mcc_mnc := '262F42'H) runs on test_CT {
	var integer i;

	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,
		depth := BSSGP_DECODE_DEPTH_L3
	};
	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,
		depth := BSSGP_DECODE_DEPTH_L3
	};
	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,
		depth := BSSGP_DECODE_DEPTH_L3
	};

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

	if (g_ranap_enable) {
		for (i := 0; i < NUM_RNC; i := i+1) {
			f_ran_adapter_init(g_ranap[i], mp_ranap_cfg[i], "SGSN_Test_" & int2str(i), RNC_RanOps);
			f_ran_adapter_start(g_ranap[i]);
		}
	}
	f_init_gsup("SGSN_Test");
	f_init_gtp("SGSN_Test");
	f_vty_enable_echo_interval(g_use_echo);
}

function f_cleanup() runs on test_CT {
	var integer i;
	if (g_ranap_enable) {
		for (i := 0; i < NUM_RNC; i := i+1) {
			f_ran_adapter_cleanup(g_ranap[i]);
		}
	}
	self.stop;
}

private function RncUnitdataCallback(RANAP_PDU ranap)
runs on RAN_Emulation_CT return template RANAP_PDU {
	var template RANAP_PDU resp := omit;

	log ("RANAP_RncUnitDataCallback");
	/* answer all RESET with RESET ACK */
	if (match(ranap, tr_RANAP_Reset)) {
		log("RANAP_RncUnitdataCallback: Responding to RESET with RESET-ACK");
		var CN_DomainIndicator dom;
		dom := ranap.initiatingMessage.value_.Reset.protocolIEs[1].value_.cN_DomainIndicator;
		resp := ts_RANAP_ResetAck(dom);
	}
	return resp;
}

const RanOps RNC_RanOps := {
	ranap_create_cb := refers(RAN_Emulation.RanapExpectedCreateCallback),
	ranap_unitdata_cb := refers(RncUnitdataCallback),
	ps_domain := true,
	decode_dtap := true,
	role_ms := true,
	protocol := RAN_PROTOCOL_RANAP,
	transport := RANAP_TRANSPORT_IuCS,
	use_osmux := false,
	sccp_addr_local := omit,
	sccp_addr_peer := omit
};

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 },
		rnc_send_initial_ue := true,
		vec := omit,
		net := net_pars,
		t_guard := t_guard,
		sccp_addr_local := omit,
		sccp_addr_peer := omit
	};

	if (g_ranap_enable) {
		pars.sccp_addr_local := g_ranap[0].sccp_addr_own;
		pars.sccp_addr_peer := g_ranap[0].sccp_addr_peer;
	}

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

	/* FIXME: support multiple RNCs */
	if (g_ranap_enable) {
		connect(vc_conn:BSSAP, g_ranap[0].vc_RAN:CLIENT);
		connect(vc_conn:BSSAP_PROC, g_ranap[0].vc_RAN: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);
	f_cleanup();
}

friend function is_gb(integer ran_index) return boolean {
	return ran_index < NUM_GB;
}
friend function is_iu(integer ran_index) return boolean {
	return ran_index >= NUM_GB;
}

function f_send_llc(template (value) PDU_LLC llc_pdu, integer ran_index := 0) runs on BSSGP_ConnHdlr {
	var octetstring llc_enc := enc_PDU_LLC(valueof(llc_pdu));
	BSSGP[ran_index].send(ts_BSSGP_UL_UD(g_pars.tlli, g_pars.bssgp_cell_id[ran_index], llc_enc));
}

private function f_send_l3_gmm_llc(template (value) PDU_L3_MS_SGSN l3_mo, integer ran_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)]);
	f_send_llc(ts_LLC_UI(l3_enc, sapi, '0'B, n_u), ran_index);
}

/* trigger sending of a RANAP InitialUE and wait for SCCP connection confirmation */
function f_send_l3_initial_ue(template (value) PDU_L3_MS_SGSN l3_mo) runs on BSSGP_ConnHdlr {
	log("Sending InitialUE: ", l3_mo);
	var octetstring l3_enc := enc_PDU_L3_MS_SGSN(valueof(l3_mo));
	var RANAP_PDU ranap;
	var LAI lai := {
		pLMNidentity := '62F224'O,
		lAC := '1234'O,
		iE_Extensions := omit
	};
	var SAI sai := {
		pLMNidentity := lai.pLMNidentity,
		lAC := lai.lAC,
		sAC := '0000'O, /* FIXME */
		iE_Extensions := omit
	};
	var IuSignallingConnectionIdentifier sigc_id := int2bit(23, 24); /* FIXME */
	var GlobalRNC_ID grnc_id := {
		pLMNidentity := lai.pLMNidentity,
		rNC_ID := 2342 /* FIXME */
	};

	ranap := valueof(ts_RANAP_initialUE_CS(lai, sai, l3_enc, sigc_id, grnc_id));
	BSSAP.send(ts_RANAP_Conn_Req(g_pars.sccp_addr_peer, g_pars.sccp_addr_local, ranap));
	alt {
	[] BSSAP.receive(RAN_Conn_Prim:MSC_CONN_PRIM_CONF_IND) {}
	[] BSSAP.receive(RAN_Conn_Prim:MSC_CONN_PRIM_DISC_IND) {
		setverdict(fail, "DISC.ind from SCCP");
		mtc.stop;
		}
	}
}

/* send a L3 (GMM/SM) message over whatever is the appropriate lower-layer bearer */
function f_send_l3(template (value) PDU_L3_MS_SGSN l3_mo, integer ran_index := 0) runs on BSSGP_ConnHdlr {
	if (is_iu(ran_index)) {
		if (g_pars.rnc_send_initial_ue) {
			g_pars.rnc_send_initial_ue := false;
			f_send_l3_initial_ue(l3_mo);
		} else {
			BSSAP.send(ts_PDU_DTAP_PS_MO(l3_mo));
		}
	} else {
		f_send_l3_gmm_llc(l3_mo, ran_index);
	}
}

altstep as_mm_identity(integer ran_index := 0) runs on BSSGP_ConnHdlr {
	var MobileL3_CommonIE_Types.MobileIdentityLV mi;
	[is_gb(ran_index)] BSSGP[ran_index].receive(tr_GMM_ID_REQ('001'B)) {
		mi := valueof(ts_MI_IMSI_LV(g_pars.imsi));
		f_send_l3(ts_GMM_ID_RESP(mi), ran_index);
		repeat;
	}
	[is_iu(ran_index)] BSSAP.receive(tr_PDU_DTAP_PS_MT(tr_GMM_ID_REQ('001'B))) {
		mi := valueof(ts_MI_IMSI_LV(g_pars.imsi));
		f_send_l3(ts_GMM_ID_RESP(mi), ran_index);
		repeat;
	}
	[is_gb(ran_index)] BSSGP[ran_index].receive(tr_GMM_ID_REQ('010'B)) {
		mi := valueof(ts_MI_IMEI_LV(g_pars.imei));
		f_send_l3(ts_GMM_ID_RESP(mi), ran_index);
		repeat;
	}
	[is_iu(ran_index)] BSSAP.receive(tr_PDU_DTAP_PS_MT(tr_GMM_ID_REQ('010'B))) {
		mi := valueof(ts_MI_IMEI_LV(g_pars.imei));
		f_send_l3(ts_GMM_ID_RESP(mi), ran_index);
		repeat;
	}
}

/* receive a L3 (GMM/SM) message over whatever is the appropriate lower-layer bearer */
function f_receive_l3(template PDU_L3_SGSN_MS rx_tpl := ?, integer ran_index := 0)
runs on BSSGP_ConnHdlr return PDU_L3_SGSN_MS {
	var PDU_DTAP_PS_MT mt;
	var PDU_L3_SGSN_MS l3_mt;
	alt {
	[is_gb(ran_index)] BSSGP[ran_index].receive(rx_tpl) -> value l3_mt { }
	[is_iu(ran_index)] BSSAP.receive(tr_PDU_DTAP_PS_MT(rx_tpl)) -> value mt {
		l3_mt := mt.dtap;
		}
	}
	return l3_mt;
}

/* 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, integer ran_index := 0) runs on BSSGP_ConnHdlr {
	var PDU_L3_MS_SGSN l3_mo;
	var PDU_L3_SGSN_MS l3_mt;
	var default di := activate(as_mm_identity(ran_index));
	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;
		l3_mt := f_receive_l3(auth_ciph_req, ran_index);
		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(l3_mo, ran_index);

		/* Security Mode Command + Complete on Iu case */
		if (is_iu(ran_index)) {
			BSSAP.receive(tr_RANAP_SecurityModeCmd(uia_algs := ?, uia_key := oct2bit(g_pars.vec.ik),
								key_sts := ?)) {
				var IntegrityProtectionAlgorithm uia_chosen := 0; /* 0 = standard_UMTS_integrity_algorithm_UIA1 */
				BSSAP.send(ts_RANAP_SecurityModeComplete(uia_chosen));
				BSSAP.receive(tr_RANAP_CommonId(imsi_hex2oct(g_pars.imsi)))
			}
		}
	} else {
		/* wait for identity procedure */
		f_sleep(1.0);
	}

	deactivate(di);
}

function f_upd_ptmsi_and_tlli(OCT4 p_tmsi, integer ran_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[ran_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 ran_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, ran_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));
}

friend function f_gmm_attach(boolean umts_aka_challenge, boolean force_gsm_sres, integer ran_index := 0) runs on BSSGP_ConnHdlr {
	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);
	var PDU_L3_SGSN_MS l3_mt;

	/* 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(attach_req, ran_index);
	f_gmm_auth(umts_aka_challenge, force_gsm_sres, ran_index);
	/* Expect SGSN to perform LU with HLR */
	f_gmm_gsup_lu_isd();

	l3_mt := f_receive_l3(tr_GMM_ATTACH_ACCEPT('001'B, ?, ?), ran_index);
	f_process_attach_accept(l3_mt.msgs.gprs_mm.attachAccept);

	/* FIXME: Extract P-TMSI, if any. Only send Complete if necessary */
	f_send_l3(ts_GMM_ATTACH_COMPL, ran_index);

	/* IuPS case: Expect Iu Release */
	if (is_iu(ran_index)) {
		as_iu_release_compl_disc();
	}
}

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

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

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

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

/* 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(ts_GMM_ATTACH_REQ(f_mi_get_lv(), old_ra, false, false, omit, omit));
	alt {
	[] BSSGP[0].receive(tr_GMM_ID_REQ(?)) {
		/* don't send ID Response */
		repeat;
		}
	[] BSSGP[0].receive(tr_GMM_ATTACH_REJECT('09'O)) {
		setverdict(pass);
		}
	[] BSSGP[0].receive(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;
	f_cleanup();
}

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

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

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

	f_send_l3(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_GMM_ATTACH_REJECT(?)) {
		setverdict(pass);
		}
	[] BSSGP[0].receive(tr_GMM_ATTACH_ACCEPT('001'B, ?, ?)) -> value l3_mt {
		f_process_attach_accept(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;
	f_cleanup();
}

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

	f_send_l3(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_GMM_ATTACH_REJECT(?)) {
		setverdict(pass);
		}
	[] BSSGP[0].receive(tr_GMM_ATTACH_ACCEPT('001'B, ?, ?)) -> value l3_mt {
		f_process_attach_accept(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;
	f_cleanup();
}


/* 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 PDU_L3_SGSN_MS l3_mt;
	var RoutingAreaIdentificationV old_ra := f_random_RAI();

	f_send_l3(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_GMM_ATTACH_ACCEPT('001'B, ?, ?)) -> value l3_mt {
		f_process_attach_accept(l3_mt.msgs.gprs_mm.attachAccept);
	}
	f_send_l3(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;
	f_cleanup();
}

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

	g_pars.net.expect_auth := false;

	f_send_l3(ts_GMM_ATTACH_REQ(f_mi_get_lv(), old_ra, false, false, omit, omit));
	f_gmm_auth();
	BSSGP[0].receive(tr_GMM_ATTACH_ACCEPT('001'B, ?, ?)) -> value l3_mt {
		f_process_attach_accept(l3_mt.msgs.gprs_mm.attachAccept);
	}
	f_send_l3(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;
	f_cleanup();
}

/* 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(ts_GMM_ATTACH_REQ(f_mi_get_lv(), old_ra, false, false, omit, omit));
	alt {
	[] as_mm_identity();
	[] BSSGP[0].receive(tr_GMM_ATTACH_REJECT('07'O)) {
		setverdict(pass);
		}
	[] BSSGP[0].receive(tr_GMM_ATTACH_REJECT(?)) {
		setverdict(pass);
		}
	[] BSSGP[0].receive(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;
	f_cleanup();
}

/* 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(ts_GMM_RAU_REQ(f_mi_get_lv(), GPRS_UPD_T_RA, old_ra, false, omit, omit));
	alt {
	[] BSSGP[0].receive(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;
	f_cleanup();
}

private function f_TC_attach_rau(charstring id) runs on BSSGP_ConnHdlr {
	/* 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;
	f_cleanup();
}

/* general GPRS DETACH helper */
function f_detach_mo(BIT3 detach_type, boolean power_off, boolean expect_purge, integer ran_index := 0) runs on BSSGP_ConnHdlr {
	var PDU_L3_SGSN_MS l3_mt;
	timer T := 5.0;
	f_send_l3(ts_GMM_DET_REQ_MO(detach_type, power_off), ran_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[ran_index].receive(tr_GMM_DET_ACCEPT_MT) -> value l3_mt {
		g_pars.ra := omit;
		setverdict(fail, "Unexpected DETACH ACCEPT in 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[ran_index].receive(tr_GMM_DET_ACCEPT_MT) -> value l3_mt {
		g_pars.ra := omit;
		setverdict(pass);
		/* TODO: check if any PDP contexts are deactivated on network side? */
		}
	[] BSSGP[ran_index].receive(PDU_L3_SGSN_MS:?) -> value l3_mt {
		if (power_off) {
			setverdict(fail, "Unexpected Layer 3 package received in power-off DETACH");
		} else {
			setverdict(fail, "Unexpected Layer 3 package received in normal DETACH");
		}
		mtc.stop;
		}
	[] BSSGP[ran_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;
	f_cleanup();
}

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

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

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

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, integer ran_index := 0)
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(ts_SM_ACT_PDP_REQ(apars.tid, apars.nsapi, apars.sapi, apars.qos, apars.addr,
				     apars.apn, apars.pco), ran_index);
	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[ran_index].receive(tr_SM_ACT_PDP_REJ(apars.tid, apars.exp_rej_cause)) {
		setverdict(pass);
		}
	[exp_rej] BSSGP[ran_index].receive(tr_SM_ACT_PDP_ACCEPT) {
		setverdict(fail, "Unexpected PDP CTX ACT ACC");
		mtc.stop;
		}
	[not exp_rej] BSSGP[ran_index].receive(tr_SM_ACT_PDP_REJ(apars.tid, ?)) {
		setverdict(fail, "Unexpected PDP CTX ACT FAIL");
		mtc.stop;
		}
	[not exp_rej] BSSGP[ran_index].receive(tr_SM_ACT_PDP_REJ(apars.tid, ?)) {
		setverdict(fail, "Unexpected PDP CTX ACT FAIL");
		mtc.stop;
		}
	[not exp_rej] BSSGP[ran_index].receive(tr_SM_ACT_PDP_ACCEPT(apars.tid, apars.sapi)) {
		setverdict(pass);
		}
	[] as_xid(apars, ran_index);
	}
}

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

	f_send_l3(ts_SM_DEACT_PDP_REQ_MO(apars.tid, cause, false, omit), ran_index);
	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[ran_index].clear;
		GTP.send(ts_GTPC_DeletePdpResp(g_ud.peer, seq_nr, apars.sgsn_tei_c, '7F'O));
	}
	alt {
	[] BSSGP[ran_index].receive(tr_SM_DEACT_PDP_ACCEPT_MT(apars.tid)) {
		setverdict(pass);
		}
	[] as_xid(apars, ran_index);
	}
}

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

	BSSGP[ran_index].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[ran_index].receive(tr_SM_DEACT_PDP_REQ_MT(apars.tid, ?, true)) {
		f_send_l3(ts_SM_DEACT_PDP_ACCEPT_MO(apars.tid), ran_index);
		}
	[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, integer ran_index := 0) runs on BSSGP_ConnHdlr {
	[] BSSGP[ran_index].receive(tr_LLC_XID_MT_CMD(?, 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, integer ran_index := 0)
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, ran_index);
	//[] BSSGP[ran_index].receive(tr_BD_SNDCP(apars.sapi, tr_SN_UD(apars.nsapi, payload)));
	[] BSSGP[ran_index].receive(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, integer ran_index := 0)
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[ran_index].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;
	f_cleanup();
}

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

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

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

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

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

/* Test MS sending a duplicate Deact PDP Ctx (OS#3956). */
private function f_TC_attach_pdp_act_deact_dup(charstring id) runs on BSSGP_ConnHdlr {
	var PdpActPars apars := valueof(t_PdpActPars(mp_ggsn_ip));
	var Gtp1cUnitdata g_ud;
	var integer i;
	var OCT1 cause_regular_deact := '24'O;

	/* first perform regular attach + PDP context act */
	f_TC_attach(id);
	f_pdp_ctx_act(apars);

	f_send_l3_gmm_llc(ts_SM_DEACT_PDP_REQ_MO(apars.tid, cause_regular_deact, false, omit), 0);
	f_send_l3_gmm_llc(ts_SM_DEACT_PDP_REQ_MO(apars.tid, cause_regular_deact, false, omit), 0);

	for (i := 0; i < 2; i := i+1) {
		GTP.receive(tr_GTPC_MsgType(?, deletePDPContextRequest, apars.ggsn_tei_c)) -> value g_ud {
			var integer seq_nr := oct2int(g_ud.gtpc.opt_part.sequenceNumber);
			log("Received deletePDPContextResponse " & int2str(i) & ", seq_nr=" & int2str(seq_nr));
			GTP.send(ts_GTPC_DeletePdpResp(g_ud.peer, seq_nr, apars.sgsn_tei_c, '7F'O));
		}
	}

	alt {
	[] BSSGP[0].receive(tr_SM_DEACT_PDP_ACCEPT_MT(apars.tid)) {
		setverdict(pass);
		}
	[] as_xid(apars, 0);
	}

	/* Make sure second DeactPdpAccept is sent: */
	timer T := 2.0;
	T.start;
	alt {
	[] BSSGP[0].receive(tr_SM_DEACT_PDP_ACCEPT_MT(apars.tid)) {
		setverdict(fail, "Second SM_DEACT_PDP_ACCEPT_MT received");
		}
	[] T.timeout {
		setverdict(pass);
		}
	}

	setverdict(pass);
}
testcase TC_attach_pdp_act_deact_dup() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_TC_attach_pdp_act_deact_dup), testcasename(), g_gb, 46);
	vc_conn.done;
	f_cleanup();
}

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

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

	/* first perform regular attach */
	f_TC_attach(id);
	/* then activate PDP context */
	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 {
		BSSGP[0].clear;
		seq_nr := oct2int(g_ud.gtpc.opt_part.sequenceNumber);
		GTP.send(ts_GTPC_PONG(g_ud.peer, seq_nr, apars.ggsn_restart_ctr));
		f_sleep(int2float(mp_echo_interval)); /* wait until around next echo is expected */
	}

	/* At some point next echo request not answered will timeout and SGSN
	   should drop the pdp ctx. Around T3 (3secs) * 6 (+ extra, a lot due to OS#4178): */
	timer T := 3.0 * 6.0 + 16.0;
	T.start;
	alt {
		[] BSSGP[0].receive(tr_SM_DEACT_PDP_REQ_MT(apars.tid, ?, true)) {
			f_send_l3_gmm_llc(ts_SM_DEACT_PDP_ACCEPT_MO(apars.tid));
			setverdict(pass);
		}
		[] GTP.receive(tr_GTPC_MsgType(?, deletePDPContextRequest, apars.ggsn_tei_c)) -> value g_ud {
			/* SGSN currently doesn't send this message because it expects GGSN to be non-reachable anyway */
			seq_nr := oct2int(g_ud.gtpc.opt_part.sequenceNumber);
			log("Received deletePDPContextRequest seq_nr=" & int2str(seq_nr));
			GTP.send(ts_GTPC_DeletePdpResp(g_ud.peer, seq_nr, apars.sgsn_tei_c, '7F'O));
			repeat;
		}
		[] GTP.receive(tr_GTPC_MsgType(?, echoRequest, ?)) -> value g_ud {
			seq_nr := oct2int(g_ud.gtpc.opt_part.sequenceNumber);
			log("Received EchoRequest seq_nr=" & int2str(seq_nr));
			repeat;
		}
		[] T.timeout {
			setverdict(fail, "BSSGP DeactPdpReq not received");
			mtc.stop;
		}
		[] as_xid(apars);
	}
	T.stop

	setverdict(pass);
}
/* ATTACH + trigger Recovery procedure through CreatePdpResp */
testcase TC_attach_echo_timeout() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	g_use_echo := true;
	f_init();
	vc_conn := f_start_handler(refers(f_TC_attach_echo_timeout), testcasename(), g_gb, 67, 50.0);
	vc_conn.done;
	g_use_echo := false;
	f_cleanup();
}

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_SM_DEACT_PDP_REQ_MT(apars.tid, cause_network_failure, true)) {
		f_send_l3(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
	f_cleanup();
}

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

/* 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_SM_DEACT_PDP_REQ_MT(apars.tid, ?, true)) {}
			[] as_xid(apars);
		}
	}

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

	f_send_l3(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;
	f_cleanup();
}

/* ATTACH + PDP CTX ACT dropped + retrans */
private function f_TC_attach_pdp_act_deact_gtp_retrans(charstring id) runs on BSSGP_ConnHdlr {
	var PdpActPars apars := valueof(t_PdpActPars(mp_ggsn_ip));
	var Gtp1cUnitdata g_ud_first, g_ud_second;
	/* first perform regular attach */
	f_TC_attach(id);

	/* then activate PDP context on the Gb side */
	f_send_l3_gmm_llc(ts_SM_ACT_PDP_REQ(apars.tid, apars.nsapi, apars.sapi, apars.qos, apars.addr,
				     apars.apn, apars.pco), 0);

	GTP.receive(tr_GTPC_MsgType(?, createPDPContextRequest, ?)) -> value g_ud_first {}
	log("First createPDPContextRequest received, dropping & waiting for retransmission");
	GTP.receive(tr_GTPC_MsgType(?, createPDPContextRequest, ?)) -> value g_ud_second {
		if (g_ud_first != g_ud_second) {
			setverdict(fail, "Retransmitted GTP message createPDPContextRequest is different from original one!");
			mtc.stop;
		}
		f_process_gtp_ctx_act_req(apars, g_ud_second.gtpc);
		var integer seq_nr := oct2int(g_ud_second.gtpc.opt_part.sequenceNumber);
		GTP.send(ts_GTPC_CreatePdpResp(g_ud_second.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, omit));
	}
	BSSGP[0].receive(tr_SM_ACT_PDP_ACCEPT) {}

	/* Now the same with Deact */
	f_send_l3_gmm_llc(ts_SM_DEACT_PDP_REQ_MO(apars.tid, '00'O, false, omit), 0);
	GTP.receive(tr_GTPC_MsgType(?, deletePDPContextRequest, apars.ggsn_tei_c)) -> value g_ud_first {}
	log("First deletePDPContextRequest received, dropping & waiting for retransmission");
	GTP.receive(tr_GTPC_MsgType(?, deletePDPContextRequest, apars.ggsn_tei_c)) -> value g_ud_second {
		if (g_ud_first != g_ud_second) {
			setverdict(fail, "Retransmitted GTP message deletePDPContextRequest is different from original one!");
			mtc.stop;
		}
		var integer seq_nr := oct2int(g_ud_second.gtpc.opt_part.sequenceNumber);
		BSSGP[0].clear;
		GTP.send(ts_GTPC_DeletePdpResp(g_ud_second.peer, seq_nr, apars.sgsn_tei_c, '7F'O));
	}
	alt {
	[] BSSGP[0].receive(tr_SM_DEACT_PDP_ACCEPT_MT(apars.tid)) {
		setverdict(pass);
		}
	[] as_xid(apars, 0);
	}

	setverdict(pass);
}
testcase TC_attach_pdp_act_deact_gtp_retrans() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_TC_attach_pdp_act_deact_gtp_retrans), testcasename(), g_gb, 27);
	vc_conn.done;
	f_cleanup();
}

/* Test that SGSN GTP response retransmit queue works fine */
private function f_TC_attach_pdp_act_deact_gtp_retrans_resp(charstring id) runs on BSSGP_ConnHdlr {
	var PdpActPars apars := valueof(t_PdpActPars(mp_ggsn_ip));
	var integer seq_nr := 23;
	var Gtp1cUnitdata g_ud_first, g_ud_second;
	var template Gtp1cUnitdata g_delete_req;
	/* first perform regular attach + PDP context act */
	f_TC_attach(id);
	f_pdp_ctx_act(apars);

	/* Now perform an MT DeleteCtxReq and emulate GGSN didn't receive response and sends a duplicated DeleteCtxReq */
	BSSGP[0].clear;
	var GtpPeer peer := valueof(ts_GtpPeerC(apars.sgsn_ip_c));
	g_delete_req := ts_GTPC_DeletePDP(peer, seq_nr, apars.sgsn_tei_c, apars.nsapi, '1'B);
	GTP.send(g_delete_req);
	alt {
	[] BSSGP[0].receive(tr_SM_DEACT_PDP_REQ_MT(apars.tid, ?, true)) {
			f_send_l3_gmm_llc(ts_SM_DEACT_PDP_ACCEPT_MO(apars.tid), 0);
		}
	[] as_xid(apars, 0);
	}
	GTP.receive(tr_GTPC_MsgType(?, deletePDPContextResponse, apars.ggsn_tei_c)) -> value g_ud_first {
		if (g_ud_first.gtpc.gtpc_pdu.deletePDPContextResponse.cause.causevalue != '80'O) {
			setverdict(fail, "Received deletePDPContextResponse cause is not 'Request accepted'");
			mtc.stop;
		}
	};

	/* Send duplicate DeleteCtxReq */
	log("First deletePDPContextResponse received, dropping & retransmitting retransmission of deletePDPContextRequest");
	GTP.send(g_delete_req);
	GTP.receive(tr_GTPC_MsgType(?, deletePDPContextResponse, apars.ggsn_tei_c)) -> value g_ud_second {
		if (g_ud_first != g_ud_second) {
			setverdict(fail, "Retransmitted GTP message deletePDPContextResponse is different from original one!");
			mtc.stop;
		}
	}

	/* Let's send now a new DeleteCtxReq (increased seq_nr) to make sure it
	 * is handled differently by SGSN (expect "non-existent" cause) */
	g_delete_req := ts_GTPC_DeletePDP(peer, seq_nr + 1, apars.sgsn_tei_c, apars.nsapi, '1'B);
	GTP.send(g_delete_req);
	/* Response with cause "non-existent" must be sent with TEID 0 according to specs */
	GTP.receive(tr_GTPC_MsgType(?, deletePDPContextResponse, '00000000'O)) -> value g_ud_second {
		if (g_ud_second.gtpc.gtpc_pdu.deletePDPContextResponse.cause.causevalue != 'C0'O) {
			setverdict(fail, "Received deletePDPContextResponse cause is not 'Non-existent'");
			mtc.stop;
		}
	}

	setverdict(pass);
}
testcase TC_attach_pdp_act_deact_gtp_retrans_resp() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_TC_attach_pdp_act_deact_gtp_retrans_resp), testcasename(), g_gb, 28);
	vc_conn.done;
	f_cleanup();
}

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_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;
	f_cleanup();
}

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


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_GMM_DET_REQ_MT(c_GMM_DTT_MT_IMSI_DETACH, ?, ?));
	f_send_l3(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;
	f_cleanup();
}


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

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

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

/* 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(ts_GMM_ATTACH_REQ(f_mi_get_lv(), f_random_RAI(), true, false, omit, omit));

	alt {
		[] BSSGP[0].receive(tr_GMM_ATTACH_REJECT(?)) {
			/* break */
		}
		[] BSSGP[0].receive(tr_GMM_ID_REQ('001'B)) {
			mi := valueof(ts_MI_IMSI_LV(g_pars.imsi));
			f_send_l3(ts_GMM_ID_RESP(mi));
			repeat;
		}
		[] BSSGP[0].receive(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;
	f_cleanup();
}

/* 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(ts_GMM_ATTACH_REQ(f_mi_get_lv(), f_random_RAI(), true, false, omit, omit));

	alt {
		[] BSSGP[0].receive(tr_GMM_ATTACH_REJECT(?)) {
			/* break */
		}
		[] BSSGP[0].receive(tr_GMM_ID_REQ('001'B)) {
			/* ignore ID REQ IMSI */
			count_req := count_req + 1;
			repeat;
		}
		[] BSSGP[0].receive(tr_GMM_ID_REQ('010'B)) {
			mi := valueof(ts_MI_IMEI_LV(g_pars.imei));
			f_send_l3(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;
	f_cleanup();
}

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

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

	/* 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(ts_GMM_ATTACH_REQ(f_mi_get_lv(), old_ra, false, false, omit, omit));
	f_gmm_auth();
	alt {
		[] BSSGP[0].receive(tr_GMM_ATTACH_REJECT(?)) {
			setverdict(fail, "Received unexpected GMM Attach REJECT");
			mtc.stop;
		}
		[] BSSGP[0].receive(tr_GMM_ATTACH_ACCEPT(*, *, *)) -> value l3_mt {
			f_process_attach_accept(l3_mt.msgs.gprs_mm.attachAccept);
			f_send_l3(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;
	f_cleanup();
}

/* 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(ts_GMM_ATTACH_REQ(f_mi_get_lv(), f_random_RAI(), true, false, omit, omit));
	f_gmm_auth();
	/* Expect SGSN to perform LU with HLR */
	f_gmm_gsup_lu_isd();

	timer T := 10.0;
	T.start;
	alt {
		[] T.timeout {
			/* break */
		}
		[] BSSGP[0].receive(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;
	f_cleanup();
}

friend function f_routing_area_update(RoutingAreaIdentificationV ra, integer ran_index := 0) runs on BSSGP_ConnHdlr {
	var PDU_L3_SGSN_MS l3_mt;
	var PDU_DTAP_PS_MT mt;
	var template OCT4 p_tmsi := omit;

	if (is_iu(ran_index)) {
		p_tmsi := g_pars.p_tmsi;
	}
	/* then send RAU */
	f_send_l3(ts_GMM_RAU_REQ(f_mi_get_lv(), GPRS_UPD_T_RA, g_pars.ra, false, omit, omit, p_tmsi), ran_index);
	alt {
	[is_gb(ran_index)] BSSGP[ran_index].receive(tr_GMM_RAU_ACCEPT) -> value l3_mt {
		f_process_rau_accept(l3_mt.msgs.gprs_mm.routingAreaUpdateAccept, ran_index);
		f_send_l3(ts_GMM_RAU_COMPL, ran_index);
		setverdict(pass);
		}
	[is_iu(ran_index)] BSSAP.receive(tr_PDU_DTAP_PS_MT(tr_GMM_RAU_ACCEPT)) -> value mt {
		f_process_rau_accept(mt.dtap.msgs.gprs_mm.routingAreaUpdateAccept, ran_index);
		f_send_l3(ts_GMM_RAU_COMPL, ran_index);
		setverdict(pass);
		}

	[is_gb(ran_index)] BSSGP[ran_index].receive(tr_GMM_RAU_REJECT) {
		setverdict(fail, "Unexpected RAU Reject");
		mtc.stop;
		}
	[is_iu(ran_index)] BSSAP.receive(tr_PDU_DTAP_PS_MT(tr_GMM_RAU_REJECT)) {
		setverdict(fail, "Unexpected RAU Reject");
		mtc.stop;
		}

	[is_iu(ran_index)] BSSAP.receive(tr_RANAP_SecurityModeCmd(uia_algs := ?, uia_key := oct2bit(g_pars.vec.ik),
								key_sts := ?)) {
			var IntegrityProtectionAlgorithm uia_chosen := 0; /* 0 = standard_UMTS_integrity_algorithm_UIA1 */
			BSSAP.send(ts_RANAP_SecurityModeComplete(uia_chosen));
			BSSAP.receive(tr_RANAP_CommonId(imsi_hex2oct(g_pars.imsi)))
		}
	[is_gb(ran_index)] BSSGP[ran_index].receive { repeat; }
	[is_iu(ran_index)] BSSAP.receive { repeat; }
	}
}

private function f_TC_attach_rau_a_a(charstring id) runs on BSSGP_ConnHdlr {
	/* 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;
	f_cleanup();
}

private function f_TC_attach_rau_a_b(charstring id) runs on BSSGP_ConnHdlr {
	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;
	f_cleanup();
}

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 PDU_L3_SGSN_MS l3_mt;

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

	alt {
		[] BSSGP[0].receive(tr_GMM_ATTACH_REJECT(?)) {
			setverdict(fail, "Unexpected GMM ATTACH REJECT");
			mtc.stop;
		}
		[] BSSGP[0].receive(tr_GMM_ID_REQ('001'B)) {
			mi := valueof(ts_MI_IMSI_LV(g_pars.imsi));
			f_send_l3(ts_GMM_ID_RESP(mi));
			repeat;
		}
		[] BSSGP[0].receive(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(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(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_GMM_ID_REQ('001'B)) {
			mi := valueof(ts_MI_IMSI_LV(g_pars.imsi));
			f_send_l3(ts_GMM_ID_RESP(mi));
			repeat;
		}
		[] BSSGP[0].receive(tr_GMM_ID_REQ('010'B)) {
			setverdict(fail, "Unexpected GMM ID REQ (IMEI).");
			mtc.stop;
		}
		[] BSSGP[0].receive(tr_GMM_ATTACH_REJECT(?)) {
			setverdict(fail, "Unexpected GMM ATTACH REJECT");
			mtc.stop;
		}
		[] BSSGP[0].receive(tr_GMM_ATTACH_ACCEPT('001'B, ?, ?)) -> value l3_mt {
			f_process_attach_accept(l3_mt.msgs.gprs_mm.attachAccept);
			f_send_l3(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;
	f_cleanup();
}

private function f_TC_attach_usim_resync(charstring id) runs on BSSGP_ConnHdlr {
	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);

	/* send Attach Request */
	/* 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(attach_req);

	/* do the auth */
	var PDU_L3_MS_SGSN l3_mo;
	var PDU_L3_SGSN_MS l3_mt;
	var default di := activate(as_mm_identity());

	var GSUP_IE auth_tuple;
	var template AuthenticationParameterAUTNTLV autn;

	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);
	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(auth_ciph_req) -> value l3_mt;

	/* send the gmm auth failure with resync IE */
	f_send_l3(ts_GMM_AUTH_FAIL_UMTS_AKA_RESYNC(g_pars.vec.auts));

	/* wait for the GSUP resync request */
	GSUP.receive(tr_GSUP_SAI_REQ_UMTS_AKA_RESYNC(
		g_pars.imsi,
		g_pars.vec.auts,
		g_pars.vec.rand));

	/* generate new key material */
	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));
	/* send new key material */
	GSUP.send(ts_GSUP_SAI_RES(g_pars.imsi, auth_tuple));

	/* wait for the new Auth Request */
	auth_ciph_req := tr_GMM_AUTH_REQ(g_pars.vec.rand);
	auth_ciph_req.msgs.gprs_mm.authenticationAndCipheringRequest.authenticationParameterAUTN := autn;
	BSSGP[0].receive(auth_ciph_req) -> value 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);
	auth_ciph_resp := ts_GMM_AUTH_RESP_2G(ac_ref, g_pars.vec.sres);
	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(l3_mo);
	deactivate(di);

	/* Expect SGSN to perform LU with HLR */
	f_gmm_gsup_lu_isd();

	BSSGP[0].receive(tr_GMM_ATTACH_ACCEPT('001'B, ?, ?)) -> value l3_mt {
		f_process_attach_accept(l3_mt.msgs.gprs_mm.attachAccept);
	}
	f_send_l3(ts_GMM_ATTACH_COMPL);
	setverdict(pass);
}

testcase TC_attach_usim_resync() runs on test_CT {
	/* MS -> SGSN: Attach Request
	 * MS <- SGSN: Identity Request IMSI
	 * MS -> SGSN: Identity Response IMSI
	 * MS <- SGSN: Identity Request IMEI
	 * MS -> SGSN: Identity Response IMEI
	 * HLR<- SGSN: SAI Request
	 * HLR-> SGSN: SAI Response
	 * MS <- SGSN: Auth Request
	 * MS -> SGSN: Auth Failure (with AUTS)
	 * HLR<- SGSN: SAI Request (with AUTS & RAND)
	 * HLR-> SGSN: SAI Response (new key material)
	 * MS <- SGSN: Auth Request (new key material)
	 * MS -> SGSN: Auth Response
	 * MS <- SGSN: Attach Accept
	 * MS -> SGSN: Attach Complete
	 */
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_TC_attach_usim_resync), testcasename(), g_gb, 40);
	vc_conn.done;
	f_cleanup();
}


/* Send LLC NULL to see if the SGSN survives it (OS#3952) */
private function f_TC_llc_null(charstring id) runs on BSSGP_ConnHdlr {
	f_gmm_attach(false, false);
	f_sleep(1.0);
	f_send_llc(ts_LLC_NULL('0'B, c_LLC_SAPI_LLGMM, LLC_CR_UL_CMD));
	/* try to detach to check if SGSN is still alive */
	f_detach_mo(c_GMM_DTT_MO_GPRS, true, true);
}
testcase TC_llc_null() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_TC_llc_null), testcasename(), g_gb, 41);
	vc_conn.done;
	f_cleanup();
}

/* Send LLC SABM to see if the SGSN rejects it properly with DM */
private function f_TC_llc_sabm_dm_llgmm(charstring id) runs on BSSGP_ConnHdlr {
	f_gmm_attach(false, false);
	f_sleep(1.0);
	f_send_llc(ts_LLC_SABM({}, '1'B, c_LLC_SAPI_LLGMM, LLC_CR_UL_CMD));
	BSSGP[0].receive(tr_LLC_DM(?, c_LLC_SAPI_LLGMM, LLC_CR_DL_RSP));
	setverdict(pass);
}
testcase TC_llc_sabm_dm_llgmm() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_TC_llc_sabm_dm_llgmm), testcasename(), g_gb, 42);
	vc_conn.done;
	f_cleanup();
}

/* Send LLC SABM to see if the SGSN rejects it properly with DM */
private function f_TC_llc_sabm_dm_ll5(charstring id) runs on BSSGP_ConnHdlr {
	f_gmm_attach(false, false);
	f_sleep(1.0);
	f_send_llc(ts_LLC_SABM({}, '1'B, c_LLC_SAPI_LL5, LLC_CR_UL_CMD));
	BSSGP[0].receive(tr_LLC_DM(?, c_LLC_SAPI_LL5, LLC_CR_DL_RSP));
	setverdict(pass);
}
testcase TC_llc_sabm_dm_ll5() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_TC_llc_sabm_dm_ll5), testcasename(), g_gb, 43);
	vc_conn.done;
	f_cleanup();
}

/* test XID handshake with empty L3 info: expect empty return (some phones require that, OS#3426 */
private function f_TC_xid_empty_l3(charstring id) runs on BSSGP_ConnHdlr {
	var PdpActPars apars := valueof(t_PdpActPars(mp_ggsn_ip));
	var template (value) XID_Information xid;
	var template XID_Information xid_rx;

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

	/* start MO XID */
	xid := { ts_XID_L3(''O) };
	xid_rx := { tr_XID_L3(''O) };
	f_send_llc(ts_LLC_XID_MO_CMD(xid, apars.sapi));
	alt {
	[] BSSGP[0].receive(tr_LLC_XID(xid_rx, apars.sapi));
	[] as_xid(apars);
	}
	setverdict(pass);
}
testcase TC_xid_empty_l3() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_TC_xid_empty_l3), testcasename(), g_gb, 44);
	vc_conn.done;
	f_cleanup();
}

private function f_TC_xid_n201u(charstring id) runs on BSSGP_ConnHdlr {
	var PdpActPars apars := valueof(t_PdpActPars(mp_ggsn_ip));
	var template (value) XID_Information xid;
	var template XID_Information xid_rx;

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

	/* start MO XID */
	xid := { ts_XID_N201U(1234) };
	xid_rx := { tr_XID_N201U(1234) };
	f_send_llc(ts_LLC_XID_MO_CMD(xid, apars.sapi));
	alt {
	[] BSSGP[0].receive(tr_LLC_XID_MT_RSP(xid_rx, apars.sapi));
	[] as_xid(apars);
	}
	setverdict(pass);
}
testcase TC_xid_n201u() runs on test_CT {
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	f_sleep(1.0);
	vc_conn := f_start_handler(refers(f_TC_xid_n201u), testcasename(), g_gb, 45);
	vc_conn.done;
	f_cleanup();
}

private function f_TC_attach_pdp_act_gmm_detach(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);
	/* do a normal detach */
	f_detach_mo(c_GMM_DTT_MO_GPRS, false, true);
}

testcase TC_attach_pdp_act_gmm_detach() runs on test_CT {
	/* MS  -> SGSN: Attach Request
	 * MS <-> SGSN: [..]
	 * MS  -> SGSN: Attach Complete
	 * MS  -> SGSN: PDP Activate Request
	 * MS <-  SGSN: PDP Activate Accept
	 * MS  -> SGSN: GMM Detach Request
	 * MS <-  SGSN: GMM Detach Accept
	 */
	var BSSGP_ConnHdlr vc_conn;
	f_init();
	vc_conn := f_start_handler(refers(f_TC_attach_pdp_act_gmm_detach), testcasename(), g_gb, 26);
	vc_conn.done;
	f_cleanup();
}

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_attach_usim_resync() );
	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_pdp_act_deact_dup() );
	execute( TC_attach_second_attempt() );
	execute( TC_attach_echo_timeout() );
	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_deact_gtp_retrans() );
	execute( TC_attach_pdp_act_deact_gtp_retrans_resp() );
	execute( TC_attach_pdp_act_user_error_ind_ggsn() );
	execute( TC_attach_pdp_act_gmm_detach() );
	execute( TC_attach_gmm_attach_req_while_gmm_attach() );

	execute( TC_xid_empty_l3() );
	execute( TC_xid_n201u() );

	execute( TC_llc_null() );
	execute( TC_llc_sabm_dm_llgmm() );
	execute( TC_llc_sabm_dm_ll5() );
}



}