gerrit-log
Threads by month
- ----- 2026 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2025 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2024 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2023 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2022 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- 1 participants
- 97203 discussions
[M] Change in osmo-ttcn3-hacks[master]: smf: Introduce test TC_n11_handover_inter_ngran_n2_direct_dl_forward
by laforge 25 Nov '26
by laforge 25 Nov '26
25 Nov '26
laforge has submitted this change. ( https://gerrit.osmocom.org/c/osmo-ttcn3-hacks/+/44163?usp=email )
Change subject: smf: Introduce test TC_n11_handover_inter_ngran_n2_direct_dl_forward
......................................................................
smf: Introduce test TC_n11_handover_inter_ngran_n2_direct_dl_forward
Change-Id: Ib2d134f688ce3a3f2e67ad6edfa589c94971abf9
---
M smf/SMF_Session_CT_5G.ttcn
M smf/SMF_Tests.ttcn
M smf/expected-results.xml
3 files changed, 53 insertions(+), 14 deletions(-)
Approvals:
osmith: Looks good to me, but someone else must approve
laforge: Looks good to me, approved
Jenkins Builder: Verified
diff --git a/smf/SMF_Session_CT_5G.ttcn b/smf/SMF_Session_CT_5G.ttcn
index e64d23d..f81ff22 100644
--- a/smf/SMF_Session_CT_5G.ttcn
+++ b/smf/SMF_Session_CT_5G.ttcn
@@ -418,7 +418,8 @@
/* 3GPP TS 23.502 Figure 4.9.1.3.2-1 step 11f
* 3GPP TS 29.502 Table 6.1.3.3.4.2.2-2, 6.1.6.2.5 Type: SmContextUpdatedData
* Expect to receive "200 OK with multipart body containing SBI + NGAP Handover Command */
-altstep as_n11_200_OK_handover_command(HTTP2_Msg http2_tx)
+altstep as_n11_200_OK_handover_command(HTTP2_Msg http2_tx,
+ template (present) NGAP_IEs.HandoverCommandTransfer exp_ho_cmd_transfer := ?)
runs on SMF_Session_CT {
var HTTP2_Msg http2_rx;
var template (present) HTTP2_Msg http2_exp_rx :=
@@ -437,7 +438,7 @@
var SmContextUpdatedData sm_ctx_updated_data;
var NGAP_IEs.PDUSessionResourceSetupRequestTransfer setup_req_transf;
- var NGAP_IEs.HandoverCommandTransfer ho_cmd_transfer
+ var NGAP_IEs.HandoverCommandTransfer ho_cmd_transfer;
/* Decode 1st part: SBI json: */
f_dec_SmContextUpdatedData(parts[0].data, sm_ctx_updated_data); // TODO: check returned integer.
@@ -445,14 +446,10 @@
/* Decode 2nd part: NGAP Handover Command: */
ho_cmd_transfer := dec_NGAP_HandoverCommandTransfer(parts[1].data);
- var F_TEID fteid := g_pars.pfcp_pars.gtp1u_pars.access.local;
- if (not match(ho_cmd_transfer,
- mw_handoverCommandTransfer(p_dLForwardingUP_TNLInformation :=
- mw_uPTransportLayerInformation_gTPTunnel(
- m_gTPTunnel(p_tla := oct2bit(fteid.ipv4_address),
- p_gtp_teid := fteid.teid))))) {
+ if (not match(ho_cmd_transfer, exp_ho_cmd_transfer)) {
Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
- log2str("Got unexpected HandoverCommandTransfer ", ho_cmd_transfer));
+ log2str("Got unexpected HandoverCommandTransfer ", ho_cmd_transfer,
+ " vs exp ", exp_ho_cmd_transfer));
}
}
}
@@ -464,6 +461,7 @@
var template (value) SmContextUpdateData sm_ctx_update;
var template (value) octetstring body_enc;
var HTTP2_Msg http2_tx;
+ var template UPTransportLayerInformation p_dLForwardingUP_TNLInformation := omit;
sm_ctx_update := ts_SmContextUpdateData(ueLocation := f_ts_UserLocation(),
n2SmInfo := TS29502_Nsmf_PDUSession_Templates.ts_RefToBinaryData("ngap-sm"),
@@ -503,10 +501,18 @@
as_pfcp_sess_mod_req(exp_create_pdr_list := {create_pdr},
exp_create_far_list := {create_far},
tx_created_pdr := created_pdr);
+
+ var F_TEID fteid := g_pars.pfcp_pars.gtp1u_pars.access.local;
+ p_dLForwardingUP_TNLInformation :=
+ mw_uPTransportLayerInformation_gTPTunnel(
+ m_gTPTunnel(p_tla := oct2bit(fteid.ipv4_address),
+ p_gtp_teid := fteid.teid));
}
/* Successful answer with HandoverCommandTransfer: */
- as_n11_200_OK_handover_command(http2_tx);
+ var template (present) NGAP_IEs.HandoverCommandTransfer exp_ho_cmd_transfer :=
+ mw_handoverCommandTransfer(p_dLForwardingUP_TNLInformation := p_dLForwardingUP_TNLInformation);
+ as_n11_200_OK_handover_command(http2_tx, exp_ho_cmd_transfer);
f_http2_adapter_close(idx := http2_tx.conn_id);
setverdict(pass);
@@ -515,7 +521,8 @@
/* 3GPP TS 23.502 Figure 4.9.1.3.3-1 step 7-11
* 3GPP TS 29.502 5.2.2.3.4.3 N2 Handover Execution */
-function f_n11_update_sm_context_handover_complete(UPTransportLayerInformation dl_utla)
+function f_n11_update_sm_context_handover_complete(UPTransportLayerInformation dl_utla,
+ boolean exp_forward_tun_teardown := true)
runs on SMF_Session_CT {
var template (value) SmContextUpdateData sm_ctx_update;
var template (value) octetstring body_enc;
@@ -538,9 +545,11 @@
network_instance := tr_PFCP_Network_Instance(g_pars.apn)));
as_pfcp_sess_mod_req(exp_update_far_list := { exp_update_far });
- /* The forwarding tunnel is removed: */
- as_pfcp_sess_mod_req(remove_pdr_list := { tr_PFCP_Remove_PDR(pdr_id := int2oct(5, 2)) },
- remove_far_list := { tr_PFCP_Remove_FAR(far_id := 4) });
+ if (exp_forward_tun_teardown) {
+ /* The forwarding tunnel is removed: */
+ as_pfcp_sess_mod_req(remove_pdr_list := { tr_PFCP_Remove_PDR(pdr_id := int2oct(5, 2)) },
+ remove_far_list := { tr_PFCP_Remove_FAR(far_id := 4) });
+ }
/* Successful answer: */
var HTTP2_Msg http2_rx;
diff --git a/smf/SMF_Tests.ttcn b/smf/SMF_Tests.ttcn
index 7a132cb..6ffb502 100644
--- a/smf/SMF_Tests.ttcn
+++ b/smf/SMF_Tests.ttcn
@@ -921,6 +921,34 @@
}
/* 3GPP TS 23.502 4.9.1.3 Inter NG-RAN node N2 based handover
+ * No "DL Forwarding UP TNL Information" in NGAP Handover Request ACK AMF->SMF,
+ * only "DL NG-U UP TNL Information" IE is to be used.*/
+private function f_TC_n11_handover_inter_ngran_n2_direct_dl_forward() runs on SMF_Session_CT {
+ var template (value) UPTransportLayerInformation dl_forward_utla;
+ var template (value) UPTransportLayerInformation dl_utla;
+ f_n11_create_session();
+
+ /* Final gNB endpoint where to send DL traffic from the UPF after Handover is completed: */
+ dl_utla := m_uPTransportLayerInformation_gTPTunnel(
+ m_gTPTunnel(p_tla := oct2bit(f_inet_addr(g_pars.namf.ran_gtpu_ip)),
+ p_gtp_teid := '11223344'O));
+
+ f_n11_update_sm_context_handover_request_ack(dl_utla := dl_utla);
+ f_n11_update_sm_context_handover_complete(valueof(dl_utla), exp_forward_tun_teardown := false);
+ f_n11_delete_session();
+ setverdict(pass);
+}
+testcase TC_n11_handover_inter_ngran_n2_direct_dl_forward() runs on SMF_Test_CT {
+ var SMF_Session_CT vc_conn;
+ var SessionPars pars := f_SessionPars(20,
+ rat_type := GTP2C_RAT_NR);
+ f_init();
+ vc_conn := f_start_handler(refers(f_TC_n11_handover_inter_ngran_n2_direct_dl_forward), pars);
+ vc_conn.done;
+ f_shutdown();
+}
+
+/* 3GPP TS 23.502 4.9.1.3 Inter NG-RAN node N2 based handover
* Set "DL Forwarding UP TNL Information" in NGAP Handover Request ACK AMF->SMF:
* The SMF should update the UPF to point to it until the handover is completed,
* at which point the "DL NG-U UP TNL Information" IE is to be used.*/
@@ -1094,6 +1122,7 @@
execute( TC_n11_createSession_pfcp_sess_est_timeout() );
execute( TC_n11_createSession_pfcp_sess_est_timeout_no_pdu_sess_est_rej() );
+ execute( TC_n11_handover_inter_ngran_n2_direct_dl_forward() );
execute( TC_n11_handover_inter_ngran_n2_indirect_dl_forward() );
execute( TC_5g_pfcp_heartbeat_timeout() );
diff --git a/smf/expected-results.xml b/smf/expected-results.xml
index e2d0150..ae436ff 100644
--- a/smf/expected-results.xml
+++ b/smf/expected-results.xml
@@ -23,6 +23,7 @@
<testcase classname='SMF_Tests' name='TC_n11_createSession_deleteSession_250_ipv4v6' time='MASKED'/>
<testcase classname='SMF_Tests' name='TC_n11_createSession_pfcp_sess_est_timeout' time='MASKED'/>
<testcase classname='SMF_Tests' name='TC_n11_createSession_pfcp_sess_est_timeout_no_pdu_sess_est_rej' time='MASKED'/>
+ <testcase classname='SMF_Tests' name='TC_n11_handover_inter_ngran_n2_direct_dl_forward' time='MASKED'/>
<testcase classname='SMF_Tests' name='TC_n11_handover_inter_ngran_n2_indirect_dl_forward' time='MASKED'/>
<testcase classname='SMF_Tests' name='TC_5g_pfcp_heartbeat_timeout' time='MASKED'/>
<testcase classname='SMF_Tests' name='TC_5g_pfcp_heartbeat_recovery_timestamp' time='MASKED'/>
--
To view, visit https://gerrit.osmocom.org/c/osmo-ttcn3-hacks/+/44163?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email
Gerrit-MessageType: merged
Gerrit-Project: osmo-ttcn3-hacks
Gerrit-Branch: master
Gerrit-Change-Id: Ib2d134f688ce3a3f2e67ad6edfa589c94971abf9
Gerrit-Change-Number: 44163
Gerrit-PatchSet: 3
Gerrit-Owner: pespin <pespin(a)sysmocom.de>
Gerrit-Reviewer: Jenkins Builder
Gerrit-Reviewer: laforge <laforge(a)osmocom.org>
Gerrit-Reviewer: osmith <osmith(a)sysmocom.de>
1
0
[L] Change in osmo-ttcn3-hacks[master]: smf: Introduce test TC_n11_handover_inter_ngran_n2_indirect_dl_forward
by laforge 25 Nov '26
by laforge 25 Nov '26
25 Nov '26
laforge has submitted this change. ( https://gerrit.osmocom.org/c/osmo-ttcn3-hacks/+/44157?usp=email )
Change subject: smf: Introduce test TC_n11_handover_inter_ngran_n2_indirect_dl_forward
......................................................................
smf: Introduce test TC_n11_handover_inter_ngran_n2_indirect_dl_forward
Related: SYS#8338
Change-Id: I11609e8b75d5ff03d2ca635599d99a7523b6787e
---
M library/HTTP2_Msg.ttcn
M library/PFCP_Templates.ttcn
M library/TS29502_Nsmf_PDUSession_Templates.ttcn
M library/ngap/NGAP_EncDec.cc
M library/ngap/NGAP_Types.ttcn
M smf/SMF_Session_CT.ttcn
M smf/SMF_Session_CT_5G.ttcn
M smf/SMF_Tests.ttcn
M smf/expected-results.xml
9 files changed, 359 insertions(+), 16 deletions(-)
Approvals:
laforge: Looks good to me, approved
Jenkins Builder: Verified
osmith: Looks good to me, but someone else must approve
diff --git a/library/HTTP2_Msg.ttcn b/library/HTTP2_Msg.ttcn
index 23cb945..8d7ac89 100644
--- a/library/HTTP2_Msg.ttcn
+++ b/library/HTTP2_Msg.ttcn
@@ -86,6 +86,12 @@
body := body
);
+template (present) HTTP2_Msg
+tr_HTTP2_Msg_200_OK(template (present) IPL4asp_Types.ConnectionId conn_id := ?,
+ template (present) integer stream_id := ?,
+ template HTTP2_header_list headers := *,
+ template HTTP2_Data_frame body := omit) :=
+tr_HTTP2_Msg_Status(conn_id, stream_id, 200, headers, body);
template (value) HTTP2_Msg
ts_HTTP2_Msg_200_OK(template (value) IPL4asp_Types.ConnectionId conn_id,
template (value) integer stream_id,
diff --git a/library/PFCP_Templates.ttcn b/library/PFCP_Templates.ttcn
index 5eea706..4e9ea05 100644
--- a/library/PFCP_Templates.ttcn
+++ b/library/PFCP_Templates.ttcn
@@ -1294,6 +1294,15 @@
}
}
+template (present) Remove_FAR
+tr_PFCP_Remove_FAR(template (present) LIN4_BO_LAST far_id := ?) := {
+ elementIdentifier := 16,
+ lengthIndicator := ?,
+ grouped_ie := {
+ far_id := tr_PFCP_FAR_ID(far_id)
+ }
+}
+
/* 8.2.36 PDR ID */
template (value) PDR_ID
ts_PFCP_PDR_ID(template (value) OCT2 pdr_id) := {
@@ -1358,6 +1367,16 @@
}
}
+
+template (present) Remove_PDR
+tr_PFCP_Remove_PDR(template (present) OCT2 pdr_id := ?) := {
+ elementIdentifier := 15,
+ lengthIndicator := ?,
+ grouped_ie := {
+ pdr_id := tr_PFCP_PDR_ID(pdr_id)
+ }
+}
+
/* 7.5.2.4 Create URR IE within PFCP Session Establishment Request */
template (value) Create_URR
ts_PFCP_Create_URR(template (value) LIN4_BO_LAST urr_id,
@@ -1480,7 +1499,8 @@
}
}
-template (value) Created_PDR ts_PFCP_Created_PDR(PDR_ID pdr_id, template (value) F_TEID local_F_TEID) := {
+template (value) Created_PDR ts_PFCP_Created_PDR(template (value) PDR_ID pdr_id,
+ template (value) F_TEID local_F_TEID) := {
elementIdentifier := 8,
lengthIndicator := 0,
grouped_ie := {
@@ -1578,6 +1598,11 @@
}
template (present) PDU_PFCP
tr_PFCP_Session_Mod_Req(template (present) OCT8 seid := ?,
+ template Remove_PDR_list remove_pdr_list := *,
+ template Remove_FAR_list remove_far_list := *,
+ template Create_PDR_list create_pdr_list := *,
+ template Create_FAR_list create_far_list := *,
+ template Update_PDR_list update_pdr_list := *,
template Update_FAR_list update_far_list := *)
modifies tr_PDU_PFCP_ := {
seid := seid,
@@ -1590,13 +1615,13 @@
remove_QER_list := *,
remove_BAR := *,
remove_traffic_endpoint := *,
- create_PDR_list := *,
- create_FAR_list := *,
+ create_PDR_list := create_pdr_list,
+ create_FAR_list := create_far_list,
create_URR_list := *,
create_QER_list := *,
create_BAR := *,
create_traffic_endpoint := *,
- update_PDR_list := *,
+ update_PDR_list := update_pdr_list,
update_FAR_list := update_far_list,
update_URR_list := *,
update_QER_list := *,
@@ -1615,7 +1640,9 @@
template (value) PDU_PFCP
ts_PFCP_Session_Mod_Resp(template (value) LIN3_BO_LAST seq_nr,
template (value) OCT8 seid,
- template (value) Cause cause := ts_PFCP_Cause(PFCP_Cause_REQUEST_ACCEPTED))
+ template (value) Cause cause := ts_PFCP_Cause(PFCP_Cause_REQUEST_ACCEPTED),
+ template (omit) Created_PDR created_pdr := omit,
+ template (omit) Created_Traffic_Endpoint created_updated_traffic_endpoint := omit)
modifies ts_PDU_PFCP_ := {
seid := seid,
sequence_number := seq_nr,
@@ -1623,13 +1650,13 @@
pfcp_session_modification_response := {
cause := cause,
offending_IE := omit,
- created_PDR := omit,
+ created_PDR := created_pdr,
load_control_information := omit,
overload_control_information := omit,
usage_report := omit,
failed_rule_id := omit,
additional_usage_reports_information := omit,
- created_updated_traffic_endpoint := omit
+ created_updated_traffic_endpoint := created_updated_traffic_endpoint
}
}
}
diff --git a/library/TS29502_Nsmf_PDUSession_Templates.ttcn b/library/TS29502_Nsmf_PDUSession_Templates.ttcn
index b19ab71..e0df82c 100644
--- a/library/TS29502_Nsmf_PDUSession_Templates.ttcn
+++ b/library/TS29502_Nsmf_PDUSession_Templates.ttcn
@@ -19,10 +19,18 @@
ts_Nsmf_PDUSession_path_sm_context_release(template (value) charstring smContextRef)
:= c_Nsmf_PDUSession_path_sm_contexts & "/" & valueof(smContextRef) & "/release";
+template (present) HoState
+tr_HoState(template (present) HoState_enum enum_val := ?) := {
+ enum_val := enum_val
+}
+template (value) HoState
+ts_HoState(template (value) HoState_enum enum_val) := {
+ enum_val := enum_val
+}
+
type TS29502_Nsmf_PDUSession.SmContextCreateData.additionalHsmfSetIdList AdditionalHsmfSetIdList;
type TS29502_Nsmf_PDUSession.SmContextCreateData.additionalSmfSetIdList AdditionalSmfSetIdList;
type TS29502_Nsmf_PDUSession.SmContextCreateData.nrfOauth2Required NrfOauth2Required;
-
template (value) SmContextCreateData
ts_SmContextCreateData(
template (omit) TS29502_Nsmf_PDUSession.Supi supi := omit,
@@ -430,6 +438,56 @@
localOffloadingMgtAllowedInd := localOffloadingMgtAllowedInd
}
+/* 6.1.6.2.5 */
+template SmContextUpdatedData
+tr_SmContextUpdatedData(template UpCnxState upCnxState := *,
+ template HoState hoState := *,
+ template TS29502_Nsmf_PDUSession.SmContextUpdatedData.releaseEbiList releaseEbiList := *,
+ template TS29502_Nsmf_PDUSession.SmContextUpdatedData.allocatedEbiList allocatedEbiList := *,
+ template TS29502_Nsmf_PDUSession.SmContextUpdatedData.modifiedEbiList modifiedEbiList := *,
+ template RefToBinaryData n1SmMsg := *,
+ template RefToBinaryData n2SmInfo := *,
+ template N2SmInfoType n2SmInfoType := *,
+ template TS29502_Nsmf_PDUSession.SmContextUpdatedData.epsBearerSetup epsBearerSetup := *,
+ template boolean dataForwarding := *,
+ template TS29502_Nsmf_PDUSession.SmContextUpdatedData.n3DlForwardingTnlList n3DlForwardingTnlList := *,
+ template TS29502_Nsmf_PDUSession.SmContextUpdatedData.n3UlForwardingTnlList n3UlForwardingTnlList := *,
+ template TunnelInfo n9UlForwardingTunnel := *,
+ template Cause cause := *,
+ template boolean maAcceptedInd := *,
+ template SupportedFeatures supportedFeatures := *,
+ template Bytes forwardingFTeid := *,
+ template TS29502_Nsmf_PDUSession.SmContextUpdatedData.forwardingBearerContexts forwardingBearerContexts := *,
+ template NfInstanceId selectedSmfId := *,
+ template NfInstanceId selectedOldSmfId := *,
+ template Uri interPlmnApiRoot := *,
+ template AnchorSmfFeatures anchorSmfFeatures := *,
+ template PduSessionPriority pduSessionPrio := *) := {
+ upCnxState := upCnxState,
+ hoState := hoState,
+ releaseEbiList := releaseEbiList,
+ allocatedEbiList := allocatedEbiList,
+ modifiedEbiList := modifiedEbiList,
+ n1SmMsg := n1SmMsg,
+ n2SmInfo := n2SmInfo,
+ n2SmInfoType := n2SmInfoType,
+ epsBearerSetup := epsBearerSetup,
+ dataForwarding := dataForwarding,
+ n3DlForwardingTnlList := n3DlForwardingTnlList,
+ n3UlForwardingTnlList := n3UlForwardingTnlList,
+ n9UlForwardingTunnel := n9UlForwardingTunnel,
+ cause := cause,
+ maAcceptedInd := maAcceptedInd,
+ supportedFeatures := supportedFeatures,
+ forwardingFTeid := forwardingFTeid,
+ forwardingBearerContexts := forwardingBearerContexts,
+ selectedSmfId := selectedSmfId,
+ selectedOldSmfId := selectedOldSmfId,
+ interPlmnApiRoot := interPlmnApiRoot,
+ anchorSmfFeatures := anchorSmfFeatures,
+ pduSessionPrio := pduSessionPrio
+}
+
/* 6.1.6.2.6 */
template (value) SmContextReleaseData
ts_SmContextReleaseData(template (omit) Cause cause := omit,
diff --git a/library/ngap/NGAP_EncDec.cc b/library/ngap/NGAP_EncDec.cc
index d15cab6..991916c 100644
--- a/library/ngap/NGAP_EncDec.cc
+++ b/library/ngap/NGAP_EncDec.cc
@@ -209,6 +209,26 @@
return ret;
}
+OCTETSTRING enc__NGAP__HandoverCommandTransfer(const NGAP__IEs::HandoverCommandTransfer &p)
+{
+ TTCN_Buffer TTCN_buf;
+ TTCN_buf.clear();
+ p.encode(NGAP__IEs::HandoverCommandTransfer_descr_, TTCN_buf,
+ TTCN_EncDec::CT_PER, PER_ALIGNED);
+ return OCTETSTRING(TTCN_buf.get_len(), TTCN_buf.get_data());
+}
+
+NGAP__IEs::HandoverCommandTransfer dec__NGAP__HandoverCommandTransfer(const OCTETSTRING &stream)
+{
+ NGAP__IEs::HandoverCommandTransfer ret;
+ TTCN_Buffer TTCN_buf;
+ TTCN_buf.clear();
+ TTCN_buf.put_os(stream);
+ ret.decode(NGAP__IEs::HandoverCommandTransfer_descr_, TTCN_buf,
+ TTCN_EncDec::CT_PER, PER_ALIGNED);
+ return ret;
+}
+
OCTETSTRING enc__NGAP__HandoverRequiredTransfer(const NGAP__IEs::HandoverRequiredTransfer &p)
{
TTCN_Buffer TTCN_buf;
diff --git a/library/ngap/NGAP_Types.ttcn b/library/ngap/NGAP_Types.ttcn
index 08d0f22..1e80763 100644
--- a/library/ngap/NGAP_Types.ttcn
+++ b/library/ngap/NGAP_Types.ttcn
@@ -33,6 +33,10 @@
external function enc_NGAP_PathSwitchRequestTransfer(NGAP_IEs.PathSwitchRequestTransfer p) return octetstring;
external function dec_NGAP_PathSwitchRequestTransfer(in octetstring pdu) return NGAP_IEs.PathSwitchRequestTransfer;
+ external function enc_NGAP_HandoverCommandTransfer(NGAP_IEs.HandoverCommandTransfer p) return octetstring;
+ external function dec_NGAP_HandoverCommandTransfer(in octetstring pdu) return NGAP_IEs.HandoverCommandTransfer;
+
+
external function enc_NGAP_HandoverRequiredTransfer(NGAP_IEs.HandoverRequiredTransfer p) return octetstring;
external function dec_NGAP_HandoverRequiredTransfer(in octetstring pdu) return NGAP_IEs.HandoverRequiredTransfer;
diff --git a/smf/SMF_Session_CT.ttcn b/smf/SMF_Session_CT.ttcn
index 5eab61b..9396b9e 100644
--- a/smf/SMF_Session_CT.ttcn
+++ b/smf/SMF_Session_CT.ttcn
@@ -518,25 +518,51 @@
}
-function f_Session_tr_PFCP_Session_Mod_Req() runs on SMF_Session_CT return template (present) PDU_PFCP
-{
- return tr_PFCP_Session_Mod_Req(g_pars.pfcp_pars.local_f_seid.seid);
+function f_Session_tr_PFCP_Session_Mod_Req(template Remove_PDR_list remove_pdr_list := *,
+ template Remove_FAR_list remove_far_list := *,
+ template Create_PDR_list create_pdr_list := *,
+ template Create_FAR_list create_far_list := *,
+ template Update_PDR_list update_pdr_list := *,
+ template Update_FAR_list update_far_list := *)
+runs on SMF_Session_CT return template (present) PDU_PFCP {
+ return tr_PFCP_Session_Mod_Req(seid := g_pars.pfcp_pars.local_f_seid.seid,
+ remove_pdr_list := remove_pdr_list,
+ remove_far_list := remove_far_list,
+ create_pdr_list := create_pdr_list,
+ create_far_list := create_far_list,
+ update_pdr_list := update_pdr_list,
+ update_far_list := update_far_list);
}
-altstep as_pfcp_sess_mod_req()
+altstep as_pfcp_sess_mod_req(template Remove_PDR_list remove_pdr_list := *,
+ template Remove_FAR_list remove_far_list := *,
+ template Create_PDR_list exp_create_pdr_list := *,
+ template Create_FAR_list exp_create_far_list := *,
+ template Update_PDR_list exp_update_pdr_list := *,
+ template Update_FAR_list exp_update_far_list := *,
+ template (omit) Created_PDR tx_created_pdr := omit)
runs on SMF_Session_CT {
- var template (present) PDU_PFCP exp_req := f_Session_tr_PFCP_Session_Mod_Req();
+ var template (present) PDU_PFCP exp_req := f_Session_tr_PFCP_Session_Mod_Req(remove_pdr_list := remove_pdr_list,
+ remove_far_list := remove_far_list,
+ create_pdr_list := exp_create_pdr_list,
+ create_far_list := exp_create_far_list,
+ update_pdr_list := exp_update_pdr_list,
+ update_far_list := exp_update_far_list);
var PDU_PFCP req;
[] PFCP.receive(exp_req) -> value req {
- f_pfcp_sess_mod_resp(req);
+ f_pfcp_sess_mod_resp(req := req,
+ created_pdr := tx_created_pdr);
}
}
-function f_pfcp_sess_mod_resp(PDU_PFCP req) runs on SMF_Session_CT {
+function f_pfcp_sess_mod_resp(PDU_PFCP req,
+ template (omit) Created_PDR created_pdr)
+runs on SMF_Session_CT {
var template (value) PDU_PFCP resp;
resp := ts_PFCP_Session_Mod_Resp(seq_nr := req.sequence_number,
seid := g_pars.pfcp_pars.remote_cp_f_seid.seid,
- cause := ts_PFCP_Cause(PFCP_Cause_REQUEST_ACCEPTED));
+ cause := ts_PFCP_Cause(PFCP_Cause_REQUEST_ACCEPTED),
+ created_pdr := created_pdr);
PFCP.send(resp);
}
diff --git a/smf/SMF_Session_CT_5G.ttcn b/smf/SMF_Session_CT_5G.ttcn
index c818d94..e64d23d 100644
--- a/smf/SMF_Session_CT_5G.ttcn
+++ b/smf/SMF_Session_CT_5G.ttcn
@@ -38,6 +38,7 @@
import from NG_NAS_Osmo_Templates all;
import from NG_NAS_Functions all;
+import from PFCP_Types all;
import from PFCP_Templates all;
import from PFCP_Emulation all;
import from Mutex all;
@@ -414,6 +415,147 @@
setverdict(pass);
}
+/* 3GPP TS 23.502 Figure 4.9.1.3.2-1 step 11f
+ * 3GPP TS 29.502 Table 6.1.3.3.4.2.2-2, 6.1.6.2.5 Type: SmContextUpdatedData
+ * Expect to receive "200 OK with multipart body containing SBI + NGAP Handover Command */
+altstep as_n11_200_OK_handover_command(HTTP2_Msg http2_tx)
+runs on SMF_Session_CT {
+ var HTTP2_Msg http2_rx;
+ var template (present) HTTP2_Msg http2_exp_rx :=
+ tr_HTTP2_Msg_200_OK(conn_id := http2_tx.conn_id,
+ stream_id := http2_tx.stream_id,
+ headers := ?,
+ body := tr_HTTP2_Data_frame(stream_id := http2_tx.stream_id,
+ end_stream_flag := true,
+ data := ?));
+
+ [] as_http2_adapter_receive(http2_rx, http2_exp_rx, idx := http2_tx.conn_id) {
+ /* Split http2_rx.body.data into chunks since it is a multipart message: */
+ var charstring content_type_val := valueof(f_HTTP2_header_list_find_header(http2_rx.hb.headers, c_HTTP2_HDR_content_type));
+ var charstring boundary := f_HTTP2_header_content_type_multipart_val_get_boundary(content_type_val);
+ var HTTP2_multipart_part_list parts := f_HTTP2_multipart_msg_parse(http2_rx.body.data, boundary);
+
+ var SmContextUpdatedData sm_ctx_updated_data;
+ var NGAP_IEs.PDUSessionResourceSetupRequestTransfer setup_req_transf;
+ var NGAP_IEs.HandoverCommandTransfer ho_cmd_transfer
+
+ /* Decode 1st part: SBI json: */
+ f_dec_SmContextUpdatedData(parts[0].data, sm_ctx_updated_data); // TODO: check returned integer.
+ /* TODO: Match sm_ctx_updated_data against what is received. */
+
+ /* Decode 2nd part: NGAP Handover Command: */
+ ho_cmd_transfer := dec_NGAP_HandoverCommandTransfer(parts[1].data);
+ var F_TEID fteid := g_pars.pfcp_pars.gtp1u_pars.access.local;
+ if (not match(ho_cmd_transfer,
+ mw_handoverCommandTransfer(p_dLForwardingUP_TNLInformation :=
+ mw_uPTransportLayerInformation_gTPTunnel(
+ m_gTPTunnel(p_tla := oct2bit(fteid.ipv4_address),
+ p_gtp_teid := fteid.teid))))) {
+ Misc_Helpers.f_shutdown(__BFILE__, __LINE__, fail,
+ log2str("Got unexpected HandoverCommandTransfer ", ho_cmd_transfer));
+ }
+ }
+}
+
+/* 3GPP TS 23.502 Figure 4.9.1.3.2-1 step 11a, 11b */
+function f_n11_update_sm_context_handover_request_ack(template (value) UPTransportLayerInformation dl_utla,
+ template (omit) UPTransportLayerInformation dl_forward_utla := omit)
+runs on SMF_Session_CT {
+ var template (value) SmContextUpdateData sm_ctx_update;
+ var template (value) octetstring body_enc;
+ var HTTP2_Msg http2_tx;
+
+ sm_ctx_update := ts_SmContextUpdateData(ueLocation := f_ts_UserLocation(),
+ n2SmInfo := TS29502_Nsmf_PDUSession_Templates.ts_RefToBinaryData("ngap-sm"),
+ n2SmInfoType := ts_N2SmInfoType(HANDOVER_REQ_ACK));
+ var octetstring ngap_enc := f_ngap_pdu_gen_HandoverRequestAcknowledge(dl_utla := dl_utla,
+ dl_forward_utla := dl_forward_utla);
+
+ http2_tx := f_n11_prepare_update_sm_context(valueof(sm_ctx_update), ngap_enc);
+ f_http2_adapter_connect_send_smf(http2_tx, idx := http2_tx.conn_id);
+
+ /* SMF updates RAN GTPU IP addr+TEID info on UPF: */
+ if (isvalue(dl_forward_utla)) {
+ var OCT2 pdr_id := int2oct(5, 2);
+ var template (present) Create_PDR create_pdr :=
+ tr_PFCP_Create_PDR(pdr_id := pdr_id,
+ pdi := tr_PFCP_PDI(src_iface := PFCP_Src_Iface_ACCESS,
+ local_F_TEID := tr_PFCP_F_TEID(?, ?, '1'B, '1'B, omit, omit, omit, ?),
+ network_instance := tr_PFCP_Network_Instance(g_pars.apn),
+ source_interface_type := tr_PFCP_ThreeGPP_Interface_Type(28 /* SGW/UPF GTP-U interface for UL data forwarding */)),
+ ohr := tr_PFCP_Outer_Header_Removal(PFCP_OHR_GTP_U_UDP_IP),
+ far_id := 4);
+
+ var template (present) Outer_Header_Creation ohc :=
+ tr_PFCP_Outer_Header_Creation_GTP_ipv4(dl_forward_utla.gTPTunnel.gTP_TEID,
+ bit2oct(valueof(dl_forward_utla.gTPTunnel.transportLayerAddress)));
+ var template (present) Create_FAR create_far :=
+ tr_PFCP_Create_FAR(far_id := 4,
+ aa := tr_PFCP_Apply_Action(forw := '1'B),
+ fp := tr_PFCP_Forwarding_Parameters(dest_iface := PFCP_Dest_Iface_ACCESS,
+ ohc := ohc,
+ destination_interface_type := tr_PFCP_ThreeGPP_Interface_Type(10 /* SGW/UPF GTP-U interface for DL data forwarding */)));
+
+ var template (value) Created_PDR created_pdr :=
+ ts_PFCP_Created_PDR(pdr_id := ts_PFCP_PDR_ID(pdr_id),
+ local_F_TEID := g_pars.pfcp_pars.gtp1u_pars.access.local);
+
+ as_pfcp_sess_mod_req(exp_create_pdr_list := {create_pdr},
+ exp_create_far_list := {create_far},
+ tx_created_pdr := created_pdr);
+ }
+
+ /* Successful answer with HandoverCommandTransfer: */
+ as_n11_200_OK_handover_command(http2_tx);
+
+ f_http2_adapter_close(idx := http2_tx.conn_id);
+ setverdict(pass);
+}
+
+
+/* 3GPP TS 23.502 Figure 4.9.1.3.3-1 step 7-11
+ * 3GPP TS 29.502 5.2.2.3.4.3 N2 Handover Execution */
+function f_n11_update_sm_context_handover_complete(UPTransportLayerInformation dl_utla)
+runs on SMF_Session_CT {
+ var template (value) SmContextUpdateData sm_ctx_update;
+ var template (value) octetstring body_enc;
+ var HTTP2_Msg http2_tx;
+ var template (present) Outer_Header_Creation ohc;
+ var template (present) Update_FAR exp_update_far;
+
+ sm_ctx_update := ts_SmContextUpdateData(ueLocation := f_ts_UserLocation(),
+ hoState := ts_HoState(COMPLETED));
+ http2_tx := f_n11_prepare_update_sm_context(valueof(sm_ctx_update), omit);
+ f_http2_adapter_connect_send_smf(http2_tx, idx := http2_tx.conn_id);
+
+ /* The main DL FAR is updated with the new DL address+TEID after HO completed: */
+ ohc := tr_PFCP_Outer_Header_Creation_GTP_ipv4(dl_utla.gTPTunnel.gTP_TEID,
+ bit2oct(valueof(dl_utla.gTPTunnel.transportLayerAddress)));
+ exp_update_far := tr_PFCP_Update_FAR(far_id := 1,
+ aa := tr_PFCP_Apply_Action(forw := '1'B),
+ fp := tr_PFCP_Update_Forwarding_Parameters(dest_iface := tr_PFCP_Destination_Interface(PFCP_Dest_Iface_ACCESS),
+ ohc := ohc,
+ network_instance := tr_PFCP_Network_Instance(g_pars.apn)));
+ as_pfcp_sess_mod_req(exp_update_far_list := { exp_update_far });
+
+ /* The forwarding tunnel is removed: */
+ as_pfcp_sess_mod_req(remove_pdr_list := { tr_PFCP_Remove_PDR(pdr_id := int2oct(5, 2)) },
+ remove_far_list := { tr_PFCP_Remove_FAR(far_id := 4) });
+
+ /* Successful answer: */
+ var HTTP2_Msg http2_rx;
+ var template (present) HTTP2_Msg http2_exp_rx :=
+ tr_HTTP2_Msg_200_OK(conn_id := http2_tx.conn_id,
+ stream_id := http2_tx.stream_id,
+ headers := ?,
+ body := tr_HTTP2_Data_frame(stream_id := http2_tx.stream_id,
+ end_stream_flag := true,
+ data := decmatch(tr_SmContextUpdatedData(hoState := tr_HoState(COMPLETED)))));
+ as_http2_adapter_receive(http2_rx, http2_exp_rx, idx := http2_tx.conn_id);
+ f_http2_adapter_close(idx := http2_tx.conn_id);
+ setverdict(pass);
+}
+
/* 3GPP TS 29.502 5.2.2.4 Release SM Context service operation
* 3GPP TS 23.502 Figure 4.3.4.2-1 step 10a */
private function f_n11_prepare_release_sm_context(SmContextReleaseData sm_ctx_rel,
@@ -1077,6 +1219,25 @@
return enc_NGAP_PDUSessionResourceSetupResponseTransfer(setup_resp_transf);
}
+/* 3GPP TS 38.413 9.3.4.11 Handover Request Acknowledge Transfer */
+private function f_ngap_pdu_gen_HandoverRequestAcknowledge(template (value) UPTransportLayerInformation dl_utla,
+ template (omit) UPTransportLayerInformation dl_forward_utla := omit)
+runs on SMF_Session_CT return octetstring {
+ var template (value) UPTransportLayerInformation utla;
+ var template (value) QosFlowItemWithDataForwarding qos;
+ var NGAP_IEs.HandoverRequestAcknowledgeTransfer ho_req_ack_transf;
+ var integer qos_id := bit2int(g_pars.nas.qos_rules[0].u.creat.flowIdentifier);
+
+ /* Prepare Response for it: */
+ qos := m_qosFlowItemWithDataForwarding(qos_id,
+ m_dataForwardingAccepted(data_forwarding_accepted));
+ ho_req_ack_transf := valueof(m_handoverRequestAcknowledgeTransfer(p_dL_NGU_UP_TNLInformation := dl_utla,
+ p_qosFlowSetupResponseList := { qos },
+ p_dLForwardingUP_TNLInformation := dl_forward_utla));
+
+ return enc_NGAP_HandoverRequestAcknowledgeTransfer(ho_req_ack_transf);
+}
+
/************
* NG NAS
**************/
diff --git a/smf/SMF_Tests.ttcn b/smf/SMF_Tests.ttcn
index 9d8c968..7a132cb 100644
--- a/smf/SMF_Tests.ttcn
+++ b/smf/SMF_Tests.ttcn
@@ -36,6 +36,9 @@
import from HTTP2_Adapter all;
import from HTTP2_Server_Emulation all;
+import from NGAP_IEs language "ASN.1:2002" all;
+import from NGAP_Templates all;
+
import from NG_NAS_Templates all;
import from TS29502_Nsmf_PDUSession_Templates all;
@@ -917,6 +920,40 @@
f_shutdown();
}
+/* 3GPP TS 23.502 4.9.1.3 Inter NG-RAN node N2 based handover
+ * Set "DL Forwarding UP TNL Information" in NGAP Handover Request ACK AMF->SMF:
+ * The SMF should update the UPF to point to it until the handover is completed,
+ * at which point the "DL NG-U UP TNL Information" IE is to be used.*/
+private function f_TC_n11_handover_inter_ngran_n2_indirect_dl_forward() runs on SMF_Session_CT {
+ var template (value) UPTransportLayerInformation dl_forward_utla;
+ var template (value) UPTransportLayerInformation dl_utla;
+ f_n11_create_session();
+
+ /* Temporary gNB endpoint where to send DL traffic from the UPF during Handover: */
+ dl_forward_utla := m_uPTransportLayerInformation_gTPTunnel(
+ m_gTPTunnel(p_tla := oct2bit(f_inet_addr("1.2.3.4")),
+ p_gtp_teid := '12345678'O));
+ /* Final gNB endpoint where to send DL traffic from the UPF after Handover is completed: */
+ dl_utla := m_uPTransportLayerInformation_gTPTunnel(
+ m_gTPTunnel(p_tla := oct2bit(f_inet_addr(g_pars.namf.ran_gtpu_ip)),
+ p_gtp_teid := '11223344'O));
+
+ f_n11_update_sm_context_handover_request_ack(dl_utla := dl_utla,
+ dl_forward_utla := dl_forward_utla);
+ f_n11_update_sm_context_handover_complete(valueof(dl_utla));
+ f_n11_delete_session();
+ setverdict(pass);
+}
+testcase TC_n11_handover_inter_ngran_n2_indirect_dl_forward() runs on SMF_Test_CT {
+ var SMF_Session_CT vc_conn;
+ var SessionPars pars := f_SessionPars(20,
+ rat_type := GTP2C_RAT_NR);
+ f_init();
+ vc_conn := f_start_handler(refers(f_TC_n11_handover_inter_ngran_n2_indirect_dl_forward), pars);
+ vc_conn.done;
+ f_shutdown();
+}
+
/* Validate IUT detects PFCP Heartbeat timeout and recovers from it tearing down
* existing subscriber connections: */
@@ -1056,6 +1093,9 @@
execute( TC_n11_createSession_deleteSession_250_ipv4v6() );
execute( TC_n11_createSession_pfcp_sess_est_timeout() );
execute( TC_n11_createSession_pfcp_sess_est_timeout_no_pdu_sess_est_rej() );
+
+ execute( TC_n11_handover_inter_ngran_n2_indirect_dl_forward() );
+
execute( TC_5g_pfcp_heartbeat_timeout() );
execute( TC_5g_pfcp_heartbeat_recovery_timestamp() );
}
diff --git a/smf/expected-results.xml b/smf/expected-results.xml
index 3656cc4..e2d0150 100644
--- a/smf/expected-results.xml
+++ b/smf/expected-results.xml
@@ -23,6 +23,7 @@
<testcase classname='SMF_Tests' name='TC_n11_createSession_deleteSession_250_ipv4v6' time='MASKED'/>
<testcase classname='SMF_Tests' name='TC_n11_createSession_pfcp_sess_est_timeout' time='MASKED'/>
<testcase classname='SMF_Tests' name='TC_n11_createSession_pfcp_sess_est_timeout_no_pdu_sess_est_rej' time='MASKED'/>
+ <testcase classname='SMF_Tests' name='TC_n11_handover_inter_ngran_n2_indirect_dl_forward' time='MASKED'/>
<testcase classname='SMF_Tests' name='TC_5g_pfcp_heartbeat_timeout' time='MASKED'/>
<testcase classname='SMF_Tests' name='TC_5g_pfcp_heartbeat_recovery_timestamp' time='MASKED'/>
</testsuite>
--
To view, visit https://gerrit.osmocom.org/c/osmo-ttcn3-hacks/+/44157?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email
Gerrit-MessageType: merged
Gerrit-Project: osmo-ttcn3-hacks
Gerrit-Branch: master
Gerrit-Change-Id: I11609e8b75d5ff03d2ca635599d99a7523b6787e
Gerrit-Change-Number: 44157
Gerrit-PatchSet: 3
Gerrit-Owner: pespin <pespin(a)sysmocom.de>
Gerrit-Reviewer: Jenkins Builder
Gerrit-Reviewer: jolly <andreas(a)eversberg.eu>
Gerrit-Reviewer: laforge <laforge(a)osmocom.org>
Gerrit-Reviewer: osmith <osmith(a)sysmocom.de>
1
0
[S] Change in osmo-ttcn3-hacks[master]: smf: Introduce test TC_n11_handover_inter_ngran_n2_indirect_back_direct
by laforge 25 Nov '26
by laforge 25 Nov '26
25 Nov '26
Attention is currently required from: pespin.
laforge has posted comments on this change by pespin. ( https://gerrit.osmocom.org/c/osmo-ttcn3-hacks/+/44164?usp=email )
Change subject: smf: Introduce test TC_n11_handover_inter_ngran_n2_indirect_back_direct
......................................................................
Patch Set 2: Code-Review+2
--
To view, visit https://gerrit.osmocom.org/c/osmo-ttcn3-hacks/+/44164?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email
Gerrit-MessageType: comment
Gerrit-Project: osmo-ttcn3-hacks
Gerrit-Branch: master
Gerrit-Change-Id: I480b1a9b714d2b73bc39470ac6c676a982d2839b
Gerrit-Change-Number: 44164
Gerrit-PatchSet: 2
Gerrit-Owner: pespin <pespin(a)sysmocom.de>
Gerrit-Reviewer: Jenkins Builder
Gerrit-Reviewer: laforge <laforge(a)osmocom.org>
Gerrit-Reviewer: osmith <osmith(a)sysmocom.de>
Gerrit-Attention: pespin <pespin(a)sysmocom.de>
Gerrit-Comment-Date: Wed, 25 Nov 2026 14:05:54 +0000
Gerrit-HasComments: No
Gerrit-Has-Labels: Yes
1
0
[M] Change in osmo-ttcn3-hacks[master]: smf: Introduce test TC_n11_handover_inter_ngran_n2_direct_dl_forward
by laforge 25 Nov '26
by laforge 25 Nov '26
25 Nov '26
Attention is currently required from: pespin.
laforge has posted comments on this change by pespin. ( https://gerrit.osmocom.org/c/osmo-ttcn3-hacks/+/44163?usp=email )
Change subject: smf: Introduce test TC_n11_handover_inter_ngran_n2_direct_dl_forward
......................................................................
Patch Set 2: Code-Review+2
--
To view, visit https://gerrit.osmocom.org/c/osmo-ttcn3-hacks/+/44163?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email
Gerrit-MessageType: comment
Gerrit-Project: osmo-ttcn3-hacks
Gerrit-Branch: master
Gerrit-Change-Id: Ib2d134f688ce3a3f2e67ad6edfa589c94971abf9
Gerrit-Change-Number: 44163
Gerrit-PatchSet: 2
Gerrit-Owner: pespin <pespin(a)sysmocom.de>
Gerrit-Reviewer: Jenkins Builder
Gerrit-Reviewer: laforge <laforge(a)osmocom.org>
Gerrit-Reviewer: osmith <osmith(a)sysmocom.de>
Gerrit-Attention: pespin <pespin(a)sysmocom.de>
Gerrit-Comment-Date: Wed, 25 Nov 2026 14:05:49 +0000
Gerrit-HasComments: No
Gerrit-Has-Labels: Yes
1
0
[L] Change in osmo-ttcn3-hacks[master]: smf: Introduce test TC_n11_handover_inter_ngran_n2_indirect_dl_forward
by laforge 25 Nov '26
by laforge 25 Nov '26
25 Nov '26
Attention is currently required from: jolly, pespin.
laforge has posted comments on this change by pespin. ( https://gerrit.osmocom.org/c/osmo-ttcn3-hacks/+/44157?usp=email )
Change subject: smf: Introduce test TC_n11_handover_inter_ngran_n2_indirect_dl_forward
......................................................................
Patch Set 2: Code-Review+2
--
To view, visit https://gerrit.osmocom.org/c/osmo-ttcn3-hacks/+/44157?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email
Gerrit-MessageType: comment
Gerrit-Project: osmo-ttcn3-hacks
Gerrit-Branch: master
Gerrit-Change-Id: I11609e8b75d5ff03d2ca635599d99a7523b6787e
Gerrit-Change-Number: 44157
Gerrit-PatchSet: 2
Gerrit-Owner: pespin <pespin(a)sysmocom.de>
Gerrit-Reviewer: Jenkins Builder
Gerrit-Reviewer: jolly <andreas(a)eversberg.eu>
Gerrit-Reviewer: laforge <laforge(a)osmocom.org>
Gerrit-Reviewer: osmith <osmith(a)sysmocom.de>
Gerrit-Attention: pespin <pespin(a)sysmocom.de>
Gerrit-Attention: jolly <andreas(a)eversberg.eu>
Gerrit-Comment-Date: Wed, 25 Nov 2026 14:05:40 +0000
Gerrit-HasComments: No
Gerrit-Has-Labels: Yes
1
0
[L] Change in pysim[master]: contrib: CAT_TP admin server for RAM/RFM over BIP
by laforge 25 Nov '26
by laforge 25 Nov '26
25 Nov '26
laforge has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/43721?usp=email )
(
1 is the latest approved patch-set.
No files were changed between the latest approved patch-set and the submitted one.
)Change subject: contrib: CAT_TP admin server for RAM/RFM over BIP
......................................................................
contrib: CAT_TP admin server for RAM/RFM over BIP
Basically the UDP counterpart of scp81_admin_server.py, plain sockets:
- waits for the SYN caused by the the PUSH
- sends the queued C-APDUs as TS 102 225 secured packets, one per SDU,
with the SCP80 keys and TAR of OTA over SMS
- decodes the responses and closes the link with RST when done.
Change-Id: I4b97971beb9c0dda73217ece5f1e51fd8ace4540
---
A contrib/cattp_admin_server.py
A tests/unittests/test_cattp_admin_server.py
2 files changed, 364 insertions(+), 0 deletions(-)
Approvals:
dexter: Looks good to me, approved
Jenkins Builder: Verified
diff --git a/contrib/cattp_admin_server.py b/contrib/cattp_admin_server.py
new file mode 100755
index 0000000..ee57ea1
--- /dev/null
+++ b/contrib/cattp_admin_server.py
@@ -0,0 +1,234 @@
+#!/usr/bin/env python3
+"""CAT_TP Remote Administration Server for RAM/RFM over BIP, ETSI TS 102 225 section 6"""
+
+# (C) 2026 by sysmocom - s.f.m.c. GmbH
+# All Rights Reserved
+#
+# Author: Eric Wild <ewild(a)sysmocom.de>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# The UDP end of "OTA over BIP" for cards that do CAT_TP instead of SCP81:
+# - contrib/cattp_trigger.py builds the PUSH that makes the card OPEN CHANNEL to us and SYN
+# - once the link is OPEN this server sends the queued C-APDUs as TS 102 225 secured
+# command packets, one per SDU, the same SCP80 keys and TAR as OTA over SMS
+# - the card answers each with a secured response packet, decoded and logged here
+# - after the last one the link is closed with RST, the card then closes the BIP channel
+#
+# Same command line spirit as scp81_admin_server.py, same OTA options as smpp-ota-tool.py.
+
+import argparse
+import logging
+from pathlib import Path
+from typing import Dict, List, Optional, Callable
+
+from osmocom.utils import h2b, b2h
+
+from pySim.cattp import CatTpServer, CatTpConnection, RST_NORMAL
+from pySim.ota import (OtaKeyset, OtaDialectCatTp, OtaCheckError, argparse_add_ota_args,
+ ota_keyset_from_args, ota_spi_from_args)
+
+logger = logging.getLogger(Path(__file__).stem)
+
+
+def format_decoded_response(res, dec) -> str:
+ bits = ['status=%s cntr=%s' % (res.response_status, b2h(res.cntr))]
+ if dec is None:
+ return bits[0]
+ if 'commands' in dec: # expanded
+ bits.append('%u command(s) executed' % dec.number_of_commands)
+ for i, c in enumerate(dec.commands):
+ bits.append(' R-APDU[%u]: SW=%s data=%s' % (i, c.status_word, c.response_data or '-'))
+ if dec.get('truncated'):
+ bits.append(' TRUNCATED: SW 62F1, the card stopped executing the script')
+ if dec.bad_format is not None:
+ bits.append(' bad-format: %s' % dec.bad_format)
+ else: # compact
+ bits.append('%u command(s) executed, last SW=%s data=%s' % (
+ dec.number_of_commands, dec.last_status_word, dec.last_response_data or '-'))
+ return '\n'.join(bits)
+
+
+class CatTpAdminSession:
+ """One card: hand it the queued commands in order, one secured packet per SDU."""
+
+ def __init__(self, otak: OtaKeyset, spi: dict, tar: bytes, commands: List,
+ remote_format: str = 'compact',
+ on_response: Optional[Callable[[object, object], None]] = None):
+ self.otak = otak
+ self.spi = spi
+ self.tar = tar
+ self.pending = list(commands)
+ self.remote_format = remote_format
+ self.on_response = on_response
+ self.dialect = OtaDialectCatTp()
+ self.responses = []
+
+ def start(self, conn: CatTpConnection):
+ logger.info('link OPEN with identification %s, %u command(s) queued',
+ b2h(conn.peer_identification), len(self.pending))
+ self._send_next(conn)
+
+ def _send_next(self, conn: CatTpConnection):
+ if not self.pending:
+ logger.info('no more commands, closing the link')
+ conn.close(RST_NORMAL)
+ return
+ cmd = self.pending.pop(0)
+ secured = self.dialect.encode_cmd(self.otak, self.tar, self.spi, cmd,
+ remote_format=self.remote_format)
+ if self.spi['counter'] != 'no_counter':
+ self.otak.cntr += 1
+ logger.info('-> command packet (%uB): %s', len(secured), b2h(secured))
+ conn.send_sdu(secured)
+
+ def _decode(self, sdu: bytes):
+ try:
+ return self.dialect.decode_resp(self.otak, self.spi, sdu, remote_format=self.remote_format)
+ except (ValueError, OtaCheckError):
+ # a card that could not process our packet answers in the clear
+ spi = dict(self.spi, por_shall_be_ciphered=False, por_rc_cc_ds='no_rc_cc_ds')
+ return self.dialect.decode_resp(self.otak, spi, sdu, remote_format=self.remote_format)
+
+ def on_sdu(self, conn: CatTpConnection, sdu: bytes):
+ logger.debug('<- response packet (%uB): %s', len(sdu), b2h(sdu))
+ try:
+ res, dec = self._decode(sdu)
+ except Exception as e:
+ logger.error('undecodable response packet %s: %s', b2h(sdu), e)
+ conn.close(RST_NORMAL)
+ return
+ self.responses.append((res, dec))
+ logger.info('card response:\n%s', format_decoded_response(res, dec))
+ if self.on_response:
+ self.on_response(res, dec)
+ self._send_next(conn)
+
+
+class CatTpAdminServer:
+ """CatTpServer that runs a CatTpAdminSession for every card that connects."""
+
+ def __init__(self, host: str, port: int, otak: OtaKeyset, spi: dict, tar: bytes,
+ commands: List, remote_format: str = 'compact',
+ on_response: Optional[Callable[[object, object], None]] = None,
+ on_session_end: Optional[Callable[[CatTpAdminSession], None]] = None,
+ **conn_kwargs):
+ self.otak = otak
+ self.spi = spi
+ self.tar = tar
+ self.commands = commands
+ self.remote_format = remote_format
+ self.on_response = on_response
+ self.on_session_end = on_session_end
+ self.sessions: Dict[int, CatTpAdminSession] = {}
+ self.server = CatTpServer(host, port, on_sdu=self._on_sdu, on_state=self._on_state, **conn_kwargs)
+
+ def bind(self) -> int:
+ return self.server.bind()
+
+ @property
+ def port(self) -> int:
+ return self.server.port
+
+ def serve_forever(self):
+ self.server.serve_forever()
+
+ def shutdown(self):
+ self.server.shutdown()
+
+ def _on_state(self, conn: CatTpConnection, state: str):
+ if state == CatTpConnection.OPEN:
+ session = CatTpAdminSession(self.otak, self.spi, self.tar, self.commands,
+ self.remote_format, self.on_response)
+ self.sessions[id(conn)] = session
+ session.start(conn)
+ elif state in (CatTpConnection.CLOSE_WAIT, CatTpConnection.CLOSED):
+ session = self.sessions.pop(id(conn), None)
+ if session is not None:
+ logger.info('session ended: %u response(s) collected', len(session.responses))
+ if self.on_session_end:
+ self.on_session_end(session)
+
+ def _on_sdu(self, conn: CatTpConnection, sdu: bytes):
+ session = self.sessions.get(id(conn))
+ if session is None:
+ logger.warning('SDU without a session, ignoring')
+ return
+ session.on_sdu(conn, sdu)
+
+
+def build_commands(apdus: List[bytes], batch: bool, remote_format: str) -> List:
+ """Group the APDUs per secured packet: one concatenated string for compact, a list for expanded."""
+ if not apdus:
+ return []
+ groups = [apdus] if batch else [[a] for a in apdus]
+ if remote_format == 'expanded':
+ return groups
+ return [b''.join(g) for g in groups]
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__,
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter)
+ parser.add_argument('--host', default='0.0.0.0', help='IP to bind to')
+ parser.add_argument('--port', type=int, default=6001,
+ help='UDP port, also the CAT_TP port the PUSH points the card to')
+ argparse_add_ota_args(parser)
+ parser.add_argument('--format', choices=['compact', 'expanded'], default='compact',
+ help='Remote Application data format, TS 102 226 5.1 / 5.2')
+ parser.add_argument('--apdu', '-a', action='append', default=[], metavar='HEX',
+ help='C-APDU to send, may be given several times, executed in order')
+ parser.add_argument('--apdu-file', help='File with one C-APDU (hex) per line, # comments allowed')
+ parser.add_argument('--batch', action='store_true', help='All C-APDUs in one command packet')
+ parser.add_argument('--max-pdu', type=int, default=1024,
+ help='largest PDU we accept, the card must not exceed it')
+ parser.add_argument('--max-sdu', type=int, default=65535, help='largest SDU we accept')
+ parser.add_argument('--window', type=int, default=4, help='receive window in PDUs')
+ parser.add_argument('--rto', type=float, default=5.0,
+ help='retransmission timeout in seconds, a card behind BIP is slow')
+ parser.add_argument('--retries', type=int, default=3, help='retransmissions before RST')
+ parser.add_argument('-v', '--verbose', action='store_true', help='enable debug output')
+ args = parser.parse_args()
+
+ logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO,
+ format='%(asctime)s %(levelname)s %(message)s',
+ datefmt='%Y-%m-%d %H:%M:%S')
+
+ apdus = [h2b(a) for a in args.apdu]
+ if args.apdu_file:
+ for line in Path(args.apdu_file).read_text().splitlines():
+ line = line.split('#', 1)[0].strip()
+ if line:
+ apdus.append(h2b(line))
+ commands = build_commands(apdus, args.batch, args.format)
+ if not commands:
+ logger.warning('no C-APDUs: the link will be closed right after the handshake')
+
+ otak = ota_keyset_from_args(args)
+ spi = ota_spi_from_args(args)
+
+ server = CatTpAdminServer(args.host, args.port, otak, spi, h2b(args.tar), commands,
+ remote_format=args.format, max_pdu=args.max_pdu, max_sdu=args.max_sdu,
+ window=args.window, rto=args.rto, max_retries=args.retries)
+ server.bind()
+ logger.info('trigger: contrib/cattp_trigger.py --ip <our ip> --port %u', server.port)
+ try:
+ server.serve_forever()
+ except KeyboardInterrupt:
+ logger.info('shutting down')
+ server.shutdown()
+
+
+if __name__ == '__main__':
+ main()
diff --git a/tests/unittests/test_cattp_admin_server.py b/tests/unittests/test_cattp_admin_server.py
new file mode 100644
index 0000000..4e137e4
--- /dev/null
+++ b/tests/unittests/test_cattp_admin_server.py
@@ -0,0 +1,130 @@
+#!/usr/bin/env python3
+
+# (C) 2026 by sysmocom - s.f.m.c. GmbH
+# All Rights Reserved
+#
+# Author: Eric Wild <ewild(a)sysmocom.de>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+import os.path
+import importlib.util
+import socket
+import threading
+import time
+import unittest
+
+from osmocom.utils import h2b, b2h
+
+from pySim.cattp import CatTpConnection, RST_NORMAL
+from pySim.ota import OtaKeyset, OtaDialectCatTp, encode_expanded_cmd, ExpandedRemoteResp
+
+_PATH = os.path.join(os.path.dirname(__file__), '..', '..', 'contrib', 'cattp_admin_server.py')
+_spec = importlib.util.spec_from_file_location('cattp_admin_server', _PATH)
+cattp_admin_server = importlib.util.module_from_spec(_spec)
+_spec.loader.exec_module(cattp_admin_server)
+
+KEYSET = OtaKeyset(algo_crypt='aes_cbc', kic_idx=2, algo_auth='aes_cmac', kid_idx=2,
+ kic=h2b('200102030405060708090a0b0c0d0e0f'),
+ kid=h2b('201102030405060708090a0b0c0d0e0f'))
+SPI = {'counter': 'no_counter', 'ciphering': True, 'rc_cc_ds': 'cc', 'por_in_submit': False,
+ 'por_shall_be_ciphered': True, 'por_rc_cc_ds': 'cc', 'por': 'por_required'}
+TAR = h2b('b00010')
+
+
+class _FakeCard:
+ """CAT_TP client that unpacks each command packet and answers 9000 for every C-APDU"""
+
+ def __init__(self, port, remote_format):
+ self.dialect = OtaDialectCatTp()
+ self.remote_format = remote_format
+ self.received = []
+ self.conn = CatTpConnection(4711, on_sdu=self._on_sdu, max_pdu=256)
+ self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ self.sock.settimeout(1.0)
+ self.sock.connect(('127.0.0.1', port))
+
+ def _on_sdu(self, conn, sdu):
+ tar, spi, apdu = self.dialect.decode_cmd(KEYSET, sdu)
+ self.received.append(apdu)
+ if self.remote_format == 'expanded':
+ n = apdu.count(b'\x22') # good enough for the C-APDUs used here
+ data = ExpandedRemoteResp.build(dict(body=dict(
+ num_executed=dict(number_of_commands=n),
+ responses=[dict(r_apdu=dict(response_data='', status_word='9000'))] * n)))
+ else:
+ data = h2b('01' '9000')
+ conn.send_sdu(self.dialect.encode_resp(KEYSET, spi, tar, data=data))
+
+ def run(self, deadline=5.0):
+ self.conn.connect(self.sock.getpeername()[1], identification=h2b('8949'))
+ end = time.monotonic() + deadline
+ while time.monotonic() < end and self.conn.state != 'CLOSE-WAIT':
+ for raw in self.conn.pop_tx():
+ self.sock.send(raw)
+ try:
+ self.conn.on_pdu(self.sock.recv(65535))
+ except socket.timeout:
+ self.conn.on_timer()
+ for raw in self.conn.pop_tx():
+ self.sock.send(raw)
+ self.sock.close()
+
+
+class CatTpAdminServerTest(unittest.TestCase):
+ APDUS = [h2b('00a40004023f00'), h2b('00b0000010')]
+
+ def _run(self, batch, remote_format):
+ commands = cattp_admin_server.build_commands(self.APDUS, batch, remote_format)
+ ended = []
+ server = cattp_admin_server.CatTpAdminServer('127.0.0.1', 0, KEYSET, SPI, TAR, commands,
+ remote_format=remote_format,
+ on_session_end=ended.append, rto=0.5)
+ server.bind()
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ self.addCleanup(server.shutdown)
+ card = _FakeCard(server.port, remote_format)
+ card.run()
+ deadline = time.monotonic() + 2.0
+ while not ended and time.monotonic() < deadline:
+ time.sleep(0.01)
+ self.assertEqual(card.conn.close_reason, RST_NORMAL)
+ self.assertEqual(len(ended), 1)
+ return card, ended[0]
+
+ def test_compact_one_packet_per_apdu(self):
+ card, session = self._run(batch=False, remote_format='compact')
+ self.assertEqual(card.received, self.APDUS)
+ self.assertEqual([d.last_status_word for _, d in session.responses], ['9000', '9000'])
+
+ def test_compact_batch(self):
+ card, session = self._run(batch=True, remote_format='compact')
+ self.assertEqual(card.received, [b''.join(self.APDUS)])
+ self.assertEqual(len(session.responses), 1)
+
+ def test_expanded_batch(self):
+ card, session = self._run(batch=True, remote_format='expanded')
+ self.assertEqual(card.received, [encode_expanded_cmd(self.APDUS)])
+ res, dec = session.responses[0]
+ self.assertEqual(res.response_status, 'por_ok')
+ self.assertEqual(dec.number_of_commands, 2)
+
+ def test_build_commands(self):
+ self.assertEqual(cattp_admin_server.build_commands([], True, 'compact'), [])
+ self.assertEqual(cattp_admin_server.build_commands(self.APDUS, False, 'expanded'),
+ [[self.APDUS[0]], [self.APDUS[1]]])
+
+
+if __name__ == "__main__":
+ unittest.main()
--
To view, visit https://gerrit.osmocom.org/c/pysim/+/43721?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email
Gerrit-MessageType: merged
Gerrit-Project: pysim
Gerrit-Branch: master
Gerrit-Change-Id: I4b97971beb9c0dda73217ece5f1e51fd8ace4540
Gerrit-Change-Number: 43721
Gerrit-PatchSet: 3
Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de>
Gerrit-Reviewer: Jenkins Builder
Gerrit-Reviewer: dexter <pmaier(a)sysmocom.de>
Gerrit-Reviewer: laforge <laforge(a)osmocom.org>
1
0
[M] Change in pysim[master]: ota: argparse helpers for the SCP80 key set and SPI
by laforge 25 Nov '26
by laforge 25 Nov '26
25 Nov '26
laforge has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/43720?usp=email )
(
1 is the latest approved patch-set.
No files were changed between the latest approved patch-set and the submitted one.
)Change subject: ota: argparse helpers for the SCP80 key set and SPI
......................................................................
ota: argparse helpers for the SCP80 key set and SPI
shared among scp80/cat-tp and scp81
Change-Id: I599a07f7e4e100ddce91ee7eae70bab3cf9c07c1
---
M pySim/ota.py
1 file changed, 49 insertions(+), 1 deletion(-)
Approvals:
laforge: Looks good to me, but someone else must approve
Jenkins Builder: Verified
dexter: Looks good to me, approved
diff --git a/pySim/ota.py b/pySim/ota.py
index e25d384..5b82b3e 100644
--- a/pySim/ota.py
+++ b/pySim/ota.py
@@ -17,6 +17,7 @@
import zlib
import abc
+import logging
import struct
from typing import Optional, Tuple, List, Union
from construct import ConstructError, Enum, Int8ub, Int16ub, Struct, BitsInteger, BitStruct
@@ -24,9 +25,12 @@
from construct import Const, Prefixed, Select, Construct, SizeofError, stream_read, stream_write
from osmocom.construct import *
from osmocom.tlv import bertlv_encode_len, bertlv_parse_len
-from osmocom.utils import b2h
+from osmocom.utils import b2h, h2b
from pySim.sms import UserDataHeader
+from pySim.utils import is_hexstr
+
+logger = logging.getLogger(__name__)
from pySim.cat import BearerDescription, BufferSize, UiccTransportLevel, OtherAddress, ChannelData
# ETS TS 102 225 gives the general command structure and the dialects for CAT_TP, TCP/IP and HTTPS
@@ -582,6 +586,50 @@
+def argparse_add_ota_args(parser, sms: bool = False):
+ """SCP80 key set and SPI options of the OTA tools, --por-in-submit only with sms"""
+ g = parser.add_argument_group('OTA security, TS 102 225')
+ g.add_argument('--algo-crypt', choices=[c.enum_name for c in OtaAlgoCrypt.__subclasses__()],
+ default='triple_des_cbc2', help='OTA crypt algorithm')
+ g.add_argument('--algo-auth', choices=[c.enum_name for c in OtaAlgoAuth.__subclasses__()],
+ default='triple_des_cbc2', help='OTA auth algorithm')
+ g.add_argument('--kic', required=True, type=is_hexstr, help='OTA key (KIC)')
+ g.add_argument('--kic-idx', default=1, type=int, help='OTA key index (KIC)')
+ g.add_argument('--kid', required=True, type=is_hexstr, help='OTA key (KID)')
+ g.add_argument('--kid-idx', default=1, type=int, help='OTA key index (KID)')
+ g.add_argument('--cntr', default=0, type=int, help='replay protection counter')
+ g.add_argument('--tar', required=True, type=is_hexstr, help='Toolkit Application Reference')
+ g.add_argument('--cntr-req', choices=CNTR_REQ.decmapping.values(), default='no_counter',
+ help='Counter requirement')
+ g.add_argument('--no-ciphering', action='store_true', default=False, help='Disable ciphering')
+ g.add_argument('--rc-cc-ds', choices=RC_CC_DS.decmapping.values(), default='cc',
+ help='message check (rc=redundency check, cc=crypt. checksum, ds=digital signature)')
+ if sms:
+ g.add_argument('--por-in-submit', action='store_true', default=False,
+ help='require PoR to be sent via SMS-SUBMIT')
+ g.add_argument('--por-no-ciphering', action='store_true', default=False, help='Disable ciphering (PoR)')
+ g.add_argument('--por-rc-cc-ds', choices=RC_CC_DS.decmapping.values(), default='cc',
+ help='PoR check (rc=redundency check, cc=crypt. checksum, ds=digital signature)')
+ g.add_argument('--por-req', choices=POR_REQ.decmapping.values(), default='por_required',
+ help='Proof of Receipt requirements')
+
+def ota_keyset_from_args(args) -> 'OtaKeyset':
+ if args.kic_idx != args.kid_idx:
+ logger.warning('KIC index (%s) and KID index (%s) differ, the card should reject that',
+ args.kic_idx, args.kid_idx)
+ return OtaKeyset(algo_crypt=args.algo_crypt, kic_idx=args.kic_idx, kic=h2b(args.kic),
+ algo_auth=args.algo_auth, kid_idx=args.kid_idx, kid=h2b(args.kid), cntr=args.cntr)
+
+def ota_spi_from_args(args) -> dict:
+ return {'counter': args.cntr_req,
+ 'ciphering': not args.no_ciphering,
+ 'rc_cc_ds': args.rc_cc_ds,
+ 'por_in_submit': getattr(args, 'por_in_submit', False),
+ 'por_shall_be_ciphered': not args.por_no_ciphering,
+ 'por_rc_cc_ds': args.por_rc_cc_ds,
+ 'por': args.por_req}
+
+
class OtaDialectSms(OtaDialect):
"""OTA dialect for SMS based transport, as described in 3GPP TS 31.115."""
SmsResponsePacket = Struct('rpl'/Int16ub,
--
To view, visit https://gerrit.osmocom.org/c/pysim/+/43720?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email
Gerrit-MessageType: merged
Gerrit-Project: pysim
Gerrit-Branch: master
Gerrit-Change-Id: I599a07f7e4e100ddce91ee7eae70bab3cf9c07c1
Gerrit-Change-Number: 43720
Gerrit-PatchSet: 3
Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de>
Gerrit-Reviewer: Jenkins Builder
Gerrit-Reviewer: dexter <pmaier(a)sysmocom.de>
Gerrit-Reviewer: laforge <laforge(a)osmocom.org>
1
0
[XL] Change in pysim[master]: cattp: ETSI TS 102 127 transport for OTA over BIP UDP
by laforge 25 Nov '26
by laforge 25 Nov '26
25 Nov '26
laforge has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/43719?usp=email )
Change subject: cattp: ETSI TS 102 127 transport for OTA over BIP UDP
......................................................................
cattp: ETSI TS 102 127 transport for OTA over BIP UDP
While this might look like "hand rolled TCP over UDP done wrong" is is
actually amazing 80s technology, based on RFC 908/1151 RDP v2.
It supports:
- three way handshake
- cumulative and extended ACKs
- retransmission with retry limit
- windows
- SEG(ments) reassembly
- NUL and RST
Has a server side the card connects to + client side for the tests, just
like scp81.
Change-Id: I6f31493c1f0fb48fb3fd5382d8af2c905d365e54
---
A pySim/cattp.py
A tests/unittests/test_cattp.py
2 files changed, 1,089 insertions(+), 0 deletions(-)
Approvals:
dexter: Looks good to me, but someone else must approve
laforge: Looks good to me, approved
Jenkins Builder: Verified
diff --git a/pySim/cattp.py b/pySim/cattp.py
new file mode 100644
index 0000000..e152b17
--- /dev/null
+++ b/pySim/cattp.py
@@ -0,0 +1,659 @@
+# -*- coding: utf-8 -*-
+"""CAT_TP, the Card Application Toolkit Transport Protocol of ETSI TS 102 127"""
+
+# (C) 2026 by sysmocom - s.f.m.c. GmbH
+# All Rights Reserved
+#
+# Author: Eric Wild <ewild(a)sysmocom.de>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# A reliable, sequenced datagram transport that a card runs over a BIP UDP channel to carry
+# TS 102 225 secured packets, one per SDU. It is the Reliable Data Protocol of RFC 908/1151
+# (handshake, sequence numbers, cumulative and extended ACKs, retransmission, per datagram
+# rather than per byte stream) plus a SEG bit to spread one SDU over several PDUs.
+# Server side, the card connects here after a TS 102 226 PUSH. The client side exists for
+# the tests.
+#
+# CatTpConnection is the protocol state machine without a socket, driven by tests or by the
+# UDP socket of CatTpServer: received PDUs go to on_pdu(), the clock to on_timer(), pop_tx()
+# returns the PDUs to send.
+
+import collections
+import logging
+import random
+import socket
+import threading
+import time
+from typing import Callable, Dict, List, Optional, Tuple
+
+from construct import Struct, BitStruct, BitsInteger, Flag, Int8ub, Int16ub, Padding, Bytes, GreedyBytes
+from construct import GreedyRange, Prefixed, Rebuild, Terminated, ConstructError, this, len_
+from osmocom.utils import b2h
+
+logger = logging.getLogger(__name__)
+
+# TS 102 127 5.6.1 figure 39, flags in the first octet
+FLAG_SYN = 0x80 # establish the connection, synchronise sequence numbers
+FLAG_ACK = 0x40 # acknowledgement number and window are significant
+FLAG_EACK = 0x20 # extended acknowledgement of PDUs received out of sequence
+FLAG_RST = 0x10 # reset (close) the connection, as in TCP
+FLAG_NUL = 0x08 # keep alive, carries no data
+FLAG_SEG = 0x04 # more segments of this SDU follow
+VERSION = 0
+
+# TS 102 127 5.6.2: header length without a variable header area
+HDR_LEN = 0x12
+
+# TS 102 127 5.6.5: sequence numbers are 16 bit and wrap around
+SEQ_MOD = 0x10000
+
+# TS 102 127 5.10.1.4, reason codes of the RST PDU
+RST_NORMAL = 0x00
+RST_ILLEGAL_PARAMS = 0x01
+RST_TEMP_UNABLE = 0x02
+RST_PORT_NOT_AVAILABLE = 0x03
+RST_UNEXPECTED_PDU = 0x04
+RST_MAX_RETRIES = 0x05
+RST_VERSION = 0x06
+RST_REASONS = {RST_NORMAL: 'normal ending', RST_ILLEGAL_PARAMS: 'illegal parameters',
+ RST_TEMP_UNABLE: 'temporarily unable', RST_PORT_NOT_AVAILABLE: 'port not available',
+ RST_UNEXPECTED_PDU: 'unexpected PDU', RST_MAX_RETRIES: 'maximum retries exceeded',
+ RST_VERSION: 'version not supported'}
+
+# TS 102 127 5.6 figure 38. The variable header area depends on the PDU type and has its own
+# constructs below.
+PduStruct = Struct('first'/BitStruct('syn'/Flag, 'ack'/Flag, 'eack'/Flag, 'rst'/Flag, 'nul'/Flag,
+ 'seg'/Flag, 'version'/BitsInteger(2)),
+ Padding(2), # RFU
+ 'hdr_len'/Rebuild(Int8ub, len_(this.var) + HDR_LEN),
+ 'src_port'/Int16ub,
+ 'dst_port'/Int16ub,
+ 'data_len'/Rebuild(Int16ub, len_(this.data)),
+ 'seq'/Int16ub,
+ 'ack'/Int16ub,
+ 'window'/Int16ub,
+ 'checksum'/Int16ub,
+ 'var'/Bytes(this.hdr_len - HDR_LEN),
+ 'data'/Bytes(this.data_len),
+ Terminated)
+
+# TS 102 127 5.7 SYN PDU. The identification is a LV (5.5), figure 40 draws it like a fixed field.
+SynVar = Struct('max_pdu'/Int16ub, 'max_sdu'/Int16ub,
+ 'identification'/Prefixed(Int8ub, GreedyBytes), Terminated)
+# TS 102 127 5.9.1.4 EACK PDU: sequence numbers of the PDUs received out of sequence
+EackVar = Struct('eack'/GreedyRange(Int16ub), Terminated)
+# TS 102 127 5.10.1.4 RST PDU
+RstVar = Struct('rst_reason'/Int8ub, Terminated)
+NoVar = Struct(Terminated)
+
+FLAG_BITS = {'syn': FLAG_SYN, 'ack': FLAG_ACK, 'eack': FLAG_EACK, 'rst': FLAG_RST,
+ 'nul': FLAG_NUL, 'seg': FLAG_SEG}
+
+
+def var_struct(flags: int) -> Struct:
+ """construct of the variable header area of a PDU with these flags, TS 102 127 5.6.9"""
+ if flags & FLAG_SYN:
+ return SynVar
+ if flags & FLAG_RST:
+ return RstVar
+ if flags & FLAG_EACK:
+ return EackVar
+ return NoVar
+
+
+def checksum(data: bytes) -> int:
+ """TS 102 127 5.3.2.2: the RFC 793 checksum without the pseudo header"""
+ if len(data) & 1:
+ data += b'\x00'
+ total = sum(int.from_bytes(data[i:i + 2], 'big') for i in range(0, len(data), 2))
+ while total >> 16:
+ total = (total & 0xffff) + (total >> 16)
+ return (~total) & 0xffff
+
+
+def _seq_add(seq: int, n: int = 1) -> int:
+ return (seq + n) % SEQ_MOD
+
+
+def _seq_diff(a: int, b: int) -> int:
+ """a - b on the sequence number circle"""
+ return (a - b) % SEQ_MOD
+
+
+def _seq_ge(a: int, b: int) -> bool:
+ """a is at or after b, less than half the circle ahead"""
+ return _seq_diff(a, b) < SEQ_MOD // 2
+
+
+class CatTpError(Exception):
+ pass
+
+
+class Pdu:
+ """One CAT_TP PDU, TS 102 127 5.6 to 5.11"""
+ __slots__ = ('flags', 'version', 'src_port', 'dst_port', 'seq', 'ack', 'window', 'data',
+ 'eack', 'max_pdu', 'max_sdu', 'identification', 'rst_reason')
+
+ def __init__(self, flags: int, src_port: int, dst_port: int, seq: int = 0, ack: int = 0,
+ window: int = 0, data: bytes = b'', eack: Tuple[int, ...] = (),
+ max_pdu: int = 0, max_sdu: int = 0, identification: bytes = b'',
+ rst_reason: int = RST_NORMAL, version: int = VERSION):
+ self.flags = flags
+ self.version = version
+ self.src_port = src_port
+ self.dst_port = dst_port
+ self.seq = seq
+ self.ack = ack
+ self.window = window
+ self.data = bytes(data)
+ self.eack = tuple(eack)
+ self.max_pdu = max_pdu
+ self.max_sdu = max_sdu
+ self.identification = bytes(identification)
+ self.rst_reason = rst_reason
+ self.check()
+
+ syn = property(lambda self: bool(self.flags & FLAG_SYN))
+ has_ack = property(lambda self: bool(self.flags & FLAG_ACK))
+ has_eack = property(lambda self: bool(self.flags & FLAG_EACK))
+ rst = property(lambda self: bool(self.flags & FLAG_RST))
+ nul = property(lambda self: bool(self.flags & FLAG_NUL))
+ seg = property(lambda self: bool(self.flags & FLAG_SEG))
+
+ @property
+ def needs_ack(self) -> bool:
+ """TS 102 127 5.3.2.1: SYN, NUL and data PDUs consume a sequence number and get acknowledged"""
+ return self.syn or self.nul or len(self.data) > 0
+
+ def check(self):
+ """Raise CatTpError for what TS 102 127 5.6.1 and 5.10.0 rule out."""
+ if self.data and (self.syn or self.rst or self.nul):
+ raise CatTpError('SYN, RST and NUL PDUs carry no data')
+ if self.seg and not self.data:
+ raise CatTpError('SEG is only allowed with data')
+ if self.syn and self.rst:
+ raise CatTpError('SYN and RST are separate PDUs')
+ if self.rst and self.has_eack:
+ raise CatTpError('RST cannot be combined with EACK')
+ if self.nul and not self.has_ack:
+ raise CatTpError('NUL comes with ACK')
+
+ def to_bytes(self) -> bytes:
+ self.check()
+ fields = {name: getattr(self, name) for name in self.__slots__}
+ fields['first'] = dict({name: bool(self.flags & bit) for name, bit in FLAG_BITS.items()},
+ version=self.version)
+ try:
+ fields['var'] = var_struct(self.flags).build(fields)
+ # TS 102 127 5.3.2.2: computed while the checksum field itself is zero
+ raw = PduStruct.build(dict(fields, checksum=0))
+ return PduStruct.build(dict(fields, checksum=checksum(raw)))
+ except ConstructError as e:
+ raise CatTpError('cannot encode %r: %s' % (self, e)) from e
+
+ @classmethod
+ def from_bytes(cls, raw: bytes) -> 'Pdu':
+ try:
+ hdr = PduStruct.parse(raw)
+ flags = sum(bit for name, bit in FLAG_BITS.items() if hdr.first[name])
+ var = var_struct(flags).parse(hdr.var)
+ except ConstructError as e:
+ raise CatTpError('malformed PDU: %s' % e) from e
+ # RFC 1071: summed up including a correct checksum field the result is zero
+ if checksum(raw) != 0:
+ raise CatTpError('checksum mismatch')
+ return cls(flags, hdr.src_port, hdr.dst_port, seq=hdr.seq, ack=hdr.ack, window=hdr.window,
+ data=hdr.data, version=hdr.first.version,
+ **{name: value for name, value in var.items() if not name.startswith('_')})
+
+ def __repr__(self):
+ names = [name.upper() for name, bit in FLAG_BITS.items() if self.flags & bit]
+ s = '<%s %u->%u seq=%u ack=%u win=%u len=%u' % ('/'.join(names) or 'DATA', self.src_port,
+ self.dst_port, self.seq, self.ack, self.window,
+ len(self.data))
+ if self.syn:
+ s += ' max_pdu=%u max_sdu=%u id=%s' % (self.max_pdu, self.max_sdu, b2h(self.identification))
+ if self.eack:
+ s += ' eack=%s' % (self.eack,)
+ if self.rst:
+ s += ' reason=%s' % RST_REASONS.get(self.rst_reason, self.rst_reason)
+ return s + '>'
+
+
+class CatTpConnection:
+ """One connection, TS 102 127 5.3.1.4 connection record and 5.4 event processing.
+
+ Upper layer hooks:
+ - on_sdu(conn, sdu) for every reassembled SDU
+ - on_state(conn, state) on every state change, 'OPEN' is when to start sending
+ Calling send_sdu() from inside on_sdu() puts the ACK into the data PDU instead of a separate one.
+ clock is only there for tests to fake time.
+ """
+ CLOSED, LISTEN, SYN_SENT, SYN_RCVD, OPEN, CLOSE_WAIT = ('CLOSED', 'LISTEN', 'SYN-SENT',
+ 'SYN-RCVD', 'OPEN', 'CLOSE-WAIT')
+
+ def __init__(self, local_port: int, *, max_pdu: int = 1024, max_sdu: int = 65535,
+ window: int = 4, rto: float = 3.0, max_retries: int = 3, close_wait: float = 2.0,
+ on_sdu: Optional[Callable[['CatTpConnection', bytes], None]] = None,
+ on_state: Optional[Callable[['CatTpConnection', str], None]] = None,
+ clock: Callable[[], float] = time.monotonic):
+ self.clock = clock
+ self.local_port = local_port
+ self.remote_port = 0
+ self.state = self.CLOSED
+ self.rto = rto
+ self.max_retries = max_retries
+ self.close_wait = close_wait
+ self.on_sdu = on_sdu
+ self.on_state = on_state
+ self.peer_identification = b''
+ self.close_reason: Optional[int] = None
+ # sending activity, 5.3.1.4.2
+ self.snd_ini = 0
+ self.snd_nxt = 0
+ self.snd_una = 0
+ self.snd_pdu_max = 0
+ self.snd_sdu_max = 0
+ self.snd_right = 0 # last sequence number the peer window allows
+ # receiving activity, 5.3.1.4.3
+ self.rcv_ini = 0
+ self.rcv_cur = 0
+ self.rcv_out_of_seq: Dict[int, Pdu] = {}
+ self.rcv_pdu_max = max_pdu
+ self.rcv_sdu_max = max_sdu
+ self.rcv_win = window
+ self._rx_sdu = bytearray()
+ # [pdu, sent_at, retries] awaiting acknowledgement, in sequence order
+ self._rtx: List[list] = []
+ self._tx_wait: collections.deque = collections.deque() # data PDUs beyond the window
+ self._tx: List[bytes] = []
+ self._close_deadline: Optional[float] = None
+ self._ack_pending = False
+ self._data_sent = False
+
+ def __repr__(self):
+ return '<CatTpConnection %s %u<->%u snd_nxt=%u snd_una=%u rcv_cur=%u>' % (
+ self.state, self.local_port, self.remote_port, self.snd_nxt, self.snd_una, self.rcv_cur)
+
+ def listen(self):
+ """TS 102 127 5.4.1.1 passive open"""
+ self._set_state(self.LISTEN)
+
+ def connect(self, remote_port: int, identification: bytes = b''):
+ """TS 102 127 5.4.1.1 active open, what the card does after the PUSH"""
+ self.remote_port = remote_port
+ self._init_send()
+ self._queue(Pdu(FLAG_SYN, self.local_port, remote_port, seq=self.snd_ini, window=self.rcv_win,
+ max_pdu=self.rcv_pdu_max, max_sdu=self.rcv_sdu_max,
+ identification=identification))
+ self._set_state(self.SYN_SENT)
+
+ def send_sdu(self, sdu: bytes):
+ """TS 102 127 5.4.1.4: segment into data PDUs (5.2.3), send what the window allows"""
+ if self.state != self.OPEN:
+ raise CatTpError('cannot send in state %s' % self.state)
+ if len(sdu) > self.snd_sdu_max:
+ raise CatTpError('SDU of %u octets exceeds peer max SDU size %u' % (len(sdu), self.snd_sdu_max))
+ chunk = self.snd_pdu_max - HDR_LEN
+ if chunk < 1:
+ raise CatTpError('peer max PDU size %u leaves no room for data' % self.snd_pdu_max)
+ segments = [sdu[i:i + chunk] for i in range(0, len(sdu), chunk)] or [b'']
+ for i, seg in enumerate(segments):
+ flags = FLAG_ACK | (FLAG_SEG if i < len(segments) - 1 else 0)
+ self._tx_wait.append(Pdu(flags, self.local_port, self.remote_port, seq=self.snd_nxt, data=seg))
+ self.snd_nxt = _seq_add(self.snd_nxt)
+ self._flush_window()
+
+ def send_nul(self):
+ """TS 102 127 5.3.1.6 probe for a half open connection"""
+ if self.state != self.OPEN:
+ raise CatTpError('cannot send in state %s' % self.state)
+ self._tx_wait.append(Pdu(FLAG_NUL | FLAG_ACK, self.local_port, self.remote_port, seq=self.snd_nxt))
+ self.snd_nxt = _seq_add(self.snd_nxt)
+ self._flush_window()
+
+ def close(self, reason: int = RST_NORMAL):
+ """TS 102 127 5.4.1.2: RST, then CLOSE-WAIT until the timer expires"""
+ if self.state in (self.CLOSED, self.CLOSE_WAIT):
+ return
+ if self.state == self.LISTEN:
+ self._set_state(self.CLOSED)
+ return
+ flags = FLAG_RST | (FLAG_ACK if self.state in (self.OPEN, self.SYN_RCVD) else 0)
+ self._queue(Pdu(flags, self.local_port, self.remote_port, seq=self.snd_nxt, ack=self.rcv_cur,
+ window=self.rcv_win, rst_reason=reason))
+ self._enter_close_wait(reason)
+
+ def pop_tx(self) -> List[bytes]:
+ """serialised PDUs to hand to the socket, in order"""
+ out, self._tx = self._tx, []
+ return out
+
+ def on_timer(self) -> Optional[float]:
+ """TS 102 127 5.4.3: retransmit what is overdue, returns the next deadline or None"""
+ now = self.clock()
+ if self.state == self.CLOSE_WAIT:
+ if now >= self._close_deadline:
+ self._rtx.clear()
+ self._set_state(self.CLOSED)
+ return None
+ return self._close_deadline
+ for entry in self._rtx:
+ pdu, sent_at, retries = entry
+ if now - sent_at < self.rto:
+ continue
+ if retries >= self.max_retries:
+ logger.warning('%r: %r not acknowledged after %u retries', self, pdu, retries)
+ self.close(RST_MAX_RETRIES)
+ return self._close_deadline
+ logger.debug('%r: retransmit %r', self, pdu)
+ entry[1], entry[2] = now, retries + 1
+ self._emit(pdu)
+ deadlines = [sent_at + self.rto for _, sent_at, _ in self._rtx]
+ return min(deadlines) if deadlines else None
+
+ def on_pdu(self, raw: bytes):
+ """TS 102 127 5.4.2 PDU arrival"""
+ try:
+ pdu = Pdu.from_bytes(raw)
+ except CatTpError as e:
+ logger.warning('%r: discarding PDU: %s', self, e)
+ return
+ if len(raw) > self.rcv_pdu_max:
+ logger.warning('%r: discarding %u octet PDU above max PDU size', self, len(raw))
+ return
+ logger.debug('%r: rx %r', self, pdu)
+ self._ack_pending = False
+ self._data_sent = False
+ handler = {self.CLOSED: self._rx_closed, self.LISTEN: self._rx_listen,
+ self.SYN_SENT: self._rx_syn_sent, self.SYN_RCVD: self._rx_syn_rcvd,
+ self.OPEN: self._rx_open, self.CLOSE_WAIT: self._rx_close_wait}[self.state]
+ handler(pdu)
+ # the upper layer may have closed the connection from its callback, TS 102 127 5.3.1.5:
+ # nothing is sent in CLOSE-WAIT
+ if self._ack_pending and not self._data_sent and self.state == self.OPEN:
+ self._queue(self._ack_pdu())
+
+ def _rx_closed(self, pdu: Pdu):
+ # TS 102 127 5.4.2.1: tell the peer nobody is home, RST is never answered
+ if not pdu.rst:
+ self._queue(Pdu(FLAG_RST | FLAG_ACK, self.local_port, pdu.src_port, ack=pdu.seq,
+ rst_reason=RST_PORT_NOT_AVAILABLE))
+
+ def _rx_close_wait(self, pdu: Pdu):
+ pass # TS 102 127 5.3.1.5: discarded
+
+ def _rx_listen(self, pdu: Pdu):
+ # TS 102 127 5.4.2.3: only a SYN gets us anywhere
+ if pdu.rst:
+ return
+ if not pdu.syn or pdu.has_ack:
+ self._queue(Pdu(FLAG_RST | FLAG_ACK, self.local_port, pdu.src_port, ack=pdu.seq,
+ rst_reason=RST_UNEXPECTED_PDU))
+ return
+ if pdu.max_pdu < HDR_LEN + 1:
+ self._queue(Pdu(FLAG_RST | FLAG_ACK, self.local_port, pdu.src_port, ack=pdu.seq,
+ rst_reason=RST_ILLEGAL_PARAMS))
+ return
+ self.remote_port = pdu.src_port
+ self.rcv_ini = self.rcv_cur = pdu.seq
+ self.peer_identification = pdu.identification
+ self._init_send(pdu)
+ # TS 102 127 5.3.1.7: answer with our version, TS 102 226 9.2.2: empty identification
+ self._queue(Pdu(FLAG_SYN | FLAG_ACK, self.local_port, self.remote_port, seq=self.snd_ini,
+ ack=self.rcv_cur, window=self.rcv_win, max_pdu=self.rcv_pdu_max,
+ max_sdu=self.rcv_sdu_max))
+ self._set_state(self.SYN_RCVD)
+
+ def _rx_syn_sent(self, pdu: Pdu):
+ # TS 102 127 5.4.2.4
+ if pdu.rst:
+ self._enter_close_wait(pdu.rst_reason)
+ return
+ if not (pdu.syn and pdu.has_ack) or pdu.ack != self.snd_ini:
+ self._queue(Pdu(FLAG_RST, self.local_port, self.remote_port, seq=self.snd_nxt,
+ rst_reason=RST_UNEXPECTED_PDU))
+ self._enter_close_wait(RST_UNEXPECTED_PDU)
+ return
+ if pdu.version != VERSION:
+ self.close(RST_VERSION)
+ return
+ self.rcv_ini = self.rcv_cur = pdu.seq
+ self.peer_identification = pdu.identification
+ self.snd_pdu_max, self.snd_sdu_max = pdu.max_pdu, pdu.max_sdu
+ self._process_ack(pdu)
+ self._set_state(self.OPEN)
+ self._ack_pending = True
+
+ def _rx_syn_rcvd(self, pdu: Pdu):
+ # TS 102 127 5.4.2.5
+ if pdu.rst:
+ self._rtx.clear()
+ self._set_state(self.LISTEN)
+ return
+ if pdu.syn:
+ if pdu.seq == self.rcv_ini and not pdu.has_ack:
+ self._retransmit_syn_ack() # our SYN/ACK got lost
+ return
+ self._queue(Pdu(FLAG_RST | FLAG_ACK, self.local_port, self.remote_port, ack=pdu.seq,
+ rst_reason=RST_UNEXPECTED_PDU))
+ self._enter_close_wait(RST_UNEXPECTED_PDU)
+ return
+ if not pdu.has_ack or pdu.ack != self.snd_ini:
+ return
+ self._set_state(self.OPEN)
+ self._rx_open(pdu)
+
+ def _rx_open(self, pdu: Pdu):
+ # TS 102 127 5.4.2.2, figures 25 to 28
+ if pdu.rst:
+ logger.info('%r: peer reset, %s', self, RST_REASONS.get(pdu.rst_reason, pdu.rst_reason))
+ self._enter_close_wait(pdu.rst_reason)
+ return
+ if pdu.syn:
+ self._queue(Pdu(FLAG_RST | FLAG_ACK, self.local_port, self.remote_port, ack=pdu.seq,
+ rst_reason=RST_UNEXPECTED_PDU))
+ self._enter_close_wait(RST_UNEXPECTED_PDU)
+ return
+ if pdu.has_ack:
+ self._process_ack(pdu)
+ if not pdu.needs_ack:
+ return
+ self._ack_pending = True
+ d = _seq_diff(pdu.seq, self.rcv_cur)
+ if d == 0 or d > self.rcv_win:
+ logger.debug('%r: seq %u outside window, duplicate ACK', self, pdu.seq)
+ return
+ if d != 1:
+ self.rcv_out_of_seq[pdu.seq] = pdu # TS 102 127 5.3.3: in the window but out of sequence
+ return
+ self._accept(pdu)
+ while _seq_add(self.rcv_cur) in self.rcv_out_of_seq:
+ self._accept(self.rcv_out_of_seq.pop(_seq_add(self.rcv_cur)))
+
+ def _accept(self, pdu: Pdu):
+ self.rcv_cur = pdu.seq
+ if pdu.nul:
+ return
+ self._rx_sdu += pdu.data
+ if len(self._rx_sdu) > self.rcv_sdu_max:
+ logger.warning('%r: SDU exceeds %u octets', self, self.rcv_sdu_max)
+ self.close(RST_ILLEGAL_PARAMS)
+ return
+ if pdu.seg:
+ return
+ sdu, self._rx_sdu = bytes(self._rx_sdu), bytearray()
+ if self.on_sdu:
+ self.on_sdu(self, sdu)
+
+ def _set_state(self, state: str):
+ logger.info('%r: %s -> %s', self, self.state, state)
+ self.state = state
+ if self.on_state:
+ self.on_state(self, state)
+
+ def _enter_close_wait(self, reason: int):
+ self.close_reason = reason
+ self._rtx.clear()
+ self._tx_wait.clear()
+ self._close_deadline = self.clock() + self.close_wait
+ self._set_state(self.CLOSE_WAIT)
+
+ def _init_send(self, syn: Optional[Pdu] = None):
+ self.snd_ini = random.randrange(SEQ_MOD)
+ self.snd_nxt = _seq_add(self.snd_ini)
+ self.snd_una = self.snd_ini
+ self.snd_right = self.snd_ini
+ if syn is not None:
+ self.snd_pdu_max, self.snd_sdu_max = syn.max_pdu, syn.max_sdu
+
+ def _retransmit_syn_ack(self):
+ for entry in self._rtx:
+ if entry[0].syn:
+ entry[1] = self.clock()
+ self._emit(entry[0])
+
+ def _ack_pdu(self) -> Pdu:
+ """(E)ACK without data, seq is SND_NXT and is not consumed, TS 102 127 figure 45"""
+ pdu = Pdu(FLAG_ACK, self.local_port, self.remote_port, seq=self.snd_nxt)
+ if self.rcv_out_of_seq:
+ pdu.flags |= FLAG_EACK
+ pdu.eack = tuple(sorted(self.rcv_out_of_seq))
+ return pdu
+
+ def _process_ack(self, pdu: Pdu):
+ # only acknowledgements within SND_UNA-1 .. SND_NXT-1 are meaningful
+ base = _seq_add(self.snd_una, -1)
+ if _seq_diff(pdu.ack, base) > _seq_diff(_seq_add(self.snd_nxt, -1), base):
+ logger.debug('%r: ignoring ack %u outside %u..%u', self, pdu.ack, base, self.snd_nxt - 1)
+ return
+ acked = set(pdu.eack)
+ self._rtx = [e for e in self._rtx
+ if not _seq_ge(pdu.ack, e[0].seq) and e[0].seq not in acked]
+ if _seq_ge(pdu.ack, self.snd_una):
+ self.snd_una = _seq_add(pdu.ack)
+ # TS 102 127 5.3.3: the right window border never moves left
+ right = _seq_add(pdu.ack, pdu.window)
+ if _seq_ge(right, self.snd_right):
+ self.snd_right = right
+ self._flush_window()
+
+ def _flush_window(self):
+ while self._tx_wait and _seq_ge(self.snd_right, self._tx_wait[0].seq):
+ pdu = self._tx_wait.popleft()
+ self._queue(pdu)
+ self._data_sent = True
+
+ def _queue(self, pdu: Pdu):
+ """TS 102 127 5.3.2.4 serialization/retransmission"""
+ if pdu.needs_ack:
+ self._rtx.append([pdu, self.clock(), 0])
+ self._emit(pdu)
+
+ def _emit(self, pdu: Pdu):
+ if pdu.has_ack and not (pdu.syn or pdu.rst):
+ pdu.ack, pdu.window = self.rcv_cur, self.rcv_win
+ logger.debug('%r: tx %r', self, pdu)
+ self._tx.append(pdu.to_bytes())
+
+
+class CatTpServer:
+ """One UDP socket, a listening CatTpConnection per peer address, single threaded.
+
+ Args:
+ host: local address to bind to
+ port: local UDP port, also the CAT_TP port of the connections. 0 picks a free one,
+ bind() returns it.
+ on_sdu: callback(conn: CatTpConnection, sdu: bytes) for every SDU received
+ on_state: callback(conn: CatTpConnection, state: str) on every state change of a
+ connection, 'OPEN' is when to start sending with conn.send_sdu()
+ conn_kwargs: passed on to every CatTpConnection (max_pdu, max_sdu, window, rto,
+ max_retries, close_wait)
+
+ The callbacks run on the server thread, sending from them puts the response and the ACK
+ into the same PDU. Other threads use send_sdu() of the server.
+ """
+ POLL = 0.05 # seconds between timer runs while no datagram arrives
+ MAX_DATAGRAM = 65535 # largest UDP datagram
+
+ def __init__(self, host: str, port: int, on_sdu=None, on_state=None, **conn_kwargs):
+ self.host = host
+ self.port = port
+ self.on_sdu = on_sdu
+ self.on_state = on_state
+ self.conn_kwargs = conn_kwargs
+ self.conns: Dict[tuple, CatTpConnection] = {}
+ self._sock: Optional[socket.socket] = None
+ self._stop = threading.Event()
+ self._lock = threading.RLock()
+
+ def bind(self) -> int:
+ """Bind the socket, returns the port. Optional, serve_forever() does it if needed."""
+ self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ self._sock.bind((self.host, self.port))
+ self._sock.settimeout(self.POLL)
+ self.port = self._sock.getsockname()[1]
+ return self.port
+
+ def serve_forever(self):
+ """Receive datagrams and run the connection timers until shutdown() is called."""
+ if self._sock is None:
+ self.bind()
+ logger.info('CAT_TP server listening on %s:%u/udp', self.host, self.port)
+ while not self._stop.is_set():
+ try:
+ raw, addr = self._sock.recvfrom(self.MAX_DATAGRAM)
+ except socket.timeout:
+ raw, addr = None, None
+ except OSError:
+ break
+ with self._lock:
+ if raw is not None:
+ conn = self.conns.get(addr)
+ if conn is None:
+ conn = CatTpConnection(self.port, on_sdu=self.on_sdu, on_state=self.on_state,
+ **self.conn_kwargs)
+ conn.listen()
+ self.conns[addr] = conn
+ conn.on_pdu(raw)
+ self._flush(conn, addr)
+ self._tick()
+
+ def _tick(self):
+ for addr, conn in list(self.conns.items()):
+ conn.on_timer()
+ self._flush(conn, addr)
+ if conn.state == CatTpConnection.CLOSED:
+ del self.conns[addr]
+
+ def _flush(self, conn: CatTpConnection, addr):
+ for raw in conn.pop_tx():
+ try:
+ self._sock.sendto(raw, addr)
+ except OSError as e:
+ logger.warning('sendto %s failed: %s', addr, e)
+
+ def send_sdu(self, conn: CatTpConnection, sdu: bytes):
+ """thread safe entry for callers outside the server thread"""
+ with self._lock:
+ conn.send_sdu(sdu)
+ addr = next(a for a, c in self.conns.items() if c is conn)
+ self._flush(conn, addr)
+
+ def shutdown(self):
+ """Stop serve_forever() and close the socket."""
+ self._stop.set()
+ if self._sock is not None:
+ self._sock.close()
diff --git a/tests/unittests/test_cattp.py b/tests/unittests/test_cattp.py
new file mode 100644
index 0000000..5e3711e
--- /dev/null
+++ b/tests/unittests/test_cattp.py
@@ -0,0 +1,430 @@
+#!/usr/bin/env python3
+
+# (C) 2026 by sysmocom - s.f.m.c. GmbH
+# All Rights Reserved
+#
+# Author: Eric Wild <ewild(a)sysmocom.de>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+import socket
+import threading
+import time
+import unittest
+from unittest import mock
+
+from osmocom.utils import b2h, h2b
+
+from pySim.cattp import (Pdu, PduStruct, FLAG_BITS, CatTpConnection, CatTpServer, CatTpError, checksum,
+ FLAG_SYN, FLAG_ACK, FLAG_EACK, FLAG_RST, FLAG_NUL, FLAG_SEG,
+ RST_NORMAL, RST_MAX_RETRIES, RST_VERSION, RST_UNEXPECTED_PDU)
+
+
+class PduCodecTest(unittest.TestCase):
+
+ def test_checksum_rfc1071_example(self):
+ self.assertEqual(checksum(h2b('0001f203f4f5f6f7')), 0x220d)
+
+ def test_syn_golden(self):
+ # TS 102 127 5.7: flags|ver 80, RFU, header length 17 hex (12 + max PDU + max SDU + id length), ports,
+ # data length 0, seq 100, ack, window, checksum, max PDU 1024, max SDU 1024, id length 0
+ pdu = Pdu(FLAG_SYN, 1024, 6001, seq=100, window=4, max_pdu=1024, max_sdu=1024)
+ raw = pdu.to_bytes()
+ self.assertEqual(b2h(raw), '80000017' '0400' '1771' '0000' '0064' '0000' '0004' '5c0f'
+ '0400' '0400' '00')
+ back = Pdu.from_bytes(raw)
+ self.assertTrue(back.syn)
+ self.assertEqual((back.src_port, back.dst_port, back.seq, back.window), (1024, 6001, 100, 4))
+ self.assertEqual((back.max_pdu, back.max_sdu, back.identification), (1024, 1024, b''))
+
+ def test_flag_bits(self):
+ # TS 102 127 figure 39: b8 SYN, b7 ACK, b6 EACK, b5 RST, b4 NUL, b3 SEG, b2..b1 version
+ self.assertEqual((FLAG_SYN, FLAG_ACK, FLAG_EACK, FLAG_RST, FLAG_NUL, FLAG_SEG),
+ (0x80, 0x40, 0x20, 0x10, 0x08, 0x04))
+ self.assertEqual(Pdu(FLAG_ACK | FLAG_SEG, 1, 2, data=b'x').to_bytes()[0], 0x44)
+ self.assertEqual(Pdu(FLAG_SYN, 1, 2, version=1).to_bytes()[0], 0x81)
+
+ def test_roundtrip_all_types(self):
+ cases = [
+ Pdu(FLAG_SYN, 5000, 6001, seq=7, window=2, max_pdu=512, max_sdu=2048,
+ identification=h2b('89490200001234567890')),
+ Pdu(FLAG_SYN | FLAG_ACK, 6001, 5000, seq=9, ack=7, window=4, max_pdu=1024, max_sdu=65535),
+ Pdu(FLAG_ACK, 6001, 5000, seq=10, ack=8, window=4),
+ Pdu(FLAG_ACK, 6001, 5000, seq=10, ack=8, window=4, data=bytes(range(200))),
+ Pdu(FLAG_ACK | FLAG_SEG, 6001, 5000, seq=10, ack=8, window=4, data=b'seg'),
+ Pdu(FLAG_ACK | FLAG_EACK, 6001, 5000, seq=10, ack=8, window=4, eack=(10, 12)),
+ Pdu(FLAG_ACK | FLAG_EACK, 6001, 5000, seq=10, ack=8, window=4, eack=(11,), data=b'd'),
+ Pdu(FLAG_RST, 6001, 5000, seq=10, rst_reason=RST_VERSION),
+ Pdu(FLAG_RST | FLAG_ACK, 6001, 5000, seq=10, ack=8, rst_reason=RST_NORMAL),
+ Pdu(FLAG_NUL | FLAG_ACK, 6001, 5000, seq=10, ack=8, window=4),
+ Pdu(FLAG_NUL | FLAG_ACK | FLAG_EACK, 6001, 5000, seq=10, ack=8, window=4, eack=(10,)),
+ ]
+ for pdu in cases:
+ with self.subTest(pdu=repr(pdu)):
+ raw = pdu.to_bytes()
+ self.assertEqual(raw[3] + len(pdu.data), len(raw)) # header length
+ back = Pdu.from_bytes(raw)
+ for f in Pdu.__slots__:
+ self.assertEqual(getattr(back, f), getattr(pdu, f), f)
+ self.assertEqual(back.to_bytes(), raw)
+
+ def test_rejects_damaged(self):
+ raw = bytearray(Pdu(FLAG_ACK, 1, 2, seq=1, data=b'abc').to_bytes())
+ raw[-1] ^= 0x01
+ with self.assertRaises(CatTpError):
+ Pdu.from_bytes(bytes(raw))
+ with self.assertRaises(CatTpError):
+ Pdu.from_bytes(bytes(raw[:10]))
+ raw = bytearray(Pdu(FLAG_ACK, 1, 2, seq=1, data=b'abc').to_bytes())
+ raw[9] += 1 # data length lies
+ with self.assertRaises(CatTpError):
+ Pdu.from_bytes(bytes(raw))
+
+
+ def test_rejects_malformed_variable_header(self):
+ def with_var(flags, var):
+ # hand built, the encoder refuses to produce these
+ fields = dict(first=dict({n: bool(flags & b) for n, b in FLAG_BITS.items()}, version=0),
+ src_port=1, dst_port=2, seq=1, ack=0, window=1, var=var, data=b'')
+ raw = PduStruct.build(dict(fields, checksum=0))
+ return PduStruct.build(dict(fields, checksum=checksum(raw)))
+ Pdu.from_bytes(with_var(FLAG_SYN, h2b('0400' '0400' '02' 'aabb')))
+ for flags, var in ((FLAG_SYN, h2b('0400' '0400')), # no identification length
+ (FLAG_SYN, h2b('0400' '0400' '02' 'aa')), # identification cut short
+ (FLAG_SYN, h2b('0400' '0400' '00' 'aa')), # trailing octet
+ (FLAG_ACK | FLAG_EACK, h2b('000a' '0b')), # half a sequence number
+ (FLAG_RST, b''), # no reason code
+ (FLAG_RST, h2b('0000')),
+ (FLAG_ACK, h2b('00'))): # nothing expected here
+ with self.subTest(flags=flags, var=var.hex()):
+ with self.assertRaises(CatTpError):
+ Pdu.from_bytes(with_var(flags, var))
+
+ def test_rejects_illegal_combinations(self):
+ # TS 102 127 5.6.1, 5.10.0
+ for flags, data in ((FLAG_SYN, b'x'), (FLAG_RST, b'x'), (FLAG_NUL | FLAG_ACK, b'x'),
+ (FLAG_ACK | FLAG_SEG, b''), (FLAG_SYN | FLAG_RST, b''),
+ (FLAG_RST | FLAG_ACK | FLAG_EACK, b''), (FLAG_NUL, b'')):
+ with self.subTest(flags=flags, data=data):
+ with self.assertRaises(CatTpError):
+ Pdu(flags, 1, 2, data=data)
+ pdu = Pdu(FLAG_ACK, 1, 2)
+ pdu.flags |= FLAG_SEG # changed after construction
+ with self.assertRaises(CatTpError):
+ pdu.to_bytes()
+ with self.assertRaises(CatTpError):
+ Pdu(FLAG_ACK, 1, 0x10000).to_bytes() # port does not fit
+
+
+class _Clock:
+ def __init__(self):
+ self.t = 1000.0
+
+ def __call__(self):
+ return self.t
+
+
+class _Pair:
+ """client and server connection joined back to back, PDUs move via pump()"""
+
+ def __init__(self, test, client_kwargs=None, server_kwargs=None, isn=(100, 200)):
+ self.test = test
+ self.clock = _Clock()
+ self.log = [] # (direction, Pdu)
+ self.client_sdus = []
+ self.server_sdus = []
+ self.states = []
+ self.client = CatTpConnection(1024, clock=self.clock, on_sdu=lambda c, s: self.client_sdus.append(s),
+ on_state=lambda c, s: self.states.append(('client', s)),
+ **(client_kwargs or {}))
+ self.server = CatTpConnection(6001, clock=self.clock, on_sdu=lambda c, s: self.server_sdus.append(s),
+ on_state=lambda c, s: self.states.append(('server', s)),
+ **(server_kwargs or {}))
+ self.isn = list(isn)
+ self.drop = []
+
+ def _isn(self, *_):
+ return self.isn.pop(0)
+
+ def open(self, identification=b''):
+ with mock.patch('pySim.cattp.random.randrange', side_effect=self._isn):
+ self.server.listen()
+ self.client.connect(6001, identification)
+ self.pump()
+
+ def pump(self):
+ """move PDUs both ways until nothing is left"""
+ moved = True
+ while moved:
+ moved = False
+ for src, dst, direction in ((self.client, self.server, '>'), (self.server, self.client, '<')):
+ for raw in src.pop_tx():
+ moved = True
+ pdu = Pdu.from_bytes(raw)
+ if any(d(direction, pdu) for d in self.drop):
+ self.log.append((direction + 'x', pdu))
+ continue
+ self.log.append((direction, pdu))
+ dst.on_pdu(raw)
+
+ def trace(self):
+ return [(d, p.flags, p.seq, p.ack, len(p.data)) for d, p in self.log]
+
+ def advance(self, seconds):
+ self.clock.t += seconds
+ self.client.on_timer()
+ self.server.on_timer()
+ self.pump()
+
+
+class ConnectionTest(unittest.TestCase):
+
+ def test_handshake_annex_a1(self):
+ p = _Pair(self)
+ p.open(identification=h2b('8949'))
+ self.assertEqual(p.trace(), [
+ ('>', FLAG_SYN, 100, 0, 0), # 2. <SEQ=100><SYN>
+ ('<', FLAG_SYN | FLAG_ACK, 200, 100, 0), # 3. <SEQ=200><ACK=100><SYN,ACK>
+ ('>', FLAG_ACK, 101, 200, 0), # 4. <SEQ=101><ACK=200>
+ ])
+ self.assertEqual((p.client.state, p.server.state), ('OPEN', 'OPEN'))
+ self.assertEqual(p.server.peer_identification, h2b('8949'))
+ self.assertEqual(p.client.peer_identification, b'') # TS 102 226 9.2.2
+ self.assertEqual((p.client.snd_nxt, p.client.rcv_cur), (101, 200))
+ self.assertEqual((p.server.snd_nxt, p.server.rcv_cur), (201, 100))
+ self.assertEqual(p.server._rtx, []) # SYN/ACK acknowledged
+ # 5./6. data goes out with the next sequence number and gets an ACK without data
+ p.client.send_sdu(b'hello')
+ p.pump()
+ self.assertEqual(p.trace()[3:], [('>', FLAG_ACK, 101, 200, 5), ('<', FLAG_ACK, 201, 101, 0)])
+ self.assertEqual(p.server_sdus, [b'hello'])
+ self.assertEqual(p.client._rtx, [])
+
+ def test_request_response_piggyback(self):
+ p = _Pair(self)
+ p.open()
+ # the server answers from within on_sdu, so the ACK rides on the response data
+ p.server.on_sdu = lambda c, s: c.send_sdu(b'resp:' + s)
+ p.client.send_sdu(b'cmd')
+ p.pump()
+ self.assertEqual(p.trace()[3:], [('>', FLAG_ACK, 101, 200, 3),
+ ('<', FLAG_ACK, 201, 101, 8),
+ ('>', FLAG_ACK, 102, 201, 0)])
+ self.assertEqual(p.client_sdus, [b'resp:cmd'])
+
+ def test_lost_pdu_annex_a2(self):
+ p = _Pair(self, client_kwargs={'rto': 1.0})
+ p.open()
+ p.drop.append(lambda d, pdu: d == '>' and pdu.seq == 102 and len(pdu.data))
+ for sdu in (b'a', b'b', b'c', b'd'):
+ p.client.send_sdu(sdu)
+ p.pump()
+ del p.drop[:]
+ # 102 was lost: 101 acked, 103 and 104 acknowledged out of sequence with EACK
+ self.assertEqual([t for t in p.trace()[3:] if t[0] == '<'], [
+ ('<', FLAG_ACK, 201, 101, 0),
+ ('<', FLAG_ACK | FLAG_EACK, 201, 101, 0),
+ ('<', FLAG_ACK | FLAG_EACK, 201, 101, 0)])
+ self.assertEqual(p.log[-1][1].eack, (103, 104))
+ self.assertEqual(p.server_sdus, [b'a'])
+ self.assertEqual([e[0].seq for e in p.client._rtx], [102])
+ # retransmission timer fires, only 102 goes again and the cumulative ACK jumps to 104
+ p.advance(1.5)
+ self.assertEqual(p.trace()[-2:], [('>', FLAG_ACK, 102, 200, 1), ('<', FLAG_ACK, 201, 104, 0)])
+ self.assertEqual(p.server_sdus, [b'a', b'b', b'c', b'd'])
+ self.assertEqual(p.client._rtx, [])
+
+ def test_segmentation(self):
+ p = _Pair(self, server_kwargs={'max_pdu': 18 + 8}) # SYN is 18 + 5 already
+ p.open()
+ p.client.send_sdu(b'0123456789abcdefgh')
+ p.pump()
+ self.assertEqual([t for t in p.trace()[3:] if t[0] == '>'], [
+ ('>', FLAG_ACK | FLAG_SEG, 101, 200, 8),
+ ('>', FLAG_ACK | FLAG_SEG, 102, 200, 8),
+ ('>', FLAG_ACK, 103, 200, 2)])
+ self.assertEqual(p.server_sdus, [b'0123456789abcdefgh'])
+ with self.assertRaises(CatTpError):
+ p.client.send_sdu(bytes(65536))
+
+ def test_window_limits_outstanding_pdus(self):
+ p = _Pair(self, server_kwargs={'window': 1})
+ p.open()
+ p.drop.append(lambda d, pdu: d == '<') # server goes quiet
+ p.client.send_sdu(b'a')
+ p.client.send_sdu(b'b')
+ p.pump()
+ self.assertEqual([t for t in p.trace() if t[0] == '>' and t[4]], [('>', FLAG_ACK, 101, 200, 1)])
+ del p.drop[:]
+ p.client.send_nul() # nothing more until the window opens
+ p.advance(3.5) # 101 retransmitted, acked, then 102 flows
+ self.assertEqual(p.server_sdus, [b'a', b'b'])
+
+ def test_retransmit_gives_up_with_rst(self):
+ p = _Pair(self, server_kwargs={'rto': 1.0, 'max_retries': 2, 'close_wait': 5.0})
+ p.open()
+ p.drop.append(lambda d, pdu: d == '>') # client vanished
+ p.server.send_sdu(b'x')
+ p.pump()
+ p.advance(1.0)
+ p.advance(1.0)
+ self.assertEqual(p.server.state, 'OPEN')
+ p.advance(1.0)
+ self.assertEqual(p.server.state, 'CLOSE-WAIT')
+ self.assertEqual(p.server.close_reason, RST_MAX_RETRIES)
+ rst = p.log[-1][1]
+ self.assertTrue(rst.rst and rst.has_ack)
+ self.assertEqual(rst.rst_reason, RST_MAX_RETRIES)
+ self.assertEqual([t for t in p.trace() if t[4] == 1],
+ [('<', FLAG_ACK, 201, 100, 1)] * 3) # original + 2 retries
+ p.advance(4.0)
+ self.assertEqual(p.server.state, 'CLOSE-WAIT')
+ p.advance(1.5)
+ self.assertEqual(p.server.state, 'CLOSED')
+
+ def test_close_with_rst(self):
+ p = _Pair(self, server_kwargs={'close_wait': 1.0})
+ p.open()
+ p.client.close()
+ p.pump()
+ self.assertEqual(p.trace()[-1], ('>', FLAG_RST | FLAG_ACK, 101, 200, 0))
+ self.assertEqual((p.client.state, p.server.state), ('CLOSE-WAIT', 'CLOSE-WAIT'))
+ self.assertEqual(p.server.close_reason, RST_NORMAL)
+ with self.assertRaises(CatTpError):
+ p.server.send_sdu(b'late')
+ p.advance(1.5)
+ self.assertEqual(p.server.state, 'CLOSED')
+
+ def test_close_from_on_sdu_sends_only_the_rst(self):
+ p = _Pair(self)
+ p.open()
+ p.server.on_sdu = lambda c, s: c.close()
+ p.client.send_sdu(b'last')
+ p.pump()
+ self.assertEqual([t for t in p.trace()[3:] if t[0] == '<'],
+ [('<', FLAG_RST | FLAG_ACK, 201, 101, 0)]) # no ACK after the RST
+ self.assertEqual(p.server.state, 'CLOSE-WAIT')
+
+ def test_duplicate_data_is_acked_not_delivered(self):
+ p = _Pair(self)
+ p.open()
+ p.client.send_sdu(b'once')
+ p.pump()
+ dup = Pdu(FLAG_ACK, 1024, 6001, seq=101, ack=200, window=4, data=b'once').to_bytes()
+ p.server.on_pdu(dup)
+ self.assertEqual(len(p.server.pop_tx()), 1)
+ self.assertEqual(p.server_sdus, [b'once'])
+
+ def test_nul_keepalive(self):
+ p = _Pair(self)
+ p.open()
+ p.server.send_nul()
+ p.pump()
+ self.assertEqual(p.trace()[3:], [('<', FLAG_NUL | FLAG_ACK, 201, 100, 0),
+ ('>', FLAG_ACK, 101, 201, 0)])
+ self.assertEqual(p.server.snd_nxt, 202)
+
+ def test_syn_ack_with_other_version_is_refused(self):
+ p = _Pair(self)
+ with mock.patch('pySim.cattp.random.randrange', return_value=100):
+ p.client.connect(6001)
+ p.client.pop_tx()
+ p.client.on_pdu(Pdu(FLAG_SYN | FLAG_ACK, 6001, 1024, seq=200, ack=100, window=4, max_pdu=1024,
+ max_sdu=1024, version=1).to_bytes())
+ rst = Pdu.from_bytes(p.client.pop_tx()[0])
+ self.assertTrue(rst.rst)
+ self.assertEqual(rst.rst_reason, RST_VERSION)
+ self.assertEqual(p.client.state, 'CLOSE-WAIT')
+
+ def test_syn_in_open_is_unexpected(self):
+ p = _Pair(self)
+ p.open()
+ p.server.on_pdu(Pdu(FLAG_SYN, 1024, 6001, seq=300, max_pdu=1024, max_sdu=1024).to_bytes())
+ rst = Pdu.from_bytes(p.server.pop_tx()[0])
+ self.assertEqual((rst.rst, rst.rst_reason, rst.ack), (True, RST_UNEXPECTED_PDU, 300))
+
+ def test_lost_syn_ack_is_retransmitted(self):
+ p = _Pair(self, server_kwargs={'rto': 1.0})
+ p.drop.append(lambda d, pdu: d == '<')
+ p.open()
+ del p.drop[:]
+ self.assertEqual((p.client.state, p.server.state), ('SYN-SENT', 'SYN-RCVD'))
+ p.advance(1.0)
+ self.assertEqual((p.client.state, p.server.state), ('OPEN', 'OPEN'))
+
+
+class UdpServerTest(unittest.TestCase):
+ """CatTpServer on a real loopback socket, driven by a hand pumped client connection"""
+
+ def setUp(self):
+ self.got = []
+ self.opened = threading.Event()
+ self.server = CatTpServer('127.0.0.1', 0, on_sdu=self._on_sdu, on_state=self._on_state, rto=0.5)
+ self.server.bind()
+ threading.Thread(target=self.server.serve_forever, daemon=True).start()
+ self.addCleanup(self.server.shutdown)
+ self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ self.sock.settimeout(2.0)
+ self.sock.connect(('127.0.0.1', self.server.port))
+ self.addCleanup(self.sock.close)
+ self.client = CatTpConnection(2048)
+
+ def _on_state(self, conn, state):
+ if state == 'OPEN':
+ conn.send_sdu(b'GET STATUS') # the admin server talks first
+ self.opened.set()
+
+ def _on_sdu(self, conn, sdu):
+ self.got.append(sdu)
+ if sdu == b'bye':
+ conn.close()
+ else:
+ conn.send_sdu(b'next after ' + sdu)
+
+ def _exchange(self, deadline=3.0):
+ """push out what the client has, feed back what the socket returns"""
+ end = time.monotonic() + deadline
+ while time.monotonic() < end:
+ for raw in self.client.pop_tx():
+ self.sock.send(raw)
+ try:
+ raw = self.sock.recv(65535)
+ except socket.timeout:
+ return
+ self.client.on_pdu(raw)
+ if not self.client._tx and not self.client._rtx:
+ return
+
+ def test_session(self):
+ rx = []
+ self.client.on_sdu = lambda c, s: rx.append(s)
+ self.client.connect(self.server.port, identification=h2b('8949020000000001'))
+ self._exchange()
+ self.assertTrue(self.opened.wait(2.0))
+ self.assertEqual(self.client.state, 'OPEN')
+ self.assertEqual(rx, [b'GET STATUS'])
+ conn = next(iter(self.server.conns.values()))
+ self.assertEqual(conn.peer_identification, h2b('8949020000000001'))
+ self.client.send_sdu(b'9000')
+ self._exchange()
+ self.assertEqual(rx, [b'GET STATUS', b'next after 9000'])
+ self.client.send_sdu(b'bye')
+ self._exchange()
+ self.assertEqual(self.got, [b'9000', b'bye'])
+ self.assertEqual(self.client.state, 'CLOSE-WAIT')
+ self.assertEqual(self.client.close_reason, RST_NORMAL)
+
+
+if __name__ == "__main__":
+ unittest.main()
--
To view, visit https://gerrit.osmocom.org/c/pysim/+/43719?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email
Gerrit-MessageType: merged
Gerrit-Project: pysim
Gerrit-Branch: master
Gerrit-Change-Id: I6f31493c1f0fb48fb3fd5382d8af2c905d365e54
Gerrit-Change-Number: 43719
Gerrit-PatchSet: 3
Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de>
Gerrit-Reviewer: Jenkins Builder
Gerrit-Reviewer: dexter <pmaier(a)sysmocom.de>
Gerrit-Reviewer: laforge <laforge(a)osmocom.org>
1
0
[M] Change in pysim[master]: smpp-ota-tool: use the shared OTA argparse helpers
by laforge 25 Nov '26
by laforge 25 Nov '26
25 Nov '26
laforge has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/43722?usp=email )
(
1 is the latest approved patch-set.
No files were changed between the latest approved patch-set and the submitted one.
)Change subject: smpp-ota-tool: use the shared OTA argparse helpers
......................................................................
smpp-ota-tool: use the shared OTA argparse helpers
Change-Id: Icea287f1a216fae4274f00a723a47ec19376a6ce
---
M contrib/smpp-ota-tool.py
1 file changed, 4 insertions(+), 49 deletions(-)
Approvals:
dexter: Looks good to me, approved
Jenkins Builder: Verified
diff --git a/contrib/smpp-ota-tool.py b/contrib/smpp-ota-tool.py
index 885cf94..5f7af40 100755
--- a/contrib/smpp-ota-tool.py
+++ b/contrib/smpp-ota-tool.py
@@ -24,7 +24,7 @@
import smpplib.client
import smpplib.consts
import time
-from pySim.ota import OtaKeyset, OtaDialectSms, OtaAlgoCrypt, OtaAlgoAuth, OtaCheckError, CNTR_REQ, RC_CC_DS, POR_REQ
+from pySim.ota import OtaKeyset, OtaDialectSms, OtaCheckError, argparse_add_ota_args, ota_keyset_from_args, ota_spi_from_args
from pySim.sms import ConcatenatedSmsReassembler
from pySim.utils import b2h, h2b, is_hexstr
from pathlib import Path
@@ -38,36 +38,7 @@
option_parser.add_argument("--system-id", help="System ID to use to bind to the SMPP server", default="test")
option_parser.add_argument("--password", help="Password to use to bind to the SMPP server", default="test")
option_parser.add_argument("--verbose", help="Enable verbose logging", action='store_true', default=False)
-algo_crypt_choices = []
-algo_crypt_classes = OtaAlgoCrypt.__subclasses__()
-for cls in algo_crypt_classes:
- algo_crypt_choices.append(cls.enum_name)
-option_parser.add_argument("--algo-crypt", choices=algo_crypt_choices, default='triple_des_cbc2',
- help="OTA crypt algorithm")
-algo_auth_choices = []
-algo_auth_classes = OtaAlgoAuth.__subclasses__()
-for cls in algo_auth_classes:
- algo_auth_choices.append(cls.enum_name)
-option_parser.add_argument("--algo-auth", choices=algo_auth_choices, default='triple_des_cbc2',
- help="OTA auth algorithm")
-option_parser.add_argument('--kic', required=True, type=is_hexstr, help='OTA key (KIC)')
-option_parser.add_argument('--kic-idx', default=1, type=int, help='OTA key index (KIC)')
-option_parser.add_argument('--kid', required=True, type=is_hexstr, help='OTA key (KID)')
-option_parser.add_argument('--kid-idx', default=1, type=int, help='OTA key index (KID)')
-option_parser.add_argument('--cntr', default=0, type=int, help='replay protection counter')
-option_parser.add_argument('--tar', required=True, type=is_hexstr, help='Toolkit Application Reference')
-option_parser.add_argument("--cntr-req", choices=CNTR_REQ.decmapping.values(), default='no_counter',
- help="Counter requirement")
-option_parser.add_argument('--no-ciphering', action='store_true', default=False, help='Disable ciphering')
-option_parser.add_argument("--rc-cc-ds", choices=RC_CC_DS.decmapping.values(), default='cc',
- help="message check (rc=redundency check, cc=crypt. checksum, ds=digital signature)")
-option_parser.add_argument('--por-in-submit', action='store_true', default=False,
- help='require PoR to be sent via SMS-SUBMIT')
-option_parser.add_argument('--por-no-ciphering', action='store_true', default=False, help='Disable ciphering (PoR)')
-option_parser.add_argument("--por-rc-cc-ds", choices=RC_CC_DS.decmapping.values(), default='cc',
- help="PoR check (rc=redundency check, cc=crypt. checksum, ds=digital signature)")
-option_parser.add_argument("--por-req", choices=POR_REQ.decmapping.values(), default='por_required',
- help="Proof of Receipt requirements")
+argparse_add_ota_args(option_parser, sms=True)
option_parser.add_argument('--src-addr', default='12', type=str, help='SMS source address (MSISDN)')
option_parser.add_argument('--dest-addr', default='23', type=str, help='SMS destination address (MSISDN)')
option_parser.add_argument('--timeout', default=10, type=int, help='Maximum response waiting time')
@@ -267,24 +238,8 @@
format='%(asctime)s %(levelname)s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
- if opts.kic_idx != opts.kid_idx:
- logger.warning("KIC index (%s) and KID index (%s) are different (security violation, card should reject message)",
- opts.kic_idx, opts.kid_idx)
-
- ota_keyset = OtaKeyset(algo_crypt=opts.algo_crypt,
- kic_idx=opts.kic_idx,
- kic=h2b(opts.kic),
- algo_auth=opts.algo_auth,
- kid_idx=opts.kid_idx,
- kid=h2b(opts.kid),
- cntr=opts.cntr)
- spi = {'counter' : opts.cntr_req,
- 'ciphering' : not opts.no_ciphering,
- 'rc_cc_ds': opts.rc_cc_ds,
- 'por_in_submit': opts.por_in_submit,
- 'por_shall_be_ciphered': not opts.por_no_ciphering,
- 'por_rc_cc_ds': opts.por_rc_cc_ds,
- 'por': opts.por_req}
+ ota_keyset = ota_keyset_from_args(opts)
+ spi = ota_spi_from_args(opts)
if opts.format == 'expanded':
# TS 102 226 5.2.1.1: wrap each apdu in its own C-APDU TLV
apdu = [h2b(a) for a in opts.apdu]
--
To view, visit https://gerrit.osmocom.org/c/pysim/+/43722?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email
Gerrit-MessageType: merged
Gerrit-Project: pysim
Gerrit-Branch: master
Gerrit-Change-Id: Icea287f1a216fae4274f00a723a47ec19376a6ce
Gerrit-Change-Number: 43722
Gerrit-PatchSet: 3
Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de>
Gerrit-Reviewer: Jenkins Builder
Gerrit-Reviewer: dexter <pmaier(a)sysmocom.de>
Gerrit-Reviewer: laforge <laforge(a)osmocom.org>
1
0
[XL] Change in pysim[master]: cattp: ETSI TS 102 127 transport for OTA over BIP UDP
by laforge 25 Nov '26
by laforge 25 Nov '26
25 Nov '26
Attention is currently required from: Hoernchen.
laforge has posted comments on this change by Hoernchen. ( https://gerrit.osmocom.org/c/pysim/+/43719?usp=email )
Change subject: cattp: ETSI TS 102 127 transport for OTA over BIP UDP
......................................................................
Patch Set 2: Code-Review+2
--
To view, visit https://gerrit.osmocom.org/c/pysim/+/43719?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email
Gerrit-MessageType: comment
Gerrit-Project: pysim
Gerrit-Branch: master
Gerrit-Change-Id: I6f31493c1f0fb48fb3fd5382d8af2c905d365e54
Gerrit-Change-Number: 43719
Gerrit-PatchSet: 2
Gerrit-Owner: Hoernchen <ewild(a)sysmocom.de>
Gerrit-Reviewer: Jenkins Builder
Gerrit-Reviewer: dexter <pmaier(a)sysmocom.de>
Gerrit-Reviewer: laforge <laforge(a)osmocom.org>
Gerrit-Attention: Hoernchen <ewild(a)sysmocom.de>
Gerrit-Comment-Date: Wed, 25 Nov 2026 14:03:56 +0000
Gerrit-HasComments: No
Gerrit-Has-Labels: Yes
1
0