aboutsummaryrefslogtreecommitdiffstats
path: root/asterisk/IMS_ConnectionHandler.ttcn
blob: 39abc59c994f57c8c796baa7d5c9cd71bccfed3e (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
/* Component implementing a IMS server towards Asterisk's IMS UE
 * (C) 2024 by sysmocom - s.f.m.c. GmbH <info@sysmocom.de>
 * Author: Pau Espin Pedrol <pespin@sysmocom.de>
 * 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
 */
module IMS_ConnectionHandler {

import from TCCEncoding_Functions all;
import from TCCOpenSecurity_Functions all;
import from General_Types all;
import from Osmocom_Types all;
import from Native_Functions all;
import from Misc_Helpers all;

/* the PIPE asp port allows us to interact with ip xfrm via stdin/stdout */
import from PIPEasp_PortType all;
import from PIPEasp_Types all;
import from PIPEasp_Templates all;

import from SDP_Types all;
import from SDP_Templates all;

import from SIP_Emulation all;
import from SIPmsg_Types all;
import from SIP_Templates all;


modulepar {
	charstring mp_ipsec_setup_script_path := "./IMS_ipsec_setup.sh";
}

const integer c_def_expires := 600000; /* 3GPP TS 24.229 5.1.1.2.1 e) */
const charstring c_sip_server_name := "osmo-ttcn3-hacks/0.23";


type port IMSCoord_PT message
{
	inout charstring;
} with { extension "internal" };

const charstring IMS_COORD_CMD_REGISTERED := "IMS_COORD_CMD_REGISTERED";
const charstring IMS_COORD_CMD_START := "IMS_COORD_CMD_START";
const charstring IMS_COORD_CMD_CALL_ESTABLISHED := "IMS_COORD_CMD_CALL_ESTABLISHED";
const charstring IMS_COORD_CMD_HANGUP := "IMS_COORD_CMD_HANGUP";
const charstring IMS_COORD_CMD_CALL_FINISHED := "IMS_COORD_CMD_CALL_FINISHED";
const charstring IMS_COORD_CMD_CALL_REJECTED := "IMS_COORD_CMD_CALL_REJECTED";
const charstring IMS_COORD_CMD_CALL_TRYING := "IMS_COORD_CMD_CALL_TRYING";
const charstring IMS_COORD_CMD_CALL_SESSION_PROGRESS := "IMS_COORD_CMD_CALL_SESSION_PROGRESS";
const charstring IMS_COORD_CMD_CALL_SESSION_REFRESH := "IMS_COORD_CMD_CALL_SESSION_REFRESH";

type component IMS_ConnHdlr extends SIP_ConnHdlr {
	var charstring g_name;
	var IMS_ConnHdlrPars g_pars;
	timer g_Tguard;
	var PDU_SIP_Request g_rx_sip_req;
	var PDU_SIP_Response g_rx_sip_resp;

	port IMSCoord_PT COORD;
	port PIPEasp_PT PIPE;
}
type record of IMS_ConnHdlr IMS_ConnHdlrList;

type record IMS_AuthVector {
	OCT16 rand,
	OCT16 autn,
	OCT8 res,
	OCT16 ck,
	OCT16 ik,
	OCT14 auts
}

type record IMS_ConnHdlrSubscrPars {
	charstring remote_sip_host optional,
	uint16_t remote_sip_port optional,
	charstring imsi,
	charstring imei,
	charstring display_name,
	charstring password,
	charstring msisdn,
	boolean support_video,
	boolean support_smsip,
	boolean close_tcp_after_registration,
	/* Expected User-Location-Info in P-Access-Network-Info */
	charstring uli_str,
	IMS_AuthVector auth,
	charstring ipsec_auth_key,
	integer ipsec_local_spi_c,
	integer ipsec_local_spi_s,
	integer ipsec_remote_spi_c optional,
	integer ipsec_remote_spi_s optional,
	uint16_t ipsec_remote_port_c optional,
	uint16_t ipsec_remote_port_s optional,
	SipAddr registrar_sip_record,
	CallidString registrar_sip_call_id,
	integer registrar_sip_seq_nr,
	integer exp_uac_expires,
	integer registrar_expires,
	SipUrl local_sip_url_ext,
	SipAddr local_sip_record,
	WwwAuthenticate www_auth optional,
	Contact registered_contact optional,
	P_Associated_Uri p_associated_uri,
	IMS_CallPars cp optional
}
type record of IMS_ConnHdlrSubscrPars IMS_ConnHdlrSubscrParsList;


type record IMS_ConnHdlrPars {
	float t_guard,
	charstring realm,
	charstring local_sip_host,
	uint16_t local_sip_port,
	SipUrl registrar_sip_req_uri,
	Via local_via,
	Server server_name,
	IMS_ConnHdlrSubscrPars subscr optional
}
type record of IMS_ConnHdlrPars IMS_ConnHdlrParsList;

type record IMS_CallParsMO {
	/* Whether to COORD.send(IMS_COORD_CMD_CALL_TRYING) when receiving an INVITE from UE. */
	boolean tx_coord_cmd_invite_trying,
	/* Whether to announce "Support: timer" and Session-Expires header */
	boolean support_timer_enable,
	integer support_timer_session_expires,
	integer support_timer_exp_min_se
}
template (value) IMS_CallParsMO t_IMS_CallParsMO := {
	tx_coord_cmd_invite_trying := false,
	support_timer_enable := false,
	support_timer_session_expires := 0,
	support_timer_exp_min_se := 0
}

type record IMS_CallParsMT {
	/* Whether to COORD.send(IMS_COORD_CMD_CALL_SESSION_PROGRESS) when receiving an 183 Session Progress from UE. */
	boolean tx_coord_cmd_session_progress,
	/* Whether to announce "Support: timer" and Session-Expires header */
	boolean support_timer_enable,
	integer support_timer_session_expires,
	integer support_timer_min_se
}
template (value) IMS_CallParsMT t_IMS_CallParsMT := {
	tx_coord_cmd_session_progress := false,
	support_timer_enable := false,
	support_timer_session_expires := 0,
	support_timer_min_se := 90
}

type record IMS_CallPars {
	SipAddr calling optional,
	SipAddr called optional,

	From from_addr optional,
	To to_addr optional,

	CallidString sip_call_id,
	integer sip_seq_nr,
	charstring sip_body optional,

	charstring local_rtp_addr,
	uint16_t local_rtp_port,

	boolean support_precondition_ext,
	boolean require_precondition_ext,
	SDP_Message peer_sdp optional,
	IMS_CallParsMO mo,
	IMS_CallParsMT mt
}

template (value) IMS_CallPars t_IMS_CallPars(charstring local_rtp_addr,
					     uint16_t local_rtp_port := 0,
					     template (omit) SipAddr calling := omit,
					     template (omit) SipAddr called := omit) := {
	calling := calling,
	called := called,
	from_addr := omit,
	to_addr := omit,
	sip_call_id := hex2str(f_rnd_hexstring(15)),
	sip_seq_nr := f_sip_rand_seq_nr(),
	sip_body := omit,
	local_rtp_addr := local_rtp_addr,
	local_rtp_port := local_rtp_port,
	support_precondition_ext := true,
	require_precondition_ext := false,
	peer_sdp := omit,
	mo := t_IMS_CallParsMO,
	mt := t_IMS_CallParsMT
}

template (value) IMS_ConnHdlrSubscrPars t_IMS_SubscrPars(charstring local_sip_host,
						   uint16_t local_sip_port,
						   charstring domain,
						   charstring imsi,
						   charstring imei,
						   charstring msisdn := "90828",
						   charstring display_name := "Anonymous",
						   charstring password := "secret",
						   template (omit) IMS_CallPars cp := omit) := {
	remote_sip_host := omit,
	remote_sip_port := omit,
	imsi := imsi,
	imei := imei,
	display_name := f_sip_str_quote(display_name),
	password := password,
	msisdn := msisdn,
	support_video := false,
	support_smsip := false,
	close_tcp_after_registration := false,
	uli_str := "2380100010000101",
	auth := {
		/* The Nonce field is the Base64 encoded version of the RAND value and concatenated with the AUTN: */
		rand := 'd5d5de2bce418d7865ed7fa6956618a2'O,
		autn := 'd42e61db5f15800067393a5b7691a227'O,
		res := '6f2556bbe4366ab1'O,
		ck := '0b389d08c833991734936bec55cac800'O,
		ik := '17141862125bd30c81c4224391a0909a'O,
		/* NOTE: AUTS value randomly crafted. It's fine since it's just forwarded
		 *       AMI -> asterisk -> IMS and we blindly match and accept it. */
		auts := 'd42e61db5f15800067393a5b7691'O
	},
	ipsec_auth_key := "0x17141862125bd30c81c4224391a0909a00000000",
	ipsec_local_spi_c := 4142,
	ipsec_local_spi_s := 4143,
	ipsec_remote_spi_c := omit,
	ipsec_remote_spi_s := omit,
	ipsec_remote_port_c := omit,
	ipsec_remote_port_s := omit,
	registrar_sip_record := ts_SipAddr(ts_HostPort(domain),
					   ts_UserInfo(imsi),
					   f_sip_str_quote(display_name)),
	registrar_sip_call_id := hex2str(f_rnd_hexstring(15)) & "@" & domain,
	registrar_sip_seq_nr := f_sip_rand_seq_nr(),
	exp_uac_expires := c_def_expires,
	registrar_expires := c_def_expires,
	local_sip_url_ext := ts_SipUrl(ts_HostPort(domain, local_sip_port),
				       ts_UserInfo(imsi)),
	local_sip_record := ts_SipAddr(ts_HostPort(domain),
				       ts_UserInfo(imsi)),
	www_auth := omit,
	registered_contact := omit,
	p_associated_uri := ts_P_Associated_Uri({}),
	cp := cp
}

template (value) IMS_ConnHdlrPars t_IMS_Pars(charstring local_sip_host,
					uint16_t local_sip_port,
					charstring domain,
					charstring imsi,
					charstring imei,
					template (omit) IMS_CallPars cp := omit) := {
	t_guard := 60.0,
	realm := domain,
	local_sip_host := local_sip_host,
	local_sip_port := local_sip_port,
	registrar_sip_req_uri := valueof(ts_SipUrlHost(domain)),
	local_via := ts_Via_from(ts_HostPort(local_sip_host, local_sip_port)),
	server_name := valueof(ts_Server({c_sip_server_name})),
	subscr := t_IMS_SubscrPars(local_sip_host, local_sip_port,
				   domain := domain, imsi := imsi,
				   imei := imei, cp := cp)
}

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

type function ims_void_fn(charstring id) runs on IMS_ConnHdlr;
function f_ims_handler_init(ims_void_fn fn, charstring id, IMS_ConnHdlrPars pars)
runs on IMS_ConnHdlr {
	g_name := id;
	g_pars := pars;
	g_Tguard.start(pars.t_guard);
	activate(as_Tguard());

	/* call the user-supied test case function */
	fn.apply(id);
}

altstep as_SIP_fail_req(charstring exp_msg_str := "") runs on IMS_ConnHdlr
{
	var PDU_SIP_Request sip_req;
	[] SIP.receive(PDU_SIP_Request:?) -> value sip_req {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
					log2str(g_name & ": Received unexpected SIP Req message := ", sip_req, "\nvs exp := ", exp_msg_str));
	}
}

altstep as_SIP_fail_resp(charstring exp_msg_str := "") runs on IMS_ConnHdlr
{
	var PDU_SIP_Response sip_resp;
	[] SIP.receive(PDU_SIP_Response:?) -> value sip_resp {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
					log2str(g_name & ": Received unexpected SIP Resp message := ", sip_resp, "\nvs exp := ", exp_msg_str));
	}
}

