Hoernchen has uploaded this change for review. ( 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. Change-Id: I015c5eb8768c70751b198d9259c58dab22e4a8ff --- M pySim/bip.py M tests/unittests/test_bip_relay.py 2 files changed, 174 insertions(+), 18 deletions(-) git pull ssh://gerrit.osmocom.org:29418/pysim refs/changes/16/43716/1 diff --git a/pySim/bip.py b/pySim/bip.py index 1cd3ba0..a652d1d 100644 --- a/pySim/bip.py +++ b/pySim/bip.py @@ -27,7 +27,9 @@ # tp = init_reader(opts, proactive_handler=handler) +import collections import logging +import select import socket import threading import time @@ -74,7 +76,7 @@ # 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) @@ -205,6 +207,75 @@ self._reader.join(timeout=1.0) self.channels.channel_delete(self.chan_nr) + +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 connect(self, host: str, port: int, timeout: float = 10.0): + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + try: + s.connect((host, port)) + except OSError: + s.close() + raise + self.sock = s + self._reader = threading.Thread(target=self._rx_loop, + name='bip-rx-%d' % self.chan_nr, daemon=True) + self._reader.start() + + 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 +293,12 @@ self.channels = {} self._on_data_available = on_data_available - def channel_create(self) -> ProactChannel: + def channel_create(self, proto: str = 'tcp') -> ProactChannel: """Create a new proactive channel, allocating its integer number.""" + cls = {'tcp': ProactChannel, '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 +519,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 +534,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", @@ -568,10 +642,13 @@ payload = chan_data_ie.decoded 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) + # command_qualifier bit 1 selects 'send immediately' / Tx-buffer store and forward. + # TCP is a stream, so just send. UDP keeps datagram boundaries, TS 102 223 6.4.30. + if isinstance(chan, ProactUdpChannel): + cd_ie = Proact._find_first_element_of_type(pcmd.children, CommandDetails) + chan.send(payload, immediate=bool(cd_ie.decoded['command_qualifier'] & 0x01)) + else: + chan.send(payload) # 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..6a3c568 100644 --- a/tests/unittests/test_bip_relay.py +++ b/tests/unittests/test_bip_relay.py @@ -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,59 @@ self.assertEqual(_first(til, ChannelDataLength).decoded, 0) +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 +375,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 +454,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: newchange Gerrit-Project: pysim Gerrit-Branch: master Gerrit-Change-Id: I015c5eb8768c70751b198d9259c58dab22e4a8ff Gerrit-Change-Number: 43716 Gerrit-PatchSet: 1 Gerrit-Owner: Hoernchen <ewild@sysmocom.de>