Hoernchen has uploaded this change for review.
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,000 insertions(+), 0 deletions(-)
git pull ssh://gerrit.osmocom.org:29418/pysim refs/changes/19/43719/1
diff --git a/pySim/cattp.py b/pySim/cattp.py
new file mode 100644
index 0000000..ab6f346
--- /dev/null
+++ b/pySim/cattp.py
@@ -0,0 +1,605 @@
+# -*- 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@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 osmocom.utils import b2h
+
+logger = logging.getLogger(__name__)
+
+# TS 102 127 5.6.1 first octet: b8..b3 flags, b2..b1 version
+FLAG_SYN = 0x80
+FLAG_ACK = 0x40
+FLAG_EACK = 0x20
+FLAG_RST = 0x10
+FLAG_NUL = 0x08
+FLAG_SEG = 0x04
+VERSION = 0
+
+HDR_LEN = 18 # TS 102 127 5.6.2, without a variable header area
+
+# TS 102 127 5.10.1.4
+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'}
+
+
+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_diff(a: int, b: int) -> int:
+ """a - b modulo 2^16, < 0x8000 means a is at or after b"""
+ return (a - b) & 0xffff
+
+
+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
+
+ 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 _variable_header(self) -> bytes:
+ var = b''
+ if self.syn:
+ var += self.max_pdu.to_bytes(2, 'big') + self.max_sdu.to_bytes(2, 'big')
+ var += bytes([len(self.identification)]) + self.identification
+ elif self.has_eack:
+ var += b''.join(s.to_bytes(2, 'big') for s in self.eack)
+ if self.rst:
+ var += bytes([self.rst_reason])
+ return var
+
+ def to_bytes(self) -> bytes:
+ var = self._variable_header()
+ hdr = bytearray([self.flags | (self.version & 0x03), 0, 0, HDR_LEN + len(var)])
+ hdr += self.src_port.to_bytes(2, 'big') + self.dst_port.to_bytes(2, 'big')
+ hdr += len(self.data).to_bytes(2, 'big')
+ hdr += self.seq.to_bytes(2, 'big') + self.ack.to_bytes(2, 'big')
+ hdr += self.window.to_bytes(2, 'big') + b'\x00\x00' + var
+ csum = checksum(bytes(hdr) + self.data)
+ hdr[16:18] = csum.to_bytes(2, 'big')
+ return bytes(hdr) + self.data
+
+ @classmethod
+ def from_bytes(cls, raw: bytes) -> 'Pdu':
+ if len(raw) < HDR_LEN:
+ raise CatTpError('PDU of %u octets is shorter than the header' % len(raw))
+ hdr_len = raw[3]
+ data_len = int.from_bytes(raw[8:10], 'big')
+ if hdr_len < HDR_LEN or hdr_len + data_len != len(raw):
+ raise CatTpError('header length %u + data length %u != %u octets' %
+ (hdr_len, data_len, len(raw)))
+ if checksum(raw[:16] + b'\x00\x00' + raw[18:]) != int.from_bytes(raw[16:18], 'big'):
+ raise CatTpError('checksum mismatch')
+ pdu = cls(raw[0] & 0xfc, int.from_bytes(raw[4:6], 'big'), int.from_bytes(raw[6:8], 'big'),
+ seq=int.from_bytes(raw[10:12], 'big'), ack=int.from_bytes(raw[12:14], 'big'),
+ window=int.from_bytes(raw[14:16], 'big'), data=raw[hdr_len:],
+ version=raw[0] & 0x03)
+ var = raw[HDR_LEN:hdr_len]
+ if pdu.syn:
+ if len(var) < 5 or len(var) != 5 + var[4]:
+ raise CatTpError('malformed SYN variable header')
+ pdu.max_pdu = int.from_bytes(var[0:2], 'big')
+ pdu.max_sdu = int.from_bytes(var[2:4], 'big')
+ pdu.identification = var[5:]
+ var = b''
+ elif pdu.has_eack:
+ n = len(var) - (1 if pdu.rst else 0)
+ if n & 1:
+ raise CatTpError('malformed EACK variable header')
+ pdu.eack = tuple(int.from_bytes(var[i:i + 2], 'big') for i in range(0, n, 2))
+ var = var[n:]
+ if pdu.rst:
+ if len(var) != 1:
+ raise CatTpError('malformed RST variable header')
+ pdu.rst_reason = var[0]
+ return pdu
+
+ def __repr__(self):
+ names = [n for f, n in ((FLAG_SYN, 'SYN'), (FLAG_ACK, 'ACK'), (FLAG_EACK, 'EACK'),
+ (FLAG_RST, 'RST'), (FLAG_NUL, 'NUL'), (FLAG_SEG, 'SEG')) if self.flags & f]
+ 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 = (self.snd_nxt + 1) & 0xffff
+ 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 = (self.snd_nxt + 1) & 0xffff
+ 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 ((self.rcv_cur + 1) & 0xffff) in self.rcv_out_of_seq:
+ self._accept(self.rcv_out_of_seq.pop((self.rcv_cur + 1) & 0xffff))
+
+ 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(0x10000)
+ self.snd_nxt = (self.snd_ini + 1) & 0xffff
+ 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 = (self.snd_una - 1) & 0xffff
+ if _seq_diff(pdu.ack, base) > _seq_diff((self.snd_nxt - 1) & 0xffff, 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 _seq_diff(pdu.ack, e[0].seq) >= 0x8000 and e[0].seq not in acked]
+ if _seq_diff(pdu.ack, self.snd_una) < 0x8000:
+ self.snd_una = (pdu.ack + 1) & 0xffff
+ # TS 102 127 5.3.3: the right window border never moves left
+ right = (pdu.ack + pdu.window) & 0xffff
+ if _seq_diff(right, self.snd_right) < 0x8000:
+ self.snd_right = right
+ self._flush_window()
+
+ def _flush_window(self):
+ while self._tx_wait and _seq_diff(self.snd_right, self._tx_wait[0].seq) < 0x8000:
+ 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.
+
+ on_sdu / on_state run on the server thread, sending from them puts the response and the
+ ACK into the same PDU."""
+ POLL = 0.05
+
+ 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:
+ 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):
+ 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(65535)
+ 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):
+ 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..5705acb
--- /dev/null
+++ b/tests/unittests/test_cattp.py
@@ -0,0 +1,395 @@
+#!/usr/bin/env python3
+
+# (C) 2026 by sysmocom - s.f.m.c. GmbH
+# All Rights Reserved
+#
+# Author: Eric Wild <ewild@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, 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 (18 + 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))
+
+
+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 change 43719. To unsubscribe, or for help writing mail filters, visit settings.