altstep as_SIP_expect_resp(template (present) PDU_SIP_Response sip_expect, boolean fail_others := true) runs on IMS_ConnHdlr
{
	var charstring sip_expect_str := log2str(sip_expect);
	[] SIP.receive(sip_expect) -> value g_rx_sip_resp;
	[fail_others] as_SIP_fail_resp(sip_expect_str);
	[fail_others] as_SIP_fail_req(sip_expect_str);
}

altstep as_SIP_ignore_resp(template PDU_SIP_Response sip_expect := ?) runs on IMS_ConnHdlr
{
	[] SIP.receive(sip_expect) -> value g_rx_sip_resp {
		log("Ignoring ", g_rx_sip_resp);
		repeat;
	}
}

private function f_nonce_from_rand_autn(octetstring rand, octetstring autn) return charstring {
	var octetstring concat := rand & autn;
	var charstring nonce := enc_MIME_Base64(concat);
	log("rand=", rand, " & autn=",autn, " => nonce=", nonce);
	return nonce;
}

/* HTTP Digest Authentication Using AKA (AKAv1-MD5): RFC 3310 */
function f_tr_Authorization_AKAv1MD5(WwwAuthenticate www_authenticate,
				     charstring username,
				     charstring uri)
return template (present) Authorization {
	var CommaParam_List digestCln;
	var template (present) Authorization authorization;
	var template (present) Credentials cred;
	var template (omit) GenericParam rx_param;

	digestCln := www_authenticate.challenge[0].digestCln;

	var charstring algorithm := f_sip_param_get_value_present_or_fail(digestCln, "algorithm");
	var charstring realm := f_sip_param_get_value_present_or_fail(digestCln, "realm");
	var charstring nonce := f_sip_param_get_value_present_or_fail(digestCln, "nonce");

	var template (present) CommaParam_List digestResponse := superset(
		tr_Param("username", f_sip_str_quote(username)),
		tr_Param("realm", f_sip_str_quote(realm)),
		tr_Param("nonce", f_sip_str_quote(nonce)),
		tr_Param("uri", f_sip_str_quote(uri)),
		tr_Param("response", ?),
		tr_Param("algorithm", algorithm),
		tr_Param("qop", "auth"),
		tr_Param("cnonce", ?),
		tr_Param("nc", ?)
	);
	cred := tr_Credentials_DigestResponse(digestResponse);
	authorization := tr_Authorization(cred);
	return authorization;
}

private function f_ims_validate_Authorization_AKAv1MD5_Response(Authorization authorization, charstring method)
runs on IMS_ConnHdlr {
	f_sip_digest_validate_Authorization_AKAv1MD5(authorization, method, g_pars.subscr.auth.res);
}

/* GSMA IR-92 2.2.1 SIP Registration Procedure */
private function f_ims_validate_register_contact(Contact rx_contact) runs on IMS_ConnHdlr
{
	/* IMS contact shows up like this:
	* Contact: <sip:8adf9f3d-9342-4060-aa4f-a909f37fd6f6@192.168.101.2:5060>;+g.3gpp.accesstype="cellular2";video;audio;+g.3gpp.smsip;+g.3gpp.nw-init-ussi;+g.3gpp.icsi-ref="urn%3Aurn-7%3A3gpp-service.ims.icsi.mmtel";+sip.instance="<urn:gsma:imei:35589811-338445-0>"
	*/
	if (ischosen(rx_contact.contactBody.wildcard)) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
			log2str(g_name & ": Received unexpected Contact wildcard := ", rx_contact));
	}
	var ContactAddress_List caddrs := rx_contact.contactBody.contactAddresses;
	if (lengthof(caddrs) == 0) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
				log2str(g_name & ": Received unexpected empty Contact Address list"));
	}
	for (var integer i := 0; i < lengthof(caddrs); i := i + 1) {
		var ContactAddress caddr := caddrs[i];
		var template (omit) GenericParam param_tpl;
		var boolean rx_supported;
		if (not ispresent(caddr.contactParams)) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
				log2str(g_name & ": Received unexpected empty Contact attributes (omit)"));
		}
		f_sip_param_match_value_or_fail(caddr.contactParams, "+g.3gpp.icsi-ref", "\"urn%3Aurn-7%3A3gpp-service.ims.icsi.mmtel\"");
		f_sip_param_match_value_or_fail(caddr.contactParams, "+sip.instance", "\"<urn:gsma:imei:" & g_pars.subscr.imei & ">\"");
		f_sip_param_match_value_or_fail(caddr.contactParams, "audio", omit);

		/* Check video support */
		param_tpl := f_sip_param_find(caddr.contactParams, "video");
		rx_supported := not istemplatekind(param_tpl, "omit");
		if (rx_supported) {
			/* This attribute never has a value: */
			if (not istemplatekind(param_tpl.paramValue, "omit")) {
				Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
					log2str(g_name & ": Received Contact with 'video' attribute containing a value := ", rx_contact));
			}
			if (not g_pars.subscr.support_video) {
				Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
					log2str(g_name & ": Received Contact with unexpected 'video' attribute := ", rx_contact));
			}
		} else if (g_pars.subscr.support_video) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
				log2str(g_name & ": Received Contact with missing 'video' attribute := ", rx_contact));
		}

		/* Check smsip support */
		param_tpl := f_sip_param_find(caddr.contactParams, "+g.3gpp.smsip");
		rx_supported := not istemplatekind(param_tpl, "omit");
		if (rx_supported) {
			/* This attribute never has a value: */
			if (not istemplatekind(param_tpl.paramValue, "omit")) {
				Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
					log2str(g_name & ": Received Contact with '+g.3gpp.smsip' attribute containing a value := ", rx_contact));
			}
			if (not g_pars.subscr.support_smsip) {
				Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
					log2str(g_name & ": Received Contact with unexpected '+g.3gpp.smsip' attribute := ", rx_contact));
			}
		} else if (g_pars.subscr.support_smsip) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
				log2str(g_name & ": Received Contact with missing '+g.3gpp.smsip' attribute := ", rx_contact));
		}
	}

}

/* Validate P-Access-Network-Info: RFC7315 6.4 */
private function f_ims_validate_register_P_Access_Network_info(PDU_SIP_Request req,
							       boolean exp_present := true) runs on IMS_ConnHdlr

{
	if (not exp_present) {
		if (ispresent(g_rx_sip_req.msgHeader.p_access_network_info)) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
						log2str(g_name & ": Received unexpected [rfc7315 6.4] P-Access-Info := ",
						g_rx_sip_req.msgHeader.p_access_network_info));
		}
		return;
	}

	/* exp_present: */
	var template (present) P_Access_Network_Info expl_tmpl :=
		tr_P_Access_Network_Info({ tr_Access_net_spec_EUTRAN(g_pars.subscr.uli_str) });

	if (not ispresent(g_rx_sip_req.msgHeader.p_access_network_info)) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
					log2str(g_name & ": Received no P-Access-Info vs exp := ",
					expl_tmpl));
	}
	if (not match(g_rx_sip_req.msgHeader.p_access_network_info, expl_tmpl)) {
				Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
							log2str(g_name & ": Received unexpected P-Access-Info := ",
							g_rx_sip_req.msgHeader.p_access_network_info,
							"\nvs exp := ", expl_tmpl));
	}
}

/* GSMA IR.92 2.2.4 Call Establishment and Termination */
private function f_ims_validate_INVITE_Contact(Contact rx_contact) runs on IMS_ConnHdlr
{
	/* INVITE Contact header shows up like this:
	* Contact: <sip:e05d8e82-8565-47b5-aca5-5f6b9164b074@192.168.101.2:44823>;+g.3gpp.icsi-ref="urn%3Aurn-7%3A3gpp-service.ims.icsi.mmtel";audio;+g.3gpp.mid-call;+g.3gpp.srvcc-alerting;+g.3gpp.ps2cs-srvcc-orig-pre-alerting
	*/
	if (ischosen(rx_contact.contactBody.wildcard)) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
			log2str(g_name & ": Received unexpected Contact wildcard := ", rx_contact));
	}
	var ContactAddress_List caddrs := rx_contact.contactBody.contactAddresses;
	if (lengthof(caddrs) == 0) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
				log2str(g_name & ": Received unexpected empty Contact Address list"));
	}
	for (var integer i := 0; i < lengthof(caddrs); i := i + 1) {
		var ContactAddress caddr := caddrs[i];
		if (not ispresent(caddr.contactParams)) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
				log2str(g_name & ": Received unexpected empty Contact attributes (omit)"));
		}
		/* GSMA FCM.01 3.2.3.3: "The INVITE request contains Within the Contact header [...] the IMS
		 * Communication Service Identifier's (ICSI) for IMS Multimedia Telephony" */
		f_sip_param_match_value_or_fail(caddr.contactParams, "+g.3gpp.icsi-ref", "\"urn%3Aurn-7%3A3gpp-service.ims.icsi.mmtel\"");
		/* "The UE must include the audio media feature tag, as defined in IETF RFC 3840,
		 * in the Contact header field of the SIP INVITE request, and in the Contact header
		 * field of the SIP response to the SIP INVITE request" */
		f_sip_param_match_value_or_fail(caddr.contactParams, "audio", omit);
	}
}

/* Validate P-Preferred-Service: GSMA FCM.01 3.2.3.3 */
private function f_ims_validate_invite_P_Preferred_Service(PDU_SIP_Request req,
							   boolean exp_present := true) runs on IMS_ConnHdlr

{
	if (not exp_present) {
		if (ispresent(g_rx_sip_req.msgHeader.p_preferred_service)) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
						log2str(g_name & ": Received unexpected [rfc6050] P-Preferred-Service := ",
						g_rx_sip_req.msgHeader.p_preferred_service));
		}
		return;
	}

	/* exp_present: */
	var template (present) P_Preferred_Service expl_tmpl :=
		tr_P_Preferred_Service({ "urn:urn-7:3gpp-service.ims.icsi.mmtel" });

	if (not ispresent(g_rx_sip_req.msgHeader.p_preferred_service)) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
					log2str(g_name & ": Received no P-Preferred-Service vs exp := ",
					expl_tmpl));
	}
	if (not match(g_rx_sip_req.msgHeader.p_preferred_service, expl_tmpl)) {
				Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
							log2str(g_name & ": Received unexpected P-Preferred-Service := ",
							g_rx_sip_req.msgHeader.p_preferred_service,
							"\nvs exp := ", expl_tmpl));
	}
}

/* GSMA IR.92 2.2.4 Call Establishment and Termination */
private function f_ims_validate_INVITE_SDP(SDP_Message sdp) runs on IMS_ConnHdlr
{
		/* "The UE must indicate in the SDP of the initial INVITE that the audio media
		 * is send-receive i.e. either by including the direction attribute "a=sendrecv"
		 * or by omitting the direction attributes. */
		if (ispresent(sdp.attributes)) {
			if (match (sdp.attributes, superset(tr_SDP_recvonly)) or
			    match (sdp.attributes, superset(tr_SDP_sendonly))) {
				Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
					log2str(g_name & ": Unexpected SDP direction attribute != sendrecv: ",
						sdp.attributes));
			}
		}
}

private function f_ims_parse_security_client(Security_client security_client) runs on IMS_ConnHdlr
{
	var boolean found := false;
	for (var integer i := 0; i < lengthof(security_client.sec_mechanism_list); i := i + 1) {
		var Security_mechanism sec_mec := security_client.sec_mechanism_list[i];
		if (sec_mec.mechanism_name != "ipsec-3gpp") {
			log("Skipping Security Mechansim: ", sec_mec.mechanism_name);
			continue;
		}
		var SemicolonParam_List sec_pars := sec_mec.mechanism_params;
		var charstring par_val;
		par_val := f_sip_param_get_value_present_or_fail(sec_pars, "alg");
		if (par_val != "hmac-sha-1-96") {
			log("Skipping Security Mechansim Algo: ", par_val);
			continue;
		}
		par_val := f_sip_param_get_value_present_or_fail(sec_pars, "spi-c");
		g_pars.subscr.ipsec_remote_spi_c := str2int(par_val);
		par_val := f_sip_param_get_value_present_or_fail(sec_pars, "spi-s");
		g_pars.subscr.ipsec_remote_spi_s := str2int(par_val);
		par_val := f_sip_param_get_value_present_or_fail(sec_pars, "port-c");
		g_pars.subscr.ipsec_remote_port_c := str2int(par_val);
		par_val := f_sip_param_get_value_present_or_fail(sec_pars, "port-s");
		g_pars.subscr.ipsec_remote_port_s := str2int(par_val);
		found := true;
		break;
	}

	if (not found) {
		Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
					log2str(g_name & "alg=hmac-sha-1-96 not found: ", security_client));
	}

	log("ipsec: remote_spi_c=", g_pars.subscr.ipsec_remote_spi_c, " remote_spi_s=", g_pars.subscr.ipsec_remote_spi_s,
	    "local_spi_c=", g_pars.subscr.ipsec_local_spi_c, " local_spi_s=", g_pars.subscr.ipsec_local_spi_s);
}

private function f_ims_parse_register_contact(Contact contact) runs on IMS_ConnHdlr
{
	var HostPort hp := valueof(contact.contactBody.contactAddresses[0].addressField.nameAddr.addrSpec.hostPort);

	g_pars.subscr.remote_sip_host := hp.host;
	if (ispresent(hp.portField)) {
		g_pars.subscr.remote_sip_port := hp.portField;
	} else {
		g_pars.subscr.remote_sip_port := 5060;
	}
}

private function f_IMS_exec_sync(charstring cmdline, template (present) integer rc := 0)
		runs on IMS_ConnHdlr return ASP_PResult {
	var ASP_PResult res;

	map(self:PIPE, system:PIPE);
	res := f_PIPEasp_exec_sync_PResult(PIPE, cmdline, tr_PResult(?, ?, rc));
	unmap(self:PIPE, system:PIPE);

	return res;
}

private function f_ims_setup_ipsec() runs on IMS_ConnHdlr
{
	var ASP_PResult res;

	var charstring cmd := mp_ipsec_setup_script_path & " " &
		g_pars.local_sip_host & " " &
		int2str(g_pars.local_sip_port) & " " & int2str(g_pars.subscr.ipsec_local_spi_c) & " " &
		int2str(g_pars.local_sip_port) & " " & int2str(g_pars.subscr.ipsec_local_spi_s) & " " &
		g_pars.subscr.remote_sip_host & " " &
		int2str(g_pars.subscr.ipsec_remote_port_c) & " " & int2str(g_pars.subscr.ipsec_remote_spi_c) & " " &
		int2str(g_pars.subscr.ipsec_remote_port_s) & " " & int2str(g_pars.subscr.ipsec_remote_spi_s) & " " &
		g_pars.subscr.ipsec_auth_key;

	res := f_IMS_exec_sync(cmd);

	/* Debug applied rules: */
	/*
	res := f_IMS_exec_sync("ip xfrm state");
	log("ip-xfrm-state Result-Stdout: " & res.stdout);

	res := f_IMS_exec_sync("ip xfrm policy");
	log("ip-xfrm-policy Result-Stdout: " & res.stdout);
	*/
}

private function f_tr_Via_response(Via via_req) return template (present) Via {
	template (present) SemicolonParam_List via_resp_params := ?;

	/*via_resp_params := {
		{ id := "rport", paramValue := int2str(g_pars.subscr.remote_sip_port.subscr.remote_sip_port) },
		{ id := "received", paramValue := g_pars.subscr.remote_sip_host }
	}; */
	return 	tr_Via_from(via_req.viaBody[0].sentBy,
			    via_req.viaBody[0].sentProtocol.transport,
			    via_resp_params);
}

private function f_tr_From(template (value) SipAddr from_req) return template (present) SipAddr {
	return tr_SipAddr_from_val(from_req);
}

private altstep as_SIP_expect_req(template (present) PDU_SIP_Request sip_expect, boolean fail_others := true) runs on IMS_ConnHdlr
{
	var charstring sip_expect_str := log2str(sip_expect);
	[] SIP.receive(sip_expect) -> value g_rx_sip_req;
	[fail_others] as_SIP_fail_req(sip_expect_str);
	[fail_others] as_SIP_fail_resp(sip_expect_str);
}

type enumerated IMS_gen_sdp_state {
	IMS_GEN_SDP_None,
	IMS_GEN_SDP_MO_INVITE,
	IMS_GEN_SDP_MO_UPDATE,
	IMS_GEN_SDP_MT_Session_Progress,
	IMS_GEN_SDP_MT_UPDATE_200OK
}

private function f_gen_sdp(IMS_gen_sdp_state st := IMS_GEN_SDP_None, charstring dir := "sendrecv") runs on IMS_ConnHdlr return charstring {
	var charstring sdp :=
		"v=0\r\n" &
		"o=0502 2390 1824 IN IP4 " & g_pars.subscr.cp.local_rtp_addr & "\r\n" &
		"s=Talk\r\n" &
		"c=IN IP4 " & g_pars.subscr.cp.local_rtp_addr & "\r\n" &
		"t=0 0\r\n" &
		"a=rtcp-xr:rcvr-rtt=all:10000 stat-summary=loss,dup,jitt,TTL voip-metrics\r\n" &
		"a=record:off\r\n" &
		"m=audio " & int2str(g_pars.subscr.cp.local_rtp_port) & " RTP/AVP 126 99 100 101\r\n" &
		"b=AS:34\r\n" &
		"b=RS:600\r\n" &
		"b=RR:2000\r\n" &
		"a=rtpmap:126 EVS/16000/1\r\n" &
		"a=fmtp:126 br=5.9-16.4;bw=nb-fb;max-red=0\r\n" &
		"a=rtpmap:99 telephone-event/48000\r\n" &
		"a=rtpmap:100 telephone-event/16000\r\n" &
		"a=rtpmap:101 telephone-event/8000\r\n" &
		"a=rtcp:" & int2str(g_pars.subscr.cp.local_rtp_port + 1) & "\r\n" &
		"a=rtcp-fb:* trr-int 1000\r\n" &
		"a=rtcp-fb:* ccm tmmbr\r\n" &
		"a=ptime:20\r\n" ;
	select (st) {
	case (IMS_GEN_SDP_None) {
	}
	case (IMS_GEN_SDP_MO_INVITE) {
		sdp := sdp &
			"a=curr:qos local none\r\n" &
			"a=curr:qos remote none\r\n" &
			"a=des:qos mandatory local sendrecv\r\n" &
			"a=des:qos optional remote sendrecv\r\n";
	}
	case (IMS_GEN_SDP_MO_UPDATE) {
		sdp := sdp &
			"a=curr:qos local sendrecv\r\n" &
			"a=curr:qos remote none\r\n" &
			"a=des:qos mandatory local sendrecv\r\n" &
			"a=des:qos mandatory remote sendrecv\r\n";
	}
	case (IMS_GEN_SDP_MT_Session_Progress) {
		sdp := sdp &
			"a=curr:qos local none\r\n" &
			"a=curr:qos remote none\r\n" &
			"a=des:qos mandatory local sendrecv\r\n" &
			"a=des:qos mandatory remote sendrecv\r\n" &
			"a=conf:qos remote sendrecv\r\n";
	}
	case (IMS_GEN_SDP_MT_UPDATE_200OK) {
		sdp := sdp &
			"a=curr:qos local sendrecv\r\n" &
			"a=curr:qos remote sendrecv\r\n" &
			"a=des:qos mandatory local sendrecv\r\n" &
			"a=des:qos mandatory remote sendrecv\r\n";
	}
	}

	sdp := sdp & "a=" & dir & "\r\n";
	return sdp;
}

private function f_gen_Security_server() runs on IMS_ConnHdlr return Security_server {
		var template (value) Security_server security_server;
		/* Security-Server: ipsec-3gpp;q=0.1;prot=esp;mod=trans;spi-c=4096;spi-s=4097;port-c=5104;port-s=6104;alg=hmac-sha-1-96;ealg=null */
		var template (value) SemicolonParam_List sec_params := {
			ts_Param("q", "0.1"),
			ts_Param("prot", "esp"),
			ts_Param("mod", "trans"),
			ts_Param("spi-c", int2str(g_pars.subscr.ipsec_local_spi_c)),
			ts_Param("spi-s", int2str(g_pars.subscr.ipsec_local_spi_s)),
			ts_Param("port-c", int2str(g_pars.local_sip_port)),
			ts_Param("port-s", int2str(g_pars.local_sip_port)),
			ts_Param("alg", "hmac-sha-1-96"),
			ts_Param("ealg", "null")
		};
		security_server := ts_Security_server({
			ts_Security_mechanism("ipsec-3gpp", sec_params)
		});
		return valueof(security_server);
}

private function f_gen_WwwAuthenticate() runs on IMS_ConnHdlr return WwwAuthenticate {
	var template (value) WwwAuthenticate wwwAuthenticate;
	var template (value) CommaParam_List digestCln;
	digestCln := {
		ts_Param("realm", f_sip_str_quote(g_pars.realm)),
		ts_Param("qop", f_sip_str_quote("auth")),
		ts_Param("algorithm", "AKAv1-MD5"),
		ts_Param("nonce", f_sip_str_quote(f_nonce_from_rand_autn(g_pars.subscr.auth.rand,
									 g_pars.subscr.auth.autn)))
		/* "opaque not needed in IMS "*/
	};
	wwwAuthenticate := ts_WwwAuthenticate( { ts_Challenge_digestCln(digestCln) } );
	return valueof(wwwAuthenticate);
}

type enumerated IMS_register_early_return {
	IMS_REG_EARLY_RET_BEFORE_None,
	IMS_REG_EARLY_RET_BEFORE_Initial_100Trying,
	IMS_REG_EARLY_RET_BEFORE_Initial_401Unauthorized,
	IMS_REG_EARLY_RET_BEFORE_Resync_401Unauthorized,
	IMS_REG_EARLY_RET_BEFORE_Protected_100Trying,
	IMS_REG_EARLY_RET_BEFORE_Protected_200OK
}

/* Peer is issuing 1st register, accept it: */
altstep as_IMS_register(boolean exp_auth_resync := false,
			IMS_register_early_return early_ret := IMS_REG_EARLY_RET_BEFORE_None,
			boolean fail_others := true) runs on IMS_ConnHdlr
{
	var template (present) PDU_SIP_Request exp_req :=
		tr_SIP_REGISTER(g_pars.registrar_sip_req_uri,
				?,
				tr_From(),
				tr_To(),
				tr_Via_from(?),
				expires := tr_Expires(int2str(g_pars.subscr.exp_uac_expires)),
				require := tr_Require(superset("sec-agree")),
				security_client := tr_Security_client(superset(tr_Security_mechanism("ipsec-3gpp",
												     superset(tr_Param("alg","hmac-sha-1-96"))))),
				supported := tr_Supported(superset("path", "sec-agree")));
	var charstring sip_expect_str := log2str(exp_req);

	[] SIP.receive(exp_req) -> value g_rx_sip_req {
		var template (value) PDU_SIP_Response tx_resp;
		var Via via;
		var CallidString sip_call_id;
		var template (value) From from_addr;
		var template (value) To to_addr;
		var Security_server security_server;
		var template (value) Require require := ts_Require({"sec-agree"});
		var template (value) Supported supported := ts_Supported({"sec-agree"});
		var integer sip_seq_nr;

		if (early_ret == IMS_REG_EARLY_RET_BEFORE_Initial_100Trying) {
			return; /* Done */
		}

		sip_call_id := g_rx_sip_req.msgHeader.callId.callid;
		via := g_rx_sip_req.msgHeader.via;
		via.viaBody[0].viaParams := f_sip_param_set(via.viaBody[0].viaParams, "rport", "1234"); /* TODO: set remote src port of the REGISTER */
		from_addr := g_rx_sip_req.msgHeader.fromField;
		to_addr := g_rx_sip_req.msgHeader.toField;
		sip_seq_nr := g_rx_sip_req.msgHeader.cSeq.seqNumber;

		/* Tx 100 Tyring */
		tx_resp := ts_SIP_Response_Trying(sip_call_id,
					from_addr,
					to_addr,
					via,
					sip_seq_nr,
					"REGISTER",
					allow := omit,
					server := g_pars.server_name,
					userAgent := omit);
		SIP.send(tx_resp);

		/* Validate P-Access-Network-Info: rfc7315 6.4:
		 * "3GPP will use the P-Access-Network-Info header field to
		 * carry relatively sensitive information like the cell ID.  Therefore,
		 * the information MUST NOT be sent outside of the 3GPP domain.""
		 * [...] "the sensitive information carried in the
		 * P-Access-Network-Info header field MUST NOT be sent in any initial
		 * unauthenticated and unprotected requests (e.g., REGISTER)."
		 */
		f_ims_validate_register_P_Access_Network_info(g_rx_sip_req, exp_present := false);

		f_ims_validate_register_contact(g_rx_sip_req.msgHeader.contact);
		f_ims_parse_register_contact(g_rx_sip_req.msgHeader.contact);
		f_ims_parse_security_client(g_rx_sip_req.msgHeader.security_client);

		if (early_ret == IMS_REG_EARLY_RET_BEFORE_Initial_401Unauthorized) {
			return; /* Done */
		}

		if (not exp_auth_resync) {
			/* Delay ipsec setup in ip xfrm, since there will be another
			* 1st REGISTER with potentially new ports coming in later. */
			f_ims_setup_ipsec();
		}

		to_addr.toParams := f_sip_param_set(to_addr.toParams, "tag", f_sip_rand_tag());
		g_pars.subscr.www_auth := f_gen_WwwAuthenticate();
		security_server := f_gen_Security_server();

		/* Tx 401 Unauthorized */
		tx_resp := ts_SIP_Response_Unauthorized(sip_call_id,
					from_addr,
					to_addr,
					via,
					g_pars.subscr.www_auth,
					sip_seq_nr,
					"REGISTER",
					p_associated_uri := g_pars.subscr.p_associated_uri,
					security_server := security_server,
					server := g_pars.server_name,
					supported := supported,
					userAgent := omit);
		SIP.send(tx_resp);

		if (exp_auth_resync) {
			/* Now we should receive a new non-protected REGISTER
			 * with Authoritzation containing auts in base64: */
			var template (present) Authorization authorization :=
				f_tr_Authorization_AKAv1MD5(g_pars.subscr.www_auth,
							    g_pars.subscr.imsi & "@" & g_pars.realm,
							    f_sip_SipUrl_to_str(g_pars.registrar_sip_req_uri));
			exp_req :=
			tr_SIP_REGISTER(g_pars.registrar_sip_req_uri,
					?,
					tr_From(),
					tr_To(),
					tr_Via_from(f_tr_HostPort(via.viaBody[0].sentBy.host, via.viaBody[0].sentBy.portField)),
					authorization := authorization);
			SIP.receive(exp_req) -> value g_rx_sip_req;

			if (early_ret == IMS_REG_EARLY_RET_BEFORE_Resync_401Unauthorized) {
				return; /* Done */
			}

			via := g_rx_sip_req.msgHeader.via;
			from_addr := g_rx_sip_req.msgHeader.fromField;
			to_addr := g_rx_sip_req.msgHeader.toField;
			sip_seq_nr := g_rx_sip_req.msgHeader.cSeq.seqNumber;

			/* Tx 100 Tyring */
			tx_resp := ts_SIP_Response_Trying(sip_call_id,
						from_addr,
						to_addr,
						via,
						sip_seq_nr,
						"REGISTER",
						allow := omit,
						server := g_pars.server_name,
						userAgent := omit);
			SIP.send(tx_resp);

			f_sip_param_match_value_or_fail(g_rx_sip_req.msgHeader.authorization.body.digestResponse,
							"auts", f_sip_str_quote(enc_MIME_Base64(g_pars.subscr.auth.auts)));
			f_ims_validate_register_P_Access_Network_info(g_rx_sip_req, exp_present := false);
			f_ims_validate_register_contact(g_rx_sip_req.msgHeader.contact);
			f_ims_parse_register_contact(g_rx_sip_req.msgHeader.contact);
			f_ims_parse_security_client(g_rx_sip_req.msgHeader.security_client);
			f_ims_setup_ipsec();

			security_server := f_gen_Security_server();
			to_addr.toParams := f_sip_param_set(to_addr.toParams, "tag", f_sip_rand_tag());

			/* Tx again 401 Unauthorized, this time our AMI interface will accept it: */
			tx_resp := ts_SIP_Response_Unauthorized(sip_call_id,
						from_addr,
						to_addr,
						via,
						g_pars.subscr.www_auth,
						sip_seq_nr,
						"REGISTER",
						p_associated_uri := g_pars.subscr.p_associated_uri,
						security_server := security_server,
						server := g_pars.server_name,
						supported := supported,
						userAgent := omit);
			SIP.send(tx_resp);
		}

		/* Now we should receive a new REGISTER over ipsec: */
		as_IMS_2nd_register(early_ret := early_ret);
	}
	[fail_others] as_SIP_fail_resp(sip_expect_str);
	[fail_others] as_SIP_fail_req(sip_expect_str);

}

/* Peer is issuing 2nd register, accept it: */
altstep as_IMS_2nd_register(IMS_register_early_return early_ret := IMS_REG_EARLY_RET_BEFORE_None,
			    boolean fail_others := true) runs on IMS_ConnHdlr
{
	var template (present) Authorization authorization :=
		f_tr_Authorization_AKAv1MD5(g_pars.subscr.www_auth,
					    g_pars.subscr.imsi & "@" & g_pars.realm,
					    f_sip_SipUrl_to_str(g_pars.registrar_sip_req_uri));
	var template (present) PDU_SIP_Request exp_req :=
		tr_SIP_REGISTER(g_pars.registrar_sip_req_uri,
				?,
				tr_From(),
				tr_To(),
				tr_Via_from(f_tr_HostPort(g_pars.subscr.remote_sip_host, g_pars.subscr.ipsec_remote_port_s)),
				authorization := authorization);
	var charstring sip_expect_str := log2str(exp_req);

	[] SIP.receive(exp_req) -> value g_rx_sip_req {
		var template (value) PDU_SIP_Response tx_resp;
		var Via via;
		var Contact contact;
		var CallidString sip_call_id;
		var template (value) From from_addr;
		var template (value) To to_addr;
		var template (value) Require require := ts_Require({"sec-agree"});
		var template (value) Supported supported := ts_Supported({"sec-agree"});
		var integer sip_seq_nr;

		if (early_ret == IMS_REG_EARLY_RET_BEFORE_Protected_100Trying) {
			return; /* Done */
		}

		sip_call_id := g_rx_sip_req.msgHeader.callId.callid;
		via := g_rx_sip_req.msgHeader.via;
		from_addr := g_rx_sip_req.msgHeader.fromField;
		to_addr := g_rx_sip_req.msgHeader.toField;
		sip_seq_nr := g_rx_sip_req.msgHeader.cSeq.seqNumber;

		/* Tx 100 Trying */
		tx_resp := ts_SIP_Response_Trying(sip_call_id,
					from_addr,
					to_addr,
					via,
					sip_seq_nr,
					"REGISTER",
					allow := omit,
					server := g_pars.server_name,
					userAgent := omit);
		SIP.send(tx_resp);

		/* Validate Digest Response: */
		f_ims_validate_Authorization_AKAv1MD5_Response(g_rx_sip_req.msgHeader.authorization, "REGISTER");

		/* Validate P-Access-Network-Info: */
		f_ims_validate_register_P_Access_Network_info(g_rx_sip_req, exp_present := true);

		if (early_ret == IMS_REG_EARLY_RET_BEFORE_Protected_200OK) {
			return; /* Done */
		}

		g_pars.subscr.p_associated_uri := valueof(ts_P_Associated_Uri({
				ts_P_Assoc_uri_spec(ts_NameAddr(ts_SipUrl(ts_HostPort(g_pars.realm),
									  ts_UserInfo(g_pars.subscr.msisdn),
									  scheme := "sip"))),
				ts_P_Assoc_uri_spec(ts_NameAddr(ts_SipUrl(ts_HostPort(g_pars.subscr.msisdn),
									  omit,
									  scheme := "tel"))),
				ts_P_Assoc_uri_spec(g_rx_sip_req.msgHeader.toField.addressField.nameAddr)
			}));

		contact := g_rx_sip_req.msgHeader.contact;
		f_ims_validate_register_contact(contact);
		f_ims_parse_register_contact(contact);
		g_pars.subscr.registered_contact := contact;
		/* Set expires= to configured value: RFC3261 10.3 8) */
		for (var integer i := 0; i < lengthof(contact.contactBody.contactAddresses); i := i + 1) {
			contact.contactBody.contactAddresses[i].contactParams :=
				valueof({ ts_Param("expires", int2str(g_pars.subscr.registrar_expires)) });
		}

		/* Tx 200 OK */
		to_addr.toParams := f_sip_param_set(to_addr.toParams, "tag", f_sip_rand_tag());
		tx_resp := ts_SIP_Response(sip_call_id,
			from_addr,
			to_addr,
			"REGISTER", 200,
			sip_seq_nr,
			"OK",
			via,
			contact := contact,
			p_associated_uri := g_pars.subscr.p_associated_uri,
			require := require,
			server := g_pars.server_name,
			supported := supported,
			userAgent := omit);
		SIP.send(tx_resp);
		if (g_pars.subscr.close_tcp_after_registration) {
			f_IMS_tcp_close();
		}
	}
	[fail_others] as_SIP_fail_resp(sip_expect_str);
	[fail_others] as_SIP_fail_req(sip_expect_str);
}

