diff --git a/CHANGES.md b/CHANGES.md index b7fa1eae..b2f08dc9 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -18,6 +18,14 @@ Unreleased * data_4: Received data from u_send transmissions * datablock_count: 0 for b_send or 1-4 for u_send transmissions. +### Bug fixes + +* `disconnect()` no longer sends a COTP disconnect request, in both clients. It closes its sending side of the TCP + connection, waits up to one second for the PLC to close its own, and then closes the socket; RFC 1006 releases a + connection that way. A CP 343-1 answered the disconnect request with a reset and kept the connection's resource + until the PLC restarted. The reporter confirmed on a CPU 313C behind a CP 343-1 that the resource is now + released (#972, #987). + 3.6.0 ----- diff --git a/snap7/async_client.py b/snap7/async_client.py index 1e38b6ea..af7d73ab 100644 --- a/snap7/async_client.py +++ b/snap7/async_client.py @@ -55,8 +55,12 @@ class AsyncISOTCPConnection: COTP_CR = 0xE0 # Connection Request COTP_CC = 0xD0 # Connection Confirm COTP_DR = 0x80 # Disconnect Request + COTP_DC = 0xC0 # Disconnect Confirm COTP_DT = 0xF0 # Data Transfer + # See ISOTCPConnection.DISCONNECT_CLOSE_TIMEOUT (#972). + DISCONNECT_CLOSE_TIMEOUT = 1.0 + # COTP parameter codes (ISO 8073) COTP_PARAM_PDU_SIZE = 0xC0 COTP_PARAM_CALLING_TSAP = 0xC1 @@ -128,17 +132,14 @@ async def disconnect(self) -> None: if self._writer: try: if self.connected: - dr_pdu = struct.pack( - ">BBHHBB", - 6, - self.COTP_DR, - self.dst_ref, - self.src_ref, - 0x00, - 0x00, - ) - self._writer.write(self._build_tpkt(dr_pdu)) - await self._writer.drain() + # No COTP disconnect request: see ISOTCPConnection.disconnect() (#972). + # Close our sending side and let the peer close its own first. + if self._writer.can_write_eof(): + self._writer.write_eof() + await self._await_peer_close() + except Exception: + pass + try: self._writer.close() await self._writer.wait_closed() except Exception: @@ -149,6 +150,22 @@ async def disconnect(self) -> None: self.connected = False logger.info(f"Disconnected from {self.host}:{self.port}") + async def _await_peer_close(self) -> None: + """Wait, briefly, for the peer to close the connection after our FIN.""" + if self._reader is None: + return + loop = asyncio.get_running_loop() + deadline = loop.time() + min(self.timeout, self.DISCONNECT_CLOSE_TIMEOUT) + while True: + remaining = deadline - loop.time() + if remaining <= 0: + return + try: + if not await asyncio.wait_for(self._reader.read(1024), timeout=remaining): + return # the peer closed the connection + except (asyncio.TimeoutError, OSError): + return + async def send_data(self, data: bytes) -> None: """Send data over ISO connection.""" if not self.connected or self._writer is None: diff --git a/snap7/connection.py b/snap7/connection.py index f6893543..b72a0c61 100644 --- a/snap7/connection.py +++ b/snap7/connection.py @@ -9,6 +9,7 @@ import socket import struct import logging +import time from enum import IntEnum from typing import Optional, Type, Union from types import TracebackType @@ -66,6 +67,10 @@ class ISOTCPConnection: COTP_PARAM_SUBNET_ID = 0xC6 COTP_PARAM_ROUTING_TSAP = 0xC7 + # How long disconnect() waits, after closing its sending side, for the peer to close + # the connection too before it closes the socket itself (#972). + DISCONNECT_CLOSE_TIMEOUT = 1.0 + def __init__( self, host: str, @@ -155,12 +160,19 @@ def disconnect(self) -> None: if self.socket: try: if self.connected: - # Send COTP disconnect request - self._send_cotp_disconnect() - self.socket.close() + # RFC 1006 releases a connection by closing the TCP connection; no + # COTP disconnect request is sent. A CP 343-1 answered such a request + # with a reset and kept the connection's resource (#972). Close our + # sending side and let the peer close its own before the socket goes. + self.socket.shutdown(socket.SHUT_WR) + self._await_peer_close() except Exception: pass # Ignore errors during disconnect finally: + try: + self.socket.close() + except Exception: + pass self.socket = None self.connected = False logger.info(f"Disconnected from {self.host}:{self.port}") @@ -431,26 +443,26 @@ def _parse_cotp_data(self, cotp_pdu: bytes) -> bytes: return cotp_pdu[3:] # Return data portion - def _send_cotp_disconnect(self) -> None: - """Send COTP Disconnect Request.""" - if self.socket is None: - return # Nothing to disconnect - - dr_pdu = struct.pack( - ">BBHHBB", - 6, # PDU length - self.COTP_DR, # PDU type - self.dst_ref, # Destination reference - self.src_ref, # Source reference - 0x00, # Reason (normal disconnect) - 0x00, # Additional info - ) + def _await_peer_close(self) -> None: + """Wait, briefly, for the peer to close the connection after our FIN. - tpkt_frame = self._build_tpkt(dr_pdu) - try: - self.socket.sendall(tpkt_frame) - except socket.error: - pass # Ignore errors during disconnect + Returns when the peer closes or resets the connection, or when + :attr:`DISCONNECT_CLOSE_TIMEOUT` (at most the connection timeout) has passed. + Data still in flight is discarded. + """ + if self.socket is None: + return + deadline = time.monotonic() + min(self.timeout, self.DISCONNECT_CLOSE_TIMEOUT) + while True: + remaining = deadline - time.monotonic() + if remaining <= 0: + return + self.socket.settimeout(remaining) + try: + if not self.socket.recv(1024): + return # the peer closed the connection + except (socket.timeout, OSError): + return def _recv_exact(self, size: int) -> bytes: """ diff --git a/tests/test_async_client.py b/tests/test_async_client.py index 55d959d7..12203e1b 100644 --- a/tests/test_async_client.py +++ b/tests/test_async_client.py @@ -7,7 +7,7 @@ import logging import struct from collections.abc import AsyncGenerator, Generator -from unittest.mock import AsyncMock, MagicMock, patch +from unittest.mock import AsyncMock, patch import pytest import pytest_asyncio @@ -341,21 +341,41 @@ def test_async_cotp_accepts_valid_pdu_sizes(parameter: bytes, expected: int) -> @pytest.mark.asyncio -async def test_async_disconnect_request_addresses_the_peer_reference() -> None: - """The DR carries the CC's source reference as its destination reference (#972).""" +async def test_async_cc_gives_the_peer_reference() -> None: connection = AsyncISOTCPConnection("127.0.0.1") # COTP CC from a CP 343-1 (#972): dst-ref 0x0001 echoes ours, src-ref 0x4431 is the CP's. connection._parse_cotp_cc(bytes.fromhex("11 d0 0001 4431 00 c0 01 0a c1 02 01 00 c2 02 01 02")) assert connection.dst_ref == 0x4431 - writer = MagicMock() - writer.drain = AsyncMock() - writer.wait_closed = AsyncMock() - connection._writer = writer + + +@pytest.mark.asyncio +async def test_async_disconnect_sends_a_fin_and_no_disconnect_request() -> None: + """disconnect() sends no COTP DR: it sends a FIN and lets the peer close first (#972).""" + seen: dict[str, object] = {} + done = asyncio.Event() + + async def peer(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: + seen["received"] = await reader.read(64) + # Our side is only half closed: the peer can still send before it closes. + writer.write(b"late") + await writer.drain() + writer.close() + done.set() + + server = await asyncio.start_server(peer, "127.0.0.1", 0) + port = server.sockets[0].getsockname()[1] + connection = AsyncISOTCPConnection("127.0.0.1", port) + connection._reader, connection._writer = await asyncio.open_connection("127.0.0.1", port) connection.connected = True + connection.dst_ref = 0x4431 await connection.disconnect() + await asyncio.wait_for(done.wait(), timeout=5.0) + server.close() + await server.wait_closed() - writer.write.assert_called_once_with(bytes.fromhex("03 00 00 0c 06 80 4431 0001 00 00")) + assert seen["received"] == b"" # a FIN, and no disconnect request before it + assert connection._writer is None and connection.connected is False @pytest.mark.parametrize( diff --git a/tests/test_connection.py b/tests/test_connection.py index 8c98b9e0..3499e5b4 100644 --- a/tests/test_connection.py +++ b/tests/test_connection.py @@ -2,6 +2,8 @@ import socket import struct +import threading +import time import pytest from unittest.mock import patch, MagicMock @@ -89,8 +91,8 @@ def test_valid_cc(self) -> None: # COTP CC from a CP 343-1 in front of an S7-313C-2 DP, captured for #972 (after the # TPKT header): dst-ref 0x0001 echoes our reference, src-ref 0x4431 is the CP's. CAPTURED_CC = bytes.fromhex("11 d0 0001 4431 00 c0 01 0a c1 02 01 00 c2 02 01 02") - # The DR must address the CP's reference; python-snap7 3.3.1 sent 06 80 0001 0001 00 00. - EXPECTED_DR = bytes.fromhex("03 00 00 0c 06 80 4431 0001 00 00") + # The DR must address the CP's reference; python-snap7 3.3.1 sent 06 80 0001 0001 00 00, + # and up to 3.4.0 a stray user-data byte followed the reason. def test_captured_cc_gives_the_peer_reference(self) -> None: conn = ISOTCPConnection("1.2.3.4") @@ -98,14 +100,16 @@ def test_captured_cc_gives_the_peer_reference(self) -> None: assert conn.dst_ref == 0x4431 assert conn.src_ref == 0x0001 - def test_disconnect_request_addresses_the_peer_reference(self) -> None: + def test_disconnect_sends_no_disconnect_request(self) -> None: conn = ISOTCPConnection("1.2.3.4") conn._parse_cotp_cc(self.CAPTURED_CC) sock = MagicMock() + sock.recv.return_value = b"" conn.socket = sock conn.connected = True conn.disconnect() - sock.sendall.assert_called_once_with(self.EXPECTED_DR) + sock.sendall.assert_not_called() + sock.shutdown.assert_called_once_with(socket.SHUT_WR) def test_cc_too_short(self) -> None: conn = ISOTCPConnection("1.2.3.4") @@ -304,31 +308,6 @@ def test_socket_error(self) -> None: conn._recv_exact(4) -class TestSendCOTPDisconnect: - """Test _send_cotp_disconnect().""" - - def test_disconnect_no_socket(self) -> None: - conn = ISOTCPConnection("1.2.3.4") - conn.socket = None - # Should return without error - conn._send_cotp_disconnect() - - def test_disconnect_sends_dr(self) -> None: - conn = ISOTCPConnection("1.2.3.4") - mock_socket = MagicMock() - conn.socket = mock_socket - conn._send_cotp_disconnect() - mock_socket.sendall.assert_called_once() - - def test_disconnect_ignores_socket_error(self) -> None: - conn = ISOTCPConnection("1.2.3.4") - mock_socket = MagicMock() - mock_socket.sendall.side_effect = socket.error("broken") - conn.socket = mock_socket - # Should not raise - conn._send_cotp_disconnect() - - class TestConnect: """Test connect() orchestration.""" @@ -370,6 +349,7 @@ def test_disconnect_when_no_socket(self) -> None: def test_disconnect_closes_socket(self) -> None: conn = ISOTCPConnection("1.2.3.4") mock_socket = MagicMock() + mock_socket.recv.return_value = b"" conn.socket = mock_socket conn.connected = True conn.disconnect() @@ -387,6 +367,81 @@ def test_disconnect_ignores_errors(self) -> None: assert conn.socket is None +class TestDisconnectClosesTheTcpConnection: + """disconnect() sends no COTP DR: it sends a FIN and lets the peer close first (#972).""" + + @staticmethod + def _connected_pair() -> tuple[ISOTCPConnection, socket.socket]: + ours, peer = socket.socketpair() + conn = ISOTCPConnection("1.2.3.4") + conn.socket = ours + conn.connected = True + conn.dst_ref = 0x4431 + return conn, peer + + def test_peer_sees_only_a_fin_and_can_still_answer(self) -> None: + conn, peer = self._connected_pair() + seen: dict[str, object] = {} + + def answer() -> None: + peer.settimeout(2.0) + seen["received"] = peer.recv(64) + # Our side is only half closed: the peer can still send before it closes. + try: + peer.sendall(b"late") + seen["could_send"] = True + except OSError: + seen["could_send"] = False + peer.close() + + thread = threading.Thread(target=answer) + thread.start() + start = time.monotonic() + conn.disconnect() + elapsed = time.monotonic() - start + thread.join(5.0) + + assert seen["received"] == b"" # a FIN, and no disconnect request before it + assert seen["could_send"] is True + assert elapsed < 0.5 # returned when the peer closed, not at the timeout + assert conn.socket is None and conn.connected is False + + def test_returns_when_the_peer_has_closed(self) -> None: + conn, peer = self._connected_pair() + peer.close() + start = time.monotonic() + conn.disconnect() + assert time.monotonic() - start < 0.5 + assert conn.socket is None + + def test_silent_peer_is_bounded(self, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(ISOTCPConnection, "DISCONNECT_CLOSE_TIMEOUT", 0.2) + conn, peer = self._connected_pair() + start = time.monotonic() + conn.disconnect() + elapsed = time.monotonic() - start + peer.close() + assert 0.15 <= elapsed < 1.0 + + def test_discards_data_in_flight(self) -> None: + conn, peer = self._connected_pair() + peer.sendall(bytes.fromhex("03 00 00 07 02 f0 80")) + peer.close() + start = time.monotonic() + conn.disconnect() + assert time.monotonic() - start < 0.5 + + def test_socket_is_closed_when_shutdown_fails(self) -> None: + conn = ISOTCPConnection("1.2.3.4") + sock = MagicMock() + sock.shutdown.side_effect = OSError("not connected") + conn.socket = sock + conn.connected = True + conn.disconnect() + sock.close.assert_called_once() + assert conn.socket is None and conn.connected is False + + class TestContextManager: """Test __enter__ / __exit__.""" @@ -397,6 +452,7 @@ def test_enter_returns_self(self) -> None: def test_exit_calls_disconnect(self) -> None: conn = ISOTCPConnection("1.2.3.4") conn.socket = MagicMock() + conn.socket.recv.return_value = b"" conn.connected = True conn.__exit__(None, None, None) assert conn.socket is None diff --git a/tests/test_partner.py b/tests/test_partner.py index 3cfda147..ada03698 100644 --- a/tests/test_partner.py +++ b/tests/test_partner.py @@ -16,6 +16,13 @@ logging.basicConfig(level=logging.WARNING) +@pytest.fixture(autouse=True) +def _short_disconnect_wait(monkeypatch: pytest.MonkeyPatch) -> None: + """Two partners in one process: the one that stays up doesn't close when the other + disconnects, so each stop() would wait out the full DISCONNECT_CLOSE_TIMEOUT.""" + monkeypatch.setattr(ISOTCPConnection, "DISCONNECT_CLOSE_TIMEOUT", 0.05) + + @pytest.mark.partner class TestPartner(unittest.TestCase): def setUp(self) -> None: