laforge has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/43716?usp=email ) Change subject: bip: UDP channels for CAT_TP ...................................................................... bip: UDP channels for CAT_TP Humble beginnings of CAT_TP support: OPEN CHANNEL with "UDP, UICC in client mode, remote connection" gets a datagram socket. SEND DATA without "send immediately" is buffered, TERMINAL PROFILE byte 17 announces our new UDP client mode. ProactChannel becomes the abstract base of ProactTcpChannel and ProactUdpChannel. Change-Id: I015c5eb8768c70751b198d9259c58dab22e4a8ff --- M pySim/bip.py M tests/unittests/test_bip_relay.py 2 files changed, 245 insertions(+), 60 deletions(-) Approvals: Jenkins Builder: Verified laforge: Looks good to me, but someone else must approve dexter: Looks good to me, approved diff --git a/pySim/bip.py b/pySim/bip.py index 1cd3ba0..2c0b244 100644 --- a/pySim/bip.py +++ b/pySim/bip.py @@ -27,7 +27,10 @@ # tp = init_reader(opts, proactive_handler=handler) +import abc +import collections import logging +import select import socket import threading import time @@ -74,16 +77,17 @@ # 13 (class "e" supported bearers): b2 GPRS, and b6..b8 the number of channels. profile[12] = 0x02 | (num_channels << 5) profile[13] = 0x40 | 0x20 # 14: b6 no display capability, b7 no keypad available - profile[16] = 0x01 # 15: b1 TCP, UICC in client mode, remote connection + profile[16] = 0x01 | 0x02 # 17: b1 TCP, b2 UDP, UICC in client mode, remote connection return bytes(profile) -class ProactChannel: - """One BIP channel, TS 102 223 class "e", backed by a blocking TCP socket. +class ProactChannel(abc.ABC): + """One BIP channel, TS 102 223 class "e", backed by a blocking socket. Created by ProactChannels.channel_create(). A reader thread fills the Rx buffer from the socket, the Proact handlers drain it (RECEIVE DATA) and write to it (SEND DATA). Payload - is opaque, TLS or CAT_TP run on the card. + is opaque, TLS or CAT_TP run on the card. ProactTcpChannel and ProactUdpChannel supply the + socket, the reader loop and send(). Args: channels: the owning ProactChannels, notified of data arrival and of close() @@ -98,8 +102,6 @@ # Plain blocking sockets just work: connect() in handle_OpenChannel, send() in # handle_SendData, recv() feeding a buffer for handle_ReceiveData. No need to make it # harder than it has to be to handle the "massive" T0 bandwidth.. - # how much we try to read off the socket per recv() - RECV_CHUNK = 4096 def __init__(self, channels: 'ProactChannels', chan_nr: int): self.channels = channels @@ -114,48 +116,25 @@ self.peer_closed = False def connect(self, host: str, port: int, timeout: float = 10.0): - """Open the blocking TCP socket and start the background Rx reader.""" - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - try: - s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) - s.settimeout(timeout) - s.connect((host, port)) - # Back to blocking mode for the reader thread. - # CLOSE CHANNEL unblocks the pending recv() via shutdown(). - s.settimeout(None) - except OSError: - s.close() - raise - self.sock = s + """Open the socket and start the background Rx reader.""" + self.sock = self._open_socket(host, port, timeout) self._reader = threading.Thread(target=self._rx_loop, name='bip-rx-%d' % self.chan_nr, daemon=True) self._reader.start() + @abc.abstractmethod + def _open_socket(self, host: str, port: int, timeout: float) -> socket.socket: + """Return the connected socket, raise OSError if that fails.""" + + @abc.abstractmethod def _rx_loop(self): - """Continuously read from the socket into rx_buf, like a real ME. + """Reader thread: move received data into rx_buf until the channel closes and call + channels.notify_data_available() when data arrives in the empty buffer.""" - TS 102 223 7.5.10.1 says the event is raised 'only if the targeted channel buffer is - empty when new data arrives in it', so the data available hook fires on the - empty->non-empty transition only. That is enough: every RECEIVE DATA response tells - the card how many bytes remain, so it keeps fetching until the buffer is empty, and - the next event restarts it when more data arrives.""" - while not self._closing: - try: - data = self.sock.recv(self.RECV_CHUNK) - except (OSError, ValueError): - break - if not data: - self.peer_closed = True - break - with self._rx_lock: - was_empty = len(self.rx_buf) == 0 - self.rx_buf.extend(data) - if was_empty and not self._closing: - self.channels.notify_data_available(self) - - def send(self, data: bytes): - """Tx, write bytes to the socket == SEND DATA""" - self.sock.sendall(data) + @abc.abstractmethod + def send(self, data: bytes, immediate: bool = True): + """SEND DATA. immediate is bit 1 of the command qualifier, "send immediately" as + opposed to "store in the Tx buffer" (TS 102 223 6.4.30).""" def available_rx(self) -> int: """Number of bytes waiting in the Rx buffer, what RECEIVE DATA can return right now.""" @@ -205,6 +184,118 @@ self._reader.join(timeout=1.0) self.channels.channel_delete(self.chan_nr) + +class ProactTcpChannel(ProactChannel): + """BIP channel on a TCP socket, a byte stream as used by SCP81.""" + # how much we try to read off the socket per recv() + RECV_CHUNK = 4096 + + def _open_socket(self, host: str, port: int, timeout: float) -> socket.socket: + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + try: + s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + s.settimeout(timeout) + s.connect((host, port)) + # Back to blocking mode for the reader thread. + # CLOSE CHANNEL unblocks the pending recv() via shutdown(). + s.settimeout(None) + except OSError: + s.close() + raise + return s + + def _rx_loop(self): + """Continuously read from the socket into rx_buf, like a real ME. + + TS 102 223 7.5.10.1 says the event is raised 'only if the targeted channel buffer is + empty when new data arrives in it', so the data available hook fires on the + empty->non-empty transition only. That is enough: every RECEIVE DATA response tells + the card how many bytes remain, so it keeps fetching until the buffer is empty, and + the next event restarts it when more data arrives.""" + while not self._closing: + try: + data = self.sock.recv(self.RECV_CHUNK) + except (OSError, ValueError): + break + if not data: + self.peer_closed = True + break + with self._rx_lock: + was_empty = len(self.rx_buf) == 0 + self.rx_buf.extend(data) + if was_empty and not self._closing: + self.channels.notify_data_available(self) + + def send(self, data: bytes, immediate: bool = True): + # a stream has no SDU boundary to keep, so nothing is held back + self.sock.sendall(data) + + +class ProactUdpChannel(ProactChannel): + """BIP channel on a connected UDP socket, for CAT_TP (TS 102 127 section 6). + + TS 102 223 6.4.29/6.4.30: the Rx buffer holds one datagram SDU at a time, the next one is + inserted only once the card drained it, and the Tx buffer collects SEND DATA until "send + immediately", which emits it as one datagram.""" + RECV_CHUNK = 65535 + + def __init__(self, channels: 'ProactChannels', chan_nr: int): + super().__init__(channels, chan_nr) + self.rx_dgrams = collections.deque() # datagrams waiting behind the current one + self.tx_buf = bytearray() + + def _open_socket(self, host: str, port: int, timeout: float) -> socket.socket: + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + try: + s.connect((host, port)) + except OSError: + s.close() + raise + return s + + def _rx_loop(self): + """One datagram per recv(). The data available event is raised for the datagram that + lands in an empty buffer, and again when the next queued one moves into the buffer.""" + while not self._closing: + try: + readable, _, _ = select.select([self.sock], [], [], 0.02) + except (OSError, ValueError): + break + if readable: + try: + data = self.sock.recv(self.RECV_CHUNK) + except ConnectionRefusedError: + logger.warning("channel %u: ICMP port unreachable from peer", self.chan_nr) + continue + except (OSError, ValueError): + break + with self._rx_lock: + was_empty = len(self.rx_buf) == 0 + if was_empty: + self.rx_buf.extend(data) + else: + self.rx_dgrams.append(data) + if was_empty and not self._closing: + self.channels.notify_data_available(self) + self._advance() + + def _advance(self): + """Move the next datagram into the drained buffer, from the reader thread so the + notification never runs on the thread that is driving the card.""" + with self._rx_lock: + if self.rx_buf or not self.rx_dgrams: + return + self.rx_buf.extend(self.rx_dgrams.popleft()) + if not self._closing: + self.channels.notify_data_available(self) + + def send(self, data: bytes, immediate: bool = True): + self.tx_buf.extend(data) + if immediate: + self.sock.send(bytes(self.tx_buf)) + self.tx_buf.clear() + + class ProactChannels: """The open BIP channels of one terminal, keyed by channel number. @@ -222,11 +313,16 @@ self.channels = {} self._on_data_available = on_data_available - def channel_create(self) -> ProactChannel: - """Create a new proactive channel, allocating its integer number.""" + def channel_create(self, proto: str = 'tcp') -> ProactChannel: + """Create a new proactive channel, allocating its integer number. + + Args: + proto: 'tcp' for a ProactTcpChannel, 'udp' for a ProactUdpChannel + """ + cls = {'tcp': ProactTcpChannel, 'udp': ProactUdpChannel}[proto] for i in range(1, self.MAX_CHANNELS + 1): if not i in self.channels: - self.channels[i] = ProactChannel(self, i) + self.channels[i] = cls(self, i) return self.channels[i] raise ValueError('Cannot allocate another channel: All channels active') @@ -447,7 +543,8 @@ # UICC/terminal interface transport level is Optional, TS 102 223 6.6.27.x. Absent means # the CAT application runs its own network and transport layer, which we do not do. - if transp_lvl_ie is None or transp_lvl_ie.decoded['protocol_type'] != 'tcp_uicc_client_remote': + protos = {'tcp_uicc_client_remote': 'tcp', 'udp_uicc_client_remote': 'udp'} + if transp_lvl_ie is None or transp_lvl_ie.decoded['protocol_type'] not in protos: logger.warning("OpenChannel: unsupported UICC/terminal interface transport level (%s) " "-> refusing", transp_lvl_ie.decoded if transp_lvl_ie else '(absent)') return refuse('requested_uicc_if_transp_level_not_available') @@ -461,9 +558,10 @@ other_addr_ie.decoded['address'], str) else other_addr_ie.decoded['address'] ipv4_str = '%u.%u.%u.%u' % (addr_bytes[0], addr_bytes[1], addr_bytes[2], addr_bytes[3]) port_nr = transp_lvl_ie.decoded['port_number'] - logger.info("OpenChannel: connecting to %s:%u", ipv4_str, port_nr) + proto = protos[transp_lvl_ie.decoded['protocol_type']] + logger.info("OpenChannel: connecting to %s:%u (%s)", ipv4_str, port_nr, proto) try: - channel = self.channels.channel_create() + channel = self.channels.channel_create(proto) except ValueError: # TS 102 223 6.4.27.2 and 6.4.27.3: no channel left -> BIP error logger.warning("OpenChannel: all %u channels are in use -> refusing", @@ -569,9 +667,8 @@ if isinstance(payload, str): payload = h2b(payload) # command_qualifier bit 1 selects 'send immediately' / Tx-buffer store and forward - # For TCP stream all we have is a socket and TCP takes care of segmentation, - # so just send. - chan.send(payload) + cd_ie = Proact._find_first_element_of_type(pcmd.children, CommandDetails) + chan.send(payload, immediate=bool(cd_ie.decoded['command_qualifier'] & 0x01)) # Terminal Response example: [ # {'command_details': {'command_number': 1, # 'type_of_command': 'send_data', diff --git a/tests/unittests/test_bip_relay.py b/tests/unittests/test_bip_relay.py index 5f72411..b4fe9d4 100644 --- a/tests/unittests/test_bip_relay.py +++ b/tests/unittests/test_bip_relay.py @@ -30,7 +30,7 @@ OtherAddress, ChannelData, ChannelDataLength, ChannelStatus, Result, LocationInformation) -from pySim.bip import Proact, ProactChannels, terminal_profile +from pySim.bip import Proact, ProactChannels, ProactTcpChannel, ProactUdpChannel, terminal_profile class _EchoServer: @@ -71,6 +71,33 @@ pass +class _UdpEchoServer: + """echoes every datagram, and records them so datagram boundaries can be asserted""" + def __init__(self): + self._srv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + self._srv.bind(('127.0.0.1', 0)) + self._srv.settimeout(0.1) + self.port = self._srv.getsockname()[1] + self.datagrams = [] + self._stop = False + threading.Thread(target=self._run, daemon=True).start() + + def _run(self): + while not self._stop: + try: + data, addr = self._srv.recvfrom(65535) + except socket.timeout: + continue + except OSError: + break + self.datagrams.append(data) + self._srv.sendto(data, addr) + + def close(self): + self._stop = True + self._srv.close() + + def _pcmd(children_tlvs): """Assemble D0 proactive-command TLV from child IE bytes, decode it like transport does after a FETCH""" @@ -79,7 +106,7 @@ return ProactiveCommand().from_tlv(pdu) -def _open_channel(port, ip='127.0.0.1', cmd_nr=1): +def _open_channel(port, ip='127.0.0.1', cmd_nr=1, proto='tcp_uicc_client_remote'): a, b, c, d = (int(x) for x in ip.split('.')) return _pcmd([ CommandDetails(decoded={'command_number': cmd_nr, 'type_of_command': 'open_channel', @@ -87,8 +114,7 @@ DeviceIdentities(decoded={'source_dev_id': 'uicc', 'dest_dev_id': 'terminal'}).to_tlv(), BearerDescription(decoded={'bearer_type': 'default', 'bearer_parameters': b''}).to_tlv(), BufferSize(decoded=1024).to_tlv(), - UiccTransportLevel(decoded={'protocol_type': 'tcp_uicc_client_remote', - 'port_number': port}).to_tlv(), + UiccTransportLevel(decoded={'protocol_type': proto, 'port_number': port}).to_tlv(), OtherAddress(decoded={'type_of_address': 'ipv4', 'address': bytes([a, b, c, d])}).to_tlv(), ]) @@ -105,10 +131,10 @@ ] + extra_ies) -def _send_data(payload, chan='channel_1', cmd_nr=1): +def _send_data(payload, chan='channel_1', cmd_nr=1, immediate=True): return _pcmd([ CommandDetails(decoded={'command_number': cmd_nr, 'type_of_command': 'send_data', - 'command_qualifier': 1}).to_tlv(), + 'command_qualifier': 1 if immediate else 0}).to_tlv(), DeviceIdentities(decoded={'source_dev_id': 'uicc', 'dest_dev_id': chan}).to_tlv(), ChannelData(decoded=b2h(payload)).to_tlv(), ]) @@ -266,6 +292,68 @@ self.assertEqual(_first(til, ChannelDataLength).decoded, 0) +class ChannelCreateTest(unittest.TestCase): + def test_proto_selects_the_channel_class(self): + channels = ProactChannels() + self.assertIsInstance(channels.channel_create(), ProactTcpChannel) + self.assertIsInstance(channels.channel_create('tcp'), ProactTcpChannel) + self.assertIsInstance(channels.channel_create('udp'), ProactUdpChannel) + self.assertEqual(sorted(channels.channels), [1, 2, 3]) + + +class BipUdpRelayTest(unittest.TestCase): + """UDP channels keep datagram boundaries, TS 102 223 6.4.29 and 6.4.30""" + + def setUp(self): + self.echo = _UdpEchoServer() + self.addCleanup(self.echo.close) + self.events = [] + self.proact = Proact(data_available_sink=self.events.append) + self.addCleanup(lambda: [c.close() for c in list(self.proact.channels.channels.values())]) + til = self.proact.handle_OpenChannel(_open_channel(self.echo.port, proto='udp_uicc_client_remote')) + b''.join(x.to_tlv() for x in til) + self.assertEqual(_first(til, Result).decoded['general_result'], 'performed_successfully') + self.assertEqual(_first(til, ChannelStatus).decoded, '8100') + self.chan = self.proact.channels.channels[1] + + def _wait_events(self, n, timeout=2.0): + deadline = time.monotonic() + timeout + while len(self.events) < n and time.monotonic() < deadline: + time.sleep(0.01) + return len(self.events) + + def test_store_and_forward_is_one_datagram(self): + # two buffered SEND DATA and a final "send immediately" leave as a single datagram + self.proact.handle_SendData(_send_data(b'one', immediate=False)) + self.proact.handle_SendData(_send_data(b'two', immediate=False)) + self.assertEqual(self.echo.datagrams, []) + self.proact.handle_SendData(_send_data(b'three')) + self.assertGreater(self.chan.wait_rx(2.0), 0) + self.assertEqual(self.echo.datagrams, [b'onetwothree']) + + def test_rx_one_sdu_at_a_time(self): + # two datagrams from the peer: RECEIVE DATA never crosses into the second one, and + # the second raises its own data available event once the first is drained + self.proact.handle_SendData(_send_data(b'first')) + self.proact.handle_SendData(_send_data(b'second')) + time.sleep(0.2) + self.assertEqual(self._wait_events(1), 1) + self.assertEqual(self.chan.available_rx(), 5) + til = self.proact.handle_ReceiveData(_receive_data(100)) + self.assertEqual(h2b(_first(til, ChannelData).decoded), b'first') + self.assertEqual(_first(til, ChannelDataLength).decoded, 0) + self.assertEqual(_first(til, Result).decoded['general_result'], + 'performed_with_missing_information') + self.assertEqual(self._wait_events(2), 2) + self.assertEqual(h2b(self.events[1])[-1], 6) # channel data length = len(b'second') + til = self.proact.handle_ReceiveData(_receive_data(3)) + self.assertEqual(h2b(_first(til, ChannelData).decoded), b'sec') + self.assertEqual(_first(til, ChannelDataLength).decoded, 3) + til = self.proact.handle_ReceiveData(_receive_data(3)) + self.assertEqual(h2b(_first(til, ChannelData).decoded), b'ond') + self.assertEqual(_first(til, ChannelDataLength).decoded, 0) + + class OpenChannelRefusalTest(unittest.TestCase): """Refusal is a TERMINAL RESPONSE, not an exception, raising takes the whole proactive session down and leaves the card wondering why""" @@ -296,8 +384,8 @@ def test_transport_level(self): cases = [[self.ADDR.to_tlv()]] # absent, 6.6.27.x Optional - for proto in ('udp_uicc_client_remote', 'tcp_uicc_server', 'udp_uicc_client_local', - 'tcp_uicc_client_local', 'direct_channel'): # not TCP client remote + for proto in ('tcp_uicc_server', 'udp_uicc_client_local', 'tcp_uicc_client_local', + 'direct_channel'): # not client mode remote tl = UiccTransportLevel(decoded={'protocol_type': proto, 'port_number': 1234}) cases.append([tl.to_tlv(), self.ADDR.to_tlv()]) for extra in cases: @@ -375,7 +463,7 @@ self.assertEqual(self.byte(12), 0x1f) # OPEN/CLOSE CHANNEL, RECEIVE/SEND DATA, STATUS self.assertEqual(self.byte(13) >> 5, ProactChannels.MAX_CHANNELS) self.assertEqual(self.byte(14), 0x60) # class ND, class NK - self.assertEqual(self.byte(17), 0x01) # TCP, UICC client mode, remote + self.assertEqual(self.byte(17), 0x03) # TCP + UDP, UICC client mode, remote def test_not_announced(self): self.assertEqual(self.byte(3) & 0x60, 0) # POLL INTERVAL, POLLING OFF -- To view, visit https://gerrit.osmocom.org/c/pysim/+/43716?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: I015c5eb8768c70751b198d9259c58dab22e4a8ff Gerrit-Change-Number: 43716 Gerrit-PatchSet: 3 Gerrit-Owner: Hoernchen <ewild@sysmocom.de> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: dexter <pmaier@sysmocom.de> Gerrit-Reviewer: laforge <laforge@osmocom.org>