/* Peer wants to unregister, accept it: */
altstep as_IMS_unregister(boolean fail_others := true) runs on IMS_ConnHdlr
{
	var template (present) PDU_SIP_Request exp_req :=
		tr_SIP_REGISTER(g_pars.registrar_sip_req_uri,
				?,
				tr_From(),
				tr_To(),
				tr_Via_from(f_tr_HostPort(g_pars.subscr.remote_sip_host, g_pars.subscr.ipsec_remote_port_s)),
				expires := tr_Expires(int2str(0)),
				require := tr_Require(superset("sec-agree")),
				security_client := tr_Security_client(superset(tr_Security_mechanism("ipsec-3gpp",
												     superset(tr_Param("alg","hmac-sha-1-96"))))),
				supported := tr_Supported(superset("path", "sec-agree")));
	var charstring sip_expect_str := log2str(exp_req);

	[] SIP.receive(exp_req) -> value g_rx_sip_req {
		var template (value) PDU_SIP_Response tx_resp;
		var Via via;
		var CallidString sip_call_id;
		var Contact contact;
		var template (value) From from_addr;
		var template (value) To to_addr;
		var template (value) CommaParam_List digestCln ;
		var template (value) WwwAuthenticate wwwAuthenticate;
		var template (value) Security_server security_server;
		var template (value) Require require := ts_Require({"sec-agree"});
		var template (value) Supported supported := ts_Supported({"sec-agree"});
		var template (present) Authorization authorization;
		var integer sip_seq_nr;

		sip_call_id := g_rx_sip_req.msgHeader.callId.callid;
		via := g_rx_sip_req.msgHeader.via;
		via.viaBody[0].viaParams := f_sip_param_set(via.viaBody[0].viaParams, "rport", "1234"); /* TODO: set remote src port of the REGISTER */
		from_addr := g_rx_sip_req.msgHeader.fromField;
		to_addr := g_rx_sip_req.msgHeader.toField;
		sip_seq_nr := g_rx_sip_req.msgHeader.cSeq.seqNumber;

		contact := g_rx_sip_req.msgHeader.contact;
		f_ims_validate_register_contact(contact);

		/* Validate P-Access-Network-Info: 3GPP TS 24.229 5.1.2A.1.1
		 * "If available to the UE (as defined in the access technology specific annexes for each access technology), the UE shall
		 * insert a P-Access-Network-Info header field into any request for a dialog, any subsequent request (except CANCEL
		 * requests) or response (except CANCEL responses) within a dialog or any request for a standalone method (see
		 * subclause 7.2A.4). Insertion of the P-Access-Network-Info header field into the ACK request is optional."
		 */
		f_ims_validate_register_P_Access_Network_info(g_rx_sip_req, exp_present := true);


		/* Tx 100 Tyring */
		tx_resp := ts_SIP_Response_Trying(sip_call_id,
					from_addr,
					to_addr,
					via,
					sip_seq_nr,
					"REGISTER",
					allow := omit,
					server := g_pars.server_name,
					userAgent := omit);
		SIP.send(tx_resp);

		/* Change all Contact parameters to expires=0: */
		for (var integer i := 0; i < lengthof(contact.contactBody.contactAddresses); i := i + 1) {
			contact.contactBody.contactAddresses[i].contactParams := valueof({ ts_Param("expires", "0") });
		}
		g_pars.subscr.registered_contact := omit;
		/* Tx 200 OK */
		to_addr.toParams := f_sip_param_set(to_addr.toParams, "tag", f_sip_rand_tag());
		tx_resp := ts_SIP_Response(sip_call_id,
			from_addr,
			to_addr,
			"REGISTER", 200,
			sip_seq_nr,
			"OK",
			via,
			contact := contact,
			p_associated_uri := g_pars.subscr.p_associated_uri,
			require := require,
			server := g_pars.server_name,
			supported := supported,
			userAgent := omit);
		SIP.send(tx_resp);
	}
	[fail_others] as_SIP_fail_resp(sip_expect_str);
	[fail_others] as_SIP_fail_req(sip_expect_str);
}

private function f_IMS_gen_new_Via() runs on IMS_ConnHdlr return Via
{
	var charstring branch_value;
	var Via via := g_pars.local_via;

	branch_value := f_sip_gen_branch(f_sip_Addr_Union_to_str(g_pars.subscr.cp.from_addr.addressField),
					 f_sip_Addr_Union_to_str(valueof(g_pars.subscr.cp.to_addr.addressField)),
					 g_pars.subscr.cp.sip_call_id,
					 g_pars.subscr.cp.sip_seq_nr);
	via.viaBody[0].viaParams := f_sip_param_set(via.viaBody[0].viaParams, "branch", branch_value);
	return via;
}

private function f_IMS_mt_call_tx_invite(Via via) runs on IMS_ConnHdlr
{
	var template (value) PDU_SIP_Request req;
	var template (present) From from_addr_exp;
	var template (present) To to_addr_exp;
	var template (omit) Min_SE min_SE := omit;
	var template (omit) Session_expires session_expires := omit;
	var template (omit) Supported supported := omit;
	var OptionTag_List supported_list := {};
	var charstring tx_sdp;
	var Contact calling_contact;

	/* RFC 3261 8.1.1.3 From */
	from_addr_exp := tr_From(tr_Addr_Union_from_val(g_pars.subscr.cp.from_addr.addressField), *);
	to_addr_exp := tr_To(tr_Addr_Union_from_val(g_pars.subscr.cp.to_addr.addressField), *);
	calling_contact := valueof(ts_Contact({
					ts_ContactAddress(g_pars.subscr.cp.calling.addr, omit)
				}));

	if (g_pars.subscr.cp.support_precondition_ext) {
		/* indicate the support for "reliable provisional response"
		 * and "preconditions mechanism" */
		supported_list := supported_list & { "100rel", "precondition" };
		tx_sdp := f_gen_sdp(IMS_GEN_SDP_MO_INVITE);
	} else {
		/* Don't add any preconditions to SDP: */
		tx_sdp := f_gen_sdp(IMS_GEN_SDP_None);
	}

	if (g_pars.subscr.cp.mt.support_timer_enable) {
		supported_list := supported_list & { "timer" };
		if (g_pars.subscr.cp.mt.support_timer_session_expires > 0) {
			session_expires := ts_Session_expires(int2str(g_pars.subscr.cp.mt.support_timer_session_expires));
			min_SE := ts_Min_SE(int2str(g_pars.subscr.cp.mt.support_timer_min_se));
		}
	}

	if (lengthof(supported_list) > 0) {
		supported := ts_Supported(supported_list);
	}

	req := ts_SIP_INVITE(g_pars.subscr.cp.sip_call_id,
			     g_pars.subscr.cp.from_addr,
			     g_pars.subscr.cp.to_addr,
			     via,
			     calling_contact,
			     g_pars.subscr.cp.sip_seq_nr,
			     accept := ts_Accept({ ts_AcceptBody("application/sdp"), ts_AcceptBody("application/3gpp-ims+xml") }),
			     min_SE := min_SE,
			     session_expires := session_expires,
			     supported := supported,
			     body := tx_sdp);

	SIP.send(req);
}

/* IMS Core starts a call towards the peer: 3GPP TS 24.229 5.1.3.1 */
function f_IMS_mt_call_setup() runs on IMS_ConnHdlr
{
	var template (value) PDU_SIP_Request req;
	var template (present) PDU_SIP_Response exp;
	var template (present) From from_addr_exp;
	var template (present) To to_addr_exp;
	var Via via;
	var template (omit) Require require := omit;
	var charstring tx_sdp;
	var default d_trying, d_ringing;
	var Contact calling_contact, called_contact;
	var integer sip_seq_nr;

	/* RFC 3261 8.1.1.3 From */
	g_pars.subscr.cp.from_addr := valueof(ts_From(g_pars.subscr.cp.calling.addr, g_pars.subscr.cp.calling.params));
	g_pars.subscr.cp.from_addr.fromParams := f_sip_param_set(g_pars.subscr.cp.from_addr.fromParams, "tag", f_sip_rand_tag());
	g_pars.subscr.cp.to_addr := valueof(ts_To(g_pars.subscr.cp.called.addr, g_pars.subscr.cp.called.params));
	from_addr_exp := tr_From(tr_Addr_Union_from_val(g_pars.subscr.cp.from_addr.addressField), *);
	to_addr_exp := tr_To(tr_Addr_Union_from_val(g_pars.subscr.cp.to_addr.addressField), *);
	calling_contact := valueof(ts_Contact({
					ts_ContactAddress(g_pars.subscr.cp.calling.addr, omit)
				}));
	via := f_IMS_gen_new_Via();

	f_IMS_mt_call_tx_invite(via);

	sip_seq_nr := g_pars.subscr.cp.sip_seq_nr;

	/* Conditionally match and accept 100 Trying. */
	exp := tr_SIP_Response_Trying(g_pars.subscr.cp.sip_call_id,
			from_addr_exp,
			to_addr_exp,
			f_tr_Via_response(via),
			sip_seq_nr, "INVITE");
	d_trying := activate(as_SIP_ignore_resp(exp));

	if (g_pars.subscr.cp.mt.tx_coord_cmd_session_progress) {
		/* Signal used to inform that Dedicated bearer can be established: */
		COORD.send(IMS_COORD_CMD_CALL_SESSION_PROGRESS);
	}

	if (g_pars.subscr.cp.require_precondition_ext) {
		var template (present) SDP_attribute_list preconds;
		/* Rx 183 Session Progress */
		exp := tr_SIP_Response_SessionProgress(
				g_pars.subscr.cp.sip_call_id,
				from_addr_exp,
				to_addr_exp,
				f_tr_Via_response(via),
				sip_seq_nr, "INVITE",
				require := tr_Require(superset("100rel", "precondition")),
				rseq := tr_RSeq(?),
				body := ?);
		alt {
		[] SIP.receive(exp) -> value g_rx_sip_resp {
			f_SDP_decodeMessage(g_rx_sip_resp.messageBody, g_pars.subscr.cp.peer_sdp);
		};
		[] SIP.receive(tr_SIP_Response_Ringing(?, ?, ?)) -> value g_rx_sip_resp {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
						log2str(g_name & ": Expected 183 Session Progress instead of 180 Ringing: ",
							g_rx_sip_resp));
			}
		}

		/* Validate SDP in Session Progress contains the preconditions:
		 * a=curr:qos local none
		 * a=curr:qos remote none
		 * a=des:qos mandatory local sendrecv
		 * a=des:qos mandatory remote sendrecv
		 * a=conf:qos remote sendrecv
		*/
		preconds := superset(
			tr_SDP_curr(c_SDP_PRECON_STATUS_TYPE_local,  c_SDP_PRECON_DIR_TAG_none),
			tr_SDP_curr(c_SDP_PRECON_STATUS_TYPE_remote, c_SDP_PRECON_DIR_TAG_none),
			tr_SDP_des(c_SDP_PRECON_STRENGTH_TAG_mandatory, c_SDP_PRECON_STATUS_TYPE_local, c_SDP_PRECON_DIR_TAG_sendrecv),
			tr_SDP_des(c_SDP_PRECON_STRENGTH_TAG_mandatory,  c_SDP_PRECON_STATUS_TYPE_remote, c_SDP_PRECON_DIR_TAG_sendrecv),
			tr_SDP_conf(c_SDP_PRECON_STATUS_TYPE_remote,  c_SDP_PRECON_DIR_TAG_sendrecv));
		if (not ispresent(g_pars.subscr.cp.peer_sdp.media_list[0].attributes) or
			not match(g_pars.subscr.cp.peer_sdp.media_list[0].attributes, preconds)) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
						log2str(g_name & ": Unexpected precondition attrs in Session Progress : ",
							g_pars.subscr.cp.peer_sdp.media_list[0].attributes));
		}

		called_contact := g_rx_sip_resp.msgHeader.contact;
		/* Update To with the tags received from peer: */
		g_pars.subscr.cp.to_addr := g_rx_sip_resp.msgHeader.toField;

		/* Tx PRACK */
		req := ts_SIP_PRACK(called_contact.contactBody.contactAddresses[0].addressField.nameAddr.addrSpec,
				    g_pars.subscr.cp.sip_call_id,
				    g_pars.subscr.cp.from_addr,
				    g_pars.subscr.cp.to_addr,
				    via,
				    g_rx_sip_resp.msgHeader.cSeq.seqNumber + 1,
				    rack := ts_RAck(g_rx_sip_resp.msgHeader.rseq.response_num,
						    g_rx_sip_resp.msgHeader.cSeq.seqNumber,
						    "INVITE"),
				    body := omit);
		SIP.send(req);

		/* Rx 200 OK (PRACK) */
		exp := tr_SIP_Response(g_pars.subscr.cp.sip_call_id,
				       from_addr_exp,
				       to_addr_exp,
				       f_tr_Via_response(via),
				       omit,
				       "PRACK", 200,
				       g_rx_sip_resp.msgHeader.cSeq.seqNumber + 1, "OK",
				       body := omit);
		as_SIP_expect_resp(exp);

		/* Tx UPDATE */
		tx_sdp := f_gen_sdp(IMS_GEN_SDP_MO_UPDATE);
		req := ts_SIP_UPDATE(called_contact.contactBody.contactAddresses[0].addressField.nameAddr.addrSpec,
				     g_pars.subscr.cp.sip_call_id,
				     g_pars.subscr.cp.from_addr,
				     g_pars.subscr.cp.to_addr,
				     via,
				     g_rx_sip_resp.msgHeader.cSeq.seqNumber + 1,
				     contact := calling_contact,
				     require := ts_Require({"sec-agree", "precondition"}),
				     body := tx_sdp);
		SIP.send(req);

		/* Rx 200 OK (UPDATE) */
		exp := tr_SIP_Response(g_pars.subscr.cp.sip_call_id,
				       from_addr_exp,
				       to_addr_exp,
				       f_tr_Via_response(via),
				       called_contact,
				       "UPDATE", 200,
				       g_rx_sip_resp.msgHeader.cSeq.seqNumber + 1, "OK",
				       body := ?);
		as_SIP_expect_resp(exp);
		f_SDP_decodeMessage(g_rx_sip_resp.messageBody, g_pars.subscr.cp.peer_sdp);

		/* Validate SDP in 200 OK (UPDATE) contains the preconditions:
		 * a=curr:qos local sendrecv
		 * a=curr:qos remote sendrecv
		 * a=des:qos mandatory local sendrecv
		 * a=des:qos mandatory remote sendrecv
		*/
		preconds := superset(
			tr_SDP_curr(c_SDP_PRECON_STATUS_TYPE_local,  c_SDP_PRECON_DIR_TAG_sendrecv),
			tr_SDP_curr(c_SDP_PRECON_STATUS_TYPE_remote, c_SDP_PRECON_DIR_TAG_sendrecv),
			tr_SDP_des(c_SDP_PRECON_STRENGTH_TAG_mandatory, c_SDP_PRECON_STATUS_TYPE_local, c_SDP_PRECON_DIR_TAG_sendrecv),
			tr_SDP_des(c_SDP_PRECON_STRENGTH_TAG_mandatory,  c_SDP_PRECON_STATUS_TYPE_remote, c_SDP_PRECON_DIR_TAG_sendrecv));
		if (not ispresent(g_pars.subscr.cp.peer_sdp.media_list[0].attributes) or
			not match(g_pars.subscr.cp.peer_sdp.media_list[0].attributes, preconds)) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
						log2str(g_name & ": Unexpected precondition attrs in 200 OK (UPDATE): ",
							g_pars.subscr.cp.peer_sdp.media_list[0].attributes));
		}

		g_pars.subscr.cp.sip_seq_nr := g_rx_sip_resp.msgHeader.cSeq.seqNumber + 1;
	}
	g_pars.subscr.cp.sip_seq_nr := g_pars.subscr.cp.sip_seq_nr + 1;

	/* Conditionally match and accept 180 Ringing */
	exp := tr_SIP_Response_Ringing(g_pars.subscr.cp.sip_call_id,
			from_addr_exp,
			to_addr_exp,
			f_tr_Via_response(via),
			sip_seq_nr, "INVITE");
	d_ringing := activate(as_SIP_ignore_resp(exp));

	/* Wait for 200 OK (INVITE) answer */
	exp := tr_SIP_Response(
			g_pars.subscr.cp.sip_call_id,
			from_addr_exp,
			to_addr_exp,
			f_tr_Via_response(via),
			?,
			"INVITE", 200,
			sip_seq_nr, "OK",
			body := *);
	as_SIP_expect_resp(exp, fail_others := false);

	called_contact := g_rx_sip_resp.msgHeader.contact;

	deactivate(d_trying);
	deactivate(d_ringing);

	/* Make sure "audio" tag set in Contact header */
	f_ims_validate_INVITE_Contact(g_rx_sip_resp.msgHeader.contact);

	/* Update To with the tags received from peer: */
	g_pars.subscr.cp.to_addr := g_rx_sip_resp.msgHeader.toField;

	/* Transmit ACK */
	req := ts_SIP_ACK(called_contact.contactBody.contactAddresses[0].addressField.nameAddr.addrSpec,
			  g_pars.subscr.cp.sip_call_id,
			  g_pars.subscr.cp.from_addr,
			  g_pars.subscr.cp.to_addr,
			  via,
			  g_pars.subscr.cp.sip_seq_nr,
			  omit);
	SIP.send(req);
	g_pars.subscr.cp.sip_seq_nr := g_pars.subscr.cp.sip_seq_nr + 1;
}

/* IMS Core starts a call towards the peer and gets rejected. */
function f_IMS_mt_call_rejected(template (present) integer exp_status_code := 486,
				template (present) charstring exp_reason := "Busy Here") runs on IMS_ConnHdlr
{
	var template (value) PDU_SIP_Request req;
	var template (present) PDU_SIP_Response exp;
	var default d_trying, d_ringing, d_sessprog;
	var Via via;

	g_pars.subscr.cp.from_addr := valueof(ts_From(g_pars.subscr.cp.calling.addr, g_pars.subscr.cp.calling.params));
	g_pars.subscr.cp.from_addr.fromParams := f_sip_param_set(g_pars.subscr.cp.from_addr.fromParams, "tag", f_sip_rand_tag());
	g_pars.subscr.cp.to_addr := valueof(ts_To(g_pars.subscr.cp.called.addr, g_pars.subscr.cp.called.params));
	via := f_IMS_gen_new_Via();
	f_IMS_mt_call_tx_invite(via);

	/* Conditionally match and accept 100 Trying. */
	exp := tr_SIP_Response_Trying(g_pars.subscr.cp.sip_call_id,
				      ?, ?,
				      f_tr_Via_response(via),
				      g_pars.subscr.cp.sip_seq_nr, "INVITE");
	d_trying := activate(as_SIP_ignore_resp(exp));
	/* Conditionally match and accept 183 Session Progress. */
	exp := tr_SIP_Response_SessionProgress(g_pars.subscr.cp.sip_call_id,
					       ?, ?,
					       f_tr_Via_response(via),
					       g_pars.subscr.cp.sip_seq_nr, "INVITE");
	d_sessprog := activate(as_SIP_ignore_resp(exp));

	/* Wait for 486 Busy Here (INVITE) answer */
	exp := tr_SIP_Response(g_pars.subscr.cp.sip_call_id,
			       ?, ?,
			       f_tr_Via_response(via),
			       *,
			       "INVITE", exp_status_code,
			       g_pars.subscr.cp.sip_seq_nr, exp_reason,
			       body := omit);
	as_SIP_expect_resp(exp, fail_others := false);

	deactivate(d_sessprog);
	deactivate(d_trying);

	/* Update To with the tags received from peer: */
	g_pars.subscr.cp.to_addr := g_rx_sip_resp.msgHeader.toField;

	/* Transmit ACK */
	req := ts_SIP_ACK(ts_SipUrl_from_Addr_Union(g_pars.subscr.cp.called.addr),
			  g_pars.subscr.cp.sip_call_id,
			  g_pars.subscr.cp.from_addr,
			  g_pars.subscr.cp.to_addr,
			  via,
			  g_pars.subscr.cp.sip_seq_nr,
			  omit);
	SIP.send(req);
	g_pars.subscr.cp.sip_seq_nr := g_pars.subscr.cp.sip_seq_nr + 1;
}

/* Tx BYE: */
function f_IMS_do_call_hangup() runs on IMS_ConnHdlr
{
	var template (value) PDU_SIP_Request req;
	var template (present) PDU_SIP_Response exp_resp;
	var Via via := f_IMS_gen_new_Via();

	/* Transmit ACK */
	req := ts_SIP_BYE(g_pars.subscr.cp.sip_call_id,
			  g_pars.subscr.cp.from_addr,
			  g_pars.subscr.cp.to_addr,
			  via,
			  g_pars.subscr.cp.sip_seq_nr,
			  omit);
	SIP.send(req);

	/* Wait for OK answer */
	exp_resp := tr_SIP_Response(
			g_pars.subscr.cp.sip_call_id,
			g_pars.subscr.cp.from_addr,
			tr_To(tr_Addr_Union_from_val(g_pars.subscr.cp.to_addr.addressField), *),
			f_tr_Via_response(via),
			*,
			"BYE", 200,
			g_pars.subscr.cp.sip_seq_nr, "OK");
	as_SIP_expect_resp(exp_resp);

	g_pars.subscr.cp.sip_seq_nr := g_pars.subscr.cp.sip_seq_nr + 1;
}

private function f_ConnHdlr_parse_initial_SIP_INVITE(PDU_SIP_Request rx_sip_req) runs on IMS_ConnHdlr
{
	f_SDP_decodeMessage(rx_sip_req.messageBody, g_pars.subscr.cp.peer_sdp);
	log("Rx Initial MO INVITE decoded SDP: ", g_pars.subscr.cp.peer_sdp);

	/* Obtain params: */
	g_pars.subscr.cp.sip_call_id := rx_sip_req.msgHeader.callId.callid;
	g_pars.subscr.cp.from_addr := rx_sip_req.msgHeader.fromField;
	g_pars.subscr.cp.to_addr := rx_sip_req.msgHeader.toField;
	g_pars.subscr.cp.to_addr.toParams := f_sip_param_set(g_pars.subscr.cp.to_addr.toParams, "tag", f_sip_rand_tag());
	g_pars.subscr.cp.sip_seq_nr := rx_sip_req.msgHeader.cSeq.seqNumber;
}

/* Peer is calling us, accept it: */
altstep as_IMS_mo_call_accept(boolean exp_update_to_direct_rtp := false,
			      boolean fail_others := true) runs on IMS_ConnHdlr
{
	/* 3GPP TS 24.229 5.1.3.1 Initial INVITE request */
	var template (present) PDU_SIP_Request exp_req :=
		tr_SIP_INVITE(f_tr_SipUrl_opt_defport(ts_SipUrl_from_Addr_Union(g_pars.subscr.cp.called.addr)),
			      ?,
			      tr_From(tr_Addr_Union_from_val(g_pars.subscr.cp.calling.addr), *),
			      tr_To(tr_Addr_Union_from_val(g_pars.subscr.cp.called.addr), *),
			      tr_Via_from(f_tr_HostPort(g_pars.subscr.remote_sip_host, g_pars.subscr.ipsec_remote_port_s)),
			      ?,
			      accept := tr_Accept(superset(tr_AcceptBody("application/sdp"), tr_AcceptBody("application/3gpp-ims+xml"))),
			      p_early_media := tr_P_Early_Media(superset("supported")),
			      supported := tr_Supported(superset("timer")),
			      body := ?);
	var charstring sip_expect_str := log2str(exp_req);

	[] SIP.receive(exp_req) -> value g_rx_sip_req {
		var template (value) PDU_SIP_Response tx_resp;
		var Via invite_via;
		var template (omit) Require require := omit;
		var template (omit) Session_expires session_expires := omit;
		var template (omit) Supported supported := omit;
		var OptionTag_List supported_list := {};
		var OptionTag_List require_list := {};
		var template (omit) charstring tx_sdp;
		var integer invite_seq_nr;
		var boolean peer_support_precondition := match(g_rx_sip_req.msgHeader.supported.optionsTags,
							       superset("100rel", "precondition"));

		/* Obtain params: */
		f_ConnHdlr_parse_initial_SIP_INVITE(g_rx_sip_req);
		invite_via := g_rx_sip_req.msgHeader.via;
		invite_seq_nr := g_pars.subscr.cp.sip_seq_nr;

		f_ims_validate_register_P_Access_Network_info(g_rx_sip_req, exp_present := true);
		f_ims_validate_invite_P_Preferred_Service(g_rx_sip_req, exp_present := true);
		f_ims_validate_INVITE_Contact(g_rx_sip_req.msgHeader.contact);
		f_ims_validate_INVITE_SDP(g_pars.subscr.cp.peer_sdp);

		if (g_pars.subscr.cp.mo.support_timer_enable) {
			supported_list := supported_list & { "timer" };
			if (g_pars.subscr.cp.mo.support_timer_session_expires > 0) {
				session_expires := ts_Session_expires(int2str(g_pars.subscr.cp.mo.support_timer_session_expires),
									      {ts_Param("refresher", "uac")});
			}
		}
		if (lengthof(supported_list) > 0) {
			supported := ts_Supported(supported_list);
		}
		if (g_pars.subscr.cp.mo.support_timer_exp_min_se > 0) {
			if (not ispresent(g_rx_sip_req.msgHeader.min_SE)) {
				Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
					log2str(g_name & ": Missing 'Min_SE' header in INVITE: ", g_rx_sip_req));
			}
			if (str2int(g_rx_sip_req.msgHeader.min_SE.deltaSec) != g_pars.subscr.cp.mo.support_timer_exp_min_se) {
				Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
					log2str(g_name & ": Received unexpected Min_SE := ",
						g_rx_sip_req.msgHeader.min_SE.deltaSec,
						"\nvs exp := ", g_pars.subscr.cp.mo.support_timer_exp_min_se));
			}
		}

		if (g_pars.subscr.cp.require_precondition_ext and not peer_support_precondition) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
						log2str(g_name & ": Missing '100rel,precondition' in INVITE Supported header: ",
						g_rx_sip_req.msgHeader.supported));
		}

		/* Tx 100 Tyring */
		tx_resp := ts_SIP_Response_Trying(g_pars.subscr.cp.sip_call_id,
						   g_pars.subscr.cp.from_addr,
						   g_pars.subscr.cp.to_addr,
						   invite_via,
						   g_pars.subscr.cp.sip_seq_nr,
						   "INVITE",
						   allow := omit,
						   server := g_pars.server_name,
						   userAgent := omit);
		SIP.send(tx_resp);

		if (g_pars.subscr.cp.mo.tx_coord_cmd_invite_trying) {
			/* Signal used to inform that Dedicated bearer can be established: */
			COORD.send(IMS_COORD_CMD_CALL_TRYING);
		}

		/* Use precondition ? */
		if (g_pars.subscr.cp.require_precondition_ext or
		    (g_pars.subscr.cp.support_precondition_ext and peer_support_precondition)) {
			var template (present) SDP_attribute_list preconds;
			/* Validate SDP in INVITE contains the preconditions:
			 * a=curr:qos local none
			 * a=curr:qos remote none
			 * a=des:qos mandatory local sendrecv
			 * a=des:qos optional remote sendrecv
			 */
			preconds := superset(
				tr_SDP_curr(c_SDP_PRECON_STATUS_TYPE_local,  c_SDP_PRECON_DIR_TAG_none),
				tr_SDP_curr(c_SDP_PRECON_STATUS_TYPE_remote, c_SDP_PRECON_DIR_TAG_none),
				tr_SDP_des(c_SDP_PRECON_STRENGTH_TAG_mandatory, c_SDP_PRECON_STATUS_TYPE_local, c_SDP_PRECON_DIR_TAG_sendrecv),
				tr_SDP_des(c_SDP_PRECON_STRENGTH_TAG_optional,  c_SDP_PRECON_STATUS_TYPE_remote, c_SDP_PRECON_DIR_TAG_sendrecv));
			if (not ispresent(g_pars.subscr.cp.peer_sdp.media_list[0].attributes) or
			    not match(g_pars.subscr.cp.peer_sdp.media_list[0].attributes, preconds)) {
				Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
							log2str(g_name & ": Unexpected precondition attrs in INVITE : ",
								g_pars.subscr.cp.peer_sdp.media_list[0].attributes,
								" vs exp: ", preconds));
			}

			/* Tx 183 Session Progress */
			tx_sdp := f_gen_sdp(IMS_GEN_SDP_MT_Session_Progress);
			tx_resp := ts_SIP_Response_SessionProgress(g_pars.subscr.cp.sip_call_id,
							g_pars.subscr.cp.from_addr,
							g_pars.subscr.cp.to_addr,
							invite_via,
							g_pars.subscr.cp.sip_seq_nr,
							p_early_media := ts_P_Early_Media({"recvonly"}),
							rseq := ts_RSeq(1),
							body := tx_sdp);
			SIP.send(tx_resp);

			/* Rx PRACK */
			exp_req := tr_SIP_PRACK(f_tr_SipUrl_opt_defport(ts_SipUrl_from_Addr_Union(g_pars.subscr.cp.called.addr)),
					g_pars.subscr.cp.sip_call_id,
					g_pars.subscr.cp.from_addr,
					g_pars.subscr.cp.to_addr,
					f_tr_Via_response(invite_via),
					g_pars.subscr.cp.sip_seq_nr + 1,
					rack := tr_RAck(1, g_pars.subscr.cp.sip_seq_nr, "INVITE"),
					body := omit);
			as_SIP_expect_req(exp_req);

			/* Tx 200 OK (PRACK) */
			tx_resp := ts_SIP_Response(g_pars.subscr.cp.sip_call_id,
						g_pars.subscr.cp.from_addr,
						g_pars.subscr.cp.to_addr,
						"PRACK", 200,
						g_pars.subscr.cp.sip_seq_nr + 1,
						"OK",
						g_rx_sip_req.msgHeader.via /* PRACK's new branch */,
						body := omit);
			SIP.send(tx_resp);

			/* Rx UPDATE */
			exp_req := tr_SIP_UPDATE(f_tr_SipUrl_opt_defport(ts_SipUrl_from_Addr_Union(g_pars.subscr.cp.called.addr)),
					g_pars.subscr.cp.sip_call_id,
					g_pars.subscr.cp.from_addr,
					g_pars.subscr.cp.to_addr,
					f_tr_Via_response(invite_via),
					g_pars.subscr.cp.sip_seq_nr + 2,
					require := tr_Require(superset("sec-agree", "precondition")),
					supported := tr_Supported(superset("100rel", "timer")),
					body := ?);
			as_SIP_expect_req(exp_req);
			f_SDP_decodeMessage(g_rx_sip_req.messageBody, g_pars.subscr.cp.peer_sdp);

			/* Validate SDP in UPDATE contains the preconditions:
			 * a=curr:qos local sendrecv
			 * a=curr:qos remote none
			 * a=des:qos mandatory local sendrecv
			 * a=des:qos mandatory remote sendrecv
			 */
			preconds := superset(
				tr_SDP_curr(c_SDP_PRECON_STATUS_TYPE_local,  c_SDP_PRECON_DIR_TAG_sendrecv),
				tr_SDP_curr(c_SDP_PRECON_STATUS_TYPE_remote, c_SDP_PRECON_DIR_TAG_none),
				tr_SDP_des(c_SDP_PRECON_STRENGTH_TAG_mandatory, c_SDP_PRECON_STATUS_TYPE_local, c_SDP_PRECON_DIR_TAG_sendrecv),
				tr_SDP_des(c_SDP_PRECON_STRENGTH_TAG_mandatory,  c_SDP_PRECON_STATUS_TYPE_remote, c_SDP_PRECON_DIR_TAG_sendrecv));
			if (not ispresent(g_pars.subscr.cp.peer_sdp.media_list[0].attributes) or
			    not match(g_pars.subscr.cp.peer_sdp.media_list[0].attributes, preconds)) {
				Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
							log2str(g_name & ": Unexpected precondition attrs in UPDATE: ",
								g_pars.subscr.cp.peer_sdp.media_list[0].attributes,
								" vs exp: ", preconds));
			}

			/* Tx 200 OK (UPDATE) */
			tx_sdp := f_gen_sdp(IMS_GEN_SDP_MT_UPDATE_200OK);
			tx_resp := ts_SIP_Response(g_pars.subscr.cp.sip_call_id,
						g_pars.subscr.cp.from_addr,
						g_pars.subscr.cp.to_addr,
						"UPDATE", 200,
						g_pars.subscr.cp.sip_seq_nr + 2,
						"OK",
						g_rx_sip_req.msgHeader.via /* UPDATE's new branch */,
						session_expires := session_expires,
						supported := supported,
						body := tx_sdp);
			SIP.send(tx_resp);

			/* Update to latest used seq_nr: */
			g_pars.subscr.cp.sip_seq_nr := g_pars.subscr.cp.sip_seq_nr + 2;
			/* 200 OK (INVITE) has no SDP if we use precondition: */
			tx_sdp := omit;
		} else {
			/* Check no precondition is sent in SDP */
			if (ispresent(g_pars.subscr.cp.peer_sdp.media_list[0].attributes) and
			    match (g_pars.subscr.cp.peer_sdp.media_list[0].attributes, superset(tr_SDP_curr_present,
												tr_SDP_des_present,
												tr_SDP_conf_present))) {
				Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
							log2str(g_name & ": Unexpected precondition attrs in INVITE: ",
								g_pars.subscr.cp.peer_sdp.media_list[0].attributes));
			}
			/* 200 OK (INVITE) has SDP if no precondition is used: */
			tx_sdp := f_gen_sdp();
		}

		/* Tx 180 Ringing */
		tx_resp := ts_SIP_Response_Ringing(g_pars.subscr.cp.sip_call_id,
						g_pars.subscr.cp.from_addr,
						g_pars.subscr.cp.to_addr,
						invite_via,
						invite_seq_nr);
		SIP.send(tx_resp);


		/* Tx 200 OK */
		if (g_pars.subscr.cp.mo.support_timer_enable) {
			require_list := require_list & { "timer" };
		}
		if (lengthof(require_list) > 0) {
			require := ts_Require(require_list);
		}

		tx_sdp := f_gen_sdp();
		tx_resp := ts_SIP_Response(g_pars.subscr.cp.sip_call_id,
					   g_pars.subscr.cp.from_addr,
					   g_pars.subscr.cp.to_addr,
					   "INVITE", 200,
					   invite_seq_nr,
					   "OK",
					   invite_via,
					   require := require,
					   session_expires := session_expires,
					   supported := supported,
					   body := tx_sdp);
		SIP.send(tx_resp);

		/* Wait for ACK */
		exp_req := tr_SIP_ACK(f_tr_SipUrl_opt_defport(ts_SipUrl_from_Addr_Union(g_pars.subscr.cp.called.addr)),
				      g_pars.subscr.cp.sip_call_id,
				      g_pars.subscr.cp.from_addr,
				      g_pars.subscr.cp.to_addr,
				      f_tr_Via_response(invite_via),
				      invite_seq_nr, *);
		as_SIP_expect_req(exp_req);
	}
	[fail_others] as_SIP_fail_resp(sip_expect_str);
	[fail_others] as_SIP_fail_req(sip_expect_str);

}

/* Call is terminated by peer: */
altstep as_IMS_exp_call_hangup(template (present) integer exp_seq_nr := ?, boolean fail_others := true) runs on IMS_ConnHdlr
{
	var template (present) PDU_SIP_Request exp_req :=
		tr_SIP_BYE(f_tr_SipUrl_opt_defport(ts_SipUrl_from_Addr_Union(g_pars.subscr.cp.called.addr)),
			   g_pars.subscr.cp.sip_call_id,
			   g_pars.subscr.cp.from_addr,
			   g_pars.subscr.cp.to_addr,
			   tr_Via_from(f_tr_HostPort(g_pars.subscr.remote_sip_host, g_pars.subscr.ipsec_remote_port_s)),
			   exp_seq_nr);
	var charstring sip_expect_str := log2str(exp_req);

	[] SIP.receive(exp_req) -> value g_rx_sip_req {
		var template (value) PDU_SIP_Response tx_resp;
		var charstring tx_sdp;
		var Via via;

		/* Update parameters: */
		g_pars.subscr.cp.sip_seq_nr := g_rx_sip_req.msgHeader.cSeq.seqNumber;
		/* "branch" has changed: */
		via := g_rx_sip_req.msgHeader.via;

		/* Tx 200 OK */
		tx_sdp := f_gen_sdp();
		tx_resp := ts_SIP_Response(g_pars.subscr.cp.sip_call_id,
					g_pars.subscr.cp.from_addr,
					g_pars.subscr.cp.to_addr,
					"BYE", 200,
					g_pars.subscr.cp.sip_seq_nr,
					"OK",
					via,
					body := tx_sdp);
		SIP.send(tx_resp);
	}
	[fail_others] as_SIP_fail_resp(sip_expect_str);
	[fail_others] as_SIP_fail_req(sip_expect_str);
}

private function f_IMS_answer_call_refresh(PDU_SIP_Request req) runs on IMS_ConnHdlr {
	var template (value) PDU_SIP_Response tx_resp;
	/* Tx 200 OK response*/
	tx_resp := ts_SIP_Response(g_pars.subscr.cp.sip_call_id,
				g_pars.subscr.cp.from_addr,
				g_pars.subscr.cp.to_addr,
				req.msgHeader.cSeq.method, 200,
				req.msgHeader.cSeq.seqNumber,
				"OK",
				req.msgHeader.via,
				session_expires := ts_Session_expires(int2str(g_pars.subscr.cp.mo.support_timer_session_expires),
									{ts_Param("refresher", "uac")}),
				supported := ts_Supported({"timer"}),
				body := omit);
	SIP.send(tx_resp);
}
/* Session Timer, RFC 4028 */
altstep as_IMS_exp_call_refresh() runs on IMS_ConnHdlr
{
	/* RFC4028 section 7.4. It can be either INVITE or UPDATE: */
	var template (present) PDU_SIP_Request exp_req_invite :=
		tr_SIP_INVITE(f_tr_SipUrl_opt_defport(ts_SipUrl_from_Addr_Union(g_pars.subscr.cp.called.addr)),
			      ?,
			      tr_From(tr_Addr_Union_from_val(g_pars.subscr.cp.calling.addr), *),
			      tr_To(tr_Addr_Union_from_val(g_pars.subscr.cp.called.addr), *),
			      tr_Via_from(f_tr_HostPort(g_pars.subscr.remote_sip_host, g_pars.subscr.ipsec_remote_port_s)),
			      ?,
			      supported := tr_Supported(superset("timer")),
			      body := *);

	var template (present) PDU_SIP_Request exp_req_update :=
		tr_SIP_UPDATE(f_tr_SipUrl_opt_defport(ts_SipUrl_from_Addr_Union(g_pars.subscr.cp.called.addr)),
			      g_pars.subscr.cp.sip_call_id,
			      g_pars.subscr.cp.from_addr,
			      g_pars.subscr.cp.to_addr,
			      tr_Via_from(f_tr_HostPort(g_pars.subscr.remote_sip_host, g_pars.subscr.ipsec_remote_port_s)),
			      ?,
			      body := *);

	[] SIP.receive(exp_req_invite) -> value g_rx_sip_req {
		f_IMS_answer_call_refresh(g_rx_sip_req);
		g_pars.subscr.cp.sip_seq_nr := g_rx_sip_req.msgHeader.cSeq.seqNumber;
	}
	[] SIP.receive(exp_req_update) -> value g_rx_sip_req {
		f_IMS_answer_call_refresh(g_rx_sip_req);
		g_pars.subscr.cp.sip_seq_nr := g_rx_sip_req.msgHeader.cSeq.seqNumber;
	}
}

private altstep as_IMS_exp_call_holdresume(template (present) SDP_attribute exp_dir := tr_SDP_sendonly,
					   charstring tx_dir := "recvonly") runs on IMS_ConnHdlr
{
	/* RFC4028 section 7.4. It can be either INVITE or UPDATE: */
	var template (present) PDU_SIP_Request exp_req_invite :=
		tr_SIP_INVITE(f_tr_SipUrl_opt_defport(ts_SipUrl_from_Addr_Union(g_pars.subscr.cp.called.addr)),
			      ?,
			      tr_From(tr_Addr_Union_from_val(g_pars.subscr.cp.calling.addr), *),
			      tr_To(tr_Addr_Union_from_val(g_pars.subscr.cp.called.addr), *),
			      tr_Via_from(f_tr_HostPort(g_pars.subscr.remote_sip_host, g_pars.subscr.ipsec_remote_port_s)),
			      ?,
			      body := ?);

	[] SIP.receive(exp_req_invite) -> value g_rx_sip_req {
		var template (present) PDU_SIP_Request exp_req;
		var template (value) PDU_SIP_Response tx_resp;
		var charstring tx_sdp;

		f_SDP_decodeMessage(g_rx_sip_req.messageBody, g_pars.subscr.cp.peer_sdp);
		g_pars.subscr.cp.sip_seq_nr := g_rx_sip_req.msgHeader.cSeq.seqNumber;

		/* Check a=$exp_dir in SDP */
		if (not ispresent(g_pars.subscr.cp.peer_sdp.media_list[0].attributes) or
		    not match (g_pars.subscr.cp.peer_sdp.media_list[0].attributes, superset(exp_dir))) {
			Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
						log2str(g_name & ": Expected re-INVITE SDP attribute a=", exp_dir, " in: ",
							g_pars.subscr.cp.peer_sdp.media_list[0].attributes));
		}

		tx_sdp := f_gen_sdp(dir := tx_dir);
		/* Tx 200 OK response*/
		tx_resp := ts_SIP_Response(g_pars.subscr.cp.sip_call_id,
					   g_pars.subscr.cp.from_addr,
					   g_pars.subscr.cp.to_addr,
					   g_rx_sip_req.msgHeader.cSeq.method, 200,
					   g_rx_sip_req.msgHeader.cSeq.seqNumber,
					   "OK",
					   g_rx_sip_req.msgHeader.via,
					   body := tx_sdp);
		SIP.send(tx_resp);

		/* Wait for ACK */
		exp_req := tr_SIP_ACK(f_tr_SipUrl_opt_defport(ts_SipUrl_from_Addr_Union(g_pars.subscr.cp.called.addr)),
				      g_pars.subscr.cp.sip_call_id,
				      g_pars.subscr.cp.from_addr,
				      g_pars.subscr.cp.to_addr,
				      f_tr_Via_response(g_rx_sip_req.msgHeader.via),
				      g_rx_sip_req.msgHeader.cSeq.seqNumber,
				      body := omit);
		as_SIP_expect_req(exp_req);
	}
}
altstep as_IMS_exp_call_hold() runs on IMS_ConnHdlr
{
	[] as_IMS_exp_call_holdresume(tr_SDP_sendonly, "recvonly");
}
altstep as_IMS_exp_call_resume() runs on IMS_ConnHdlr
{
	[] as_IMS_exp_call_holdresume(tr_SDP_sendrecv, "sendrecv");
}

function f_IMS_tcp_close() runs on IMS_ConnHdlr
{
	var ASP_SIP_close v_close:={addr:={
		remote_host := g_pars.subscr.remote_sip_host,
		remote_port := g_pars.subscr.ipsec_remote_port_c,
		local_host := g_pars.local_sip_host,
		local_port := g_pars.local_sip_port,
		protocol := TCP_E
		}}
	log("Closing TCP connection: ", v_close);
	SIP.send(v_close);
}

}