Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions API_changes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ Versions (X.Y.Z) where Z == 0 e.g. 3.0.1 do NOT have API changes!
API changes 3.17.0
------------------
- the sync client converts automatically to async, this is not a API change, but it is a major change.
- ModbusTcpServer / ModbusTlsServer / ModbusUdpServer, new parameter max_connections=10 (0 = no limit).

API changes 3.16.0
------------------
Expand Down
7 changes: 7 additions & 0 deletions pymodbus/server/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@
from .requesthandler import ServerRequestHandler


MAX_CONNECTIONS = 1000


class ModbusBaseServer(ModbusProtocol):
"""Common functionality for all server classes."""

Expand All @@ -37,6 +40,10 @@ def __init__(
custom_pdu: list[type[ModbusPDU]] | None,
) -> None:
"""Initialize base server."""
if not 0 <= params.max_connections <= MAX_CONNECTIONS:
raise ParameterException(
f"max_connections= must be between 0 and {MAX_CONNECTIONS}."
)
super().__init__(
params,
True,
Expand Down
9 changes: 9 additions & 0 deletions pymodbus/server/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ def __init__(
trace_pdu: Callable[[bool, ModbusPDU], ModbusPDU] | None = None,
trace_connect: Callable[[bool], None] | None = None,
custom_pdu: list[type[ModbusPDU]] | None = None,
max_connections: int = 10,
):
"""Initialize the socket server.

Expand All @@ -50,6 +51,7 @@ def __init__(
:param trace_pdu: Called with PDU received/to be sent
:param trace_connect: Called when connected/disconnected
:param custom_pdu: list of ModbusPDU custom classes
:param max_connections: Maximum number of connections (0 = no limit)
"""
params = getattr(
self,
Expand All @@ -63,6 +65,7 @@ def __init__(
),
)
params.source_address = address
params.max_connections = max_connections
super().__init__(
params,
context,
Expand Down Expand Up @@ -98,6 +101,7 @@ def __init__(
trace_pdu: Callable[[bool, ModbusPDU], ModbusPDU] | None = None,
trace_connect: Callable[[bool], None] | None = None,
custom_pdu: list[type[ModbusPDU]] | None = None,
max_connections: int = 10,
):
"""Overloaded initializer for the socket server.

Expand All @@ -116,6 +120,7 @@ def __init__(
:param trace_pdu: Called with PDU received/to be sent
:param trace_connect: Called when connected/disconnected
:param custom_pdu: list of ModbusPDU custom classes
:param max_connections: Maximum number of connections (0 = no limit)
"""
if not sslctx:
raise TypeError(
Expand All @@ -140,6 +145,7 @@ def __init__(
trace_pdu=trace_pdu,
trace_connect=trace_connect,
custom_pdu=custom_pdu,
max_connections=max_connections,
)


Expand All @@ -163,6 +169,7 @@ def __init__(
trace_pdu: Callable[[bool, ModbusPDU], ModbusPDU] | None = None,
trace_connect: Callable[[bool], None] | None = None,
custom_pdu: list[type[ModbusPDU]] | None = None,
max_connections: int = 10,
):
"""Overloaded initializer for the socket server.

Expand All @@ -180,6 +187,7 @@ def __init__(
:param trace_pdu: Called with PDU received/to be sent
:param trace_connect: Called when connected/disconnected
:param custom_pdu: list of ModbusPDU custom classes
:param max_connections: Maximum number of connections (0 = no limit)
"""
# ----------------
params = CommParams(
Expand All @@ -189,6 +197,7 @@ def __init__(
reconnect_delay=0.0,
reconnect_delay_max=0.0,
timeout_connect=0.0,
max_connections=max_connections,
)
super().__init__(
params,
Expand Down
41 changes: 39 additions & 2 deletions pymodbus/transport/transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,11 +100,26 @@ class CommParams:
stopbits: int = -1
handle_local_echo: bool = False

# server
max_connections: int = 0

def copy(self: CommParams) -> CommParams:
"""Create a copy."""
return copy.copy(self)


class RefusedConnection(asyncio.Protocol):
"""Close a connection the listener does not accept.

asyncio cannot refuse a connection: if handle_new_connection()
returns None, the tcp socket stays open and the client hangs.
"""

def connection_made(self, transport: asyncio.BaseTransport) -> None:
"""Call from asyncio, when a connection is made."""
transport.abort() # type: ignore[attr-defined]


class ModbusProtocol(asyncio.BaseProtocol):
"""Protocol layer including transport."""

Expand Down Expand Up @@ -254,6 +269,14 @@ def connection_made(self, transport: asyncio.BaseTransport) -> None:
:param transport: socket etc. representing the connection.
"""
Log.debug("Connected to {}", self.comm_params.comm_name)
if self.listener:
if self.listener.is_closing or self.listener.is_full():
# Accepted at the same time as the connection that filled the listener.
self.listener = None
self.is_closing = True
transport.abort() # type: ignore[attr-defined]
return
self.listener.active_connections[self.unique_id] = self
self.transport = transport
self.reset_delay()
self.callback_connected()
Expand All @@ -280,6 +303,9 @@ def data_received(self, data: bytes) -> None:

:param data: non-empty bytes object with incoming data.
"""
if self.is_closing:
# asyncio (Python 3.10, TLS) delivers data even after abort().
return
self.datagram_received(data, None)

def datagram_received(self, data: bytes, addr: tuple | None) -> None:
Expand Down Expand Up @@ -386,7 +412,7 @@ def __close(self, reconnect: bool = False) -> None:
self.reconnect_task = None
self.reconnect_delay_current = 0.0
if self.listener:
self.listener.active_connections.pop(self.unique_id)
self.listener.active_connections.pop(self.unique_id, None)

def close(self, reconnect: bool = False) -> None:
"""Close connection (external).
Expand Down Expand Up @@ -421,14 +447,25 @@ async def create_nullmodem(
# connect object
return NullModem.set_connection(port, self)

def is_full(self) -> bool:
"""Return true if listener has max_connections connections."""
return 0 < self.comm_params.max_connections <= len(self.active_connections)

def handle_new_connection(self) -> ModbusProtocol:
"""Handle incoming connect."""
if not self.is_server:
# Clients reuse the same object.
return self

if self.is_full():
Log.warning(
"Connection refused, already {} connections",
self.comm_params.max_connections,
)
return RefusedConnection() # type: ignore[return-value]
# The connection is registered in connection_made(), because asyncio
# never reports a connection that fails before that (e.g. TLS handshake).
Comment thread
janiversen marked this conversation as resolved.
Resolved
new_protocol = self.callback_new_connection()
self.active_connections[new_protocol.unique_id] = new_protocol
new_protocol.listener = self
return new_protocol

Expand Down
104 changes: 102 additions & 2 deletions test/server/test_server_asyncio.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

from examples.helper import generate_ssl, get_certificate
from pymodbus import FramerType, ModbusDeviceIdentification
from pymodbus.exceptions import NoSuchIdException
from pymodbus.exceptions import NoSuchIdException, ParameterException
from pymodbus.server import (
ModbusBaseServer,
ModbusSerialServer,
Expand Down Expand Up @@ -149,6 +149,7 @@ async def start_server(
do_udp=False,
do_ident=False,
serv_addr=SERV_ADDR,
**kwargs,
):
"""Handle setup and control of tcp server."""
args: dict[str, Any] = {
Expand All @@ -164,17 +165,19 @@ async def start_server(
identity=self.identity,
address=serv_addr,
sslctx=generate_ssl(
False,
True,
certfile=get_certificate("crt"),
keyfile=get_certificate("key"),
),
**kwargs,
)
elif do_udp:
self.server = ModbusUdpServer(
self.context,
framer=FramerType.SOCKET,
identity=self.identity,
address=serv_addr,
**kwargs,
)
elif do_serial:
self.server = ModbusSerialServer(
Expand All @@ -190,6 +193,7 @@ async def start_server(
framer=FramerType.SOCKET,
identity=self.identity,
address=serv_addr,
**kwargs,
)
assert self.server
if do_forever:
Expand Down Expand Up @@ -336,6 +340,102 @@ async def test_async_tcp_server_modbus_error(self):
await self.connect_server()
await asyncio.wait_for(BasicClient.done, timeout=0.1)

async def open_clients(self, count, do_tls=False):
"""Open a number of client connections simultaneously."""
sslctx = None
if do_tls:
sslctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
sslctx.check_hostname = False
sslctx.verify_mode = ssl.CERT_NONE
port = self.server.transport.sockets[0].getsockname()[1] # type: ignore[union-attr, attr-defined]
clients = await asyncio.gather(
*[asyncio.open_connection(SERV_IP, port, ssl=sslctx) for _ in range(count)]
)
await asyncio.sleep(0.2)
return clients

@pytest.mark.parametrize("do_tls", [False, True])
async def test_async_server_max_connections(self, do_tls):
"""Test connections above max_connections are refused."""
response = b"\x01\x00\x00\x00\x00\x05\x01\x03\x02\x00\x11"
events = []
await self.start_server(
do_tls=do_tls, max_connections=2, trace_connect=events.append
)
assert self.server
clients = await self.open_clients(2, do_tls=do_tls)
assert len(self.server.active_connections) == 2

for reader, writer in await self.open_clients(3, do_tls=do_tls):
with suppress(OSError):
assert not await asyncio.wait_for(reader.read(), timeout=1)
writer.close()
assert len(self.server.active_connections) == 2
assert events == [True, True]

reader, writer = clients[0]
writer.write(TEST_DATA)
assert await asyncio.wait_for(reader.read(11), timeout=1) == response
writer.close()
await asyncio.sleep(0.2)
assert len(self.server.active_connections) == 1
clients[0] = (await self.open_clients(1, do_tls=do_tls))[0]
assert len(self.server.active_connections) == 2
for _, writer in clients:
writer.close()

@pytest.mark.parametrize(("limit", "active"), [(5, 5), (0, 20)])
async def test_async_server_max_connections_burst(self, limit, active):
"""Test connections opened at the same time, 0 means no limit."""
await self.start_server(max_connections=limit)
assert self.server
clients = await self.open_clients(20)
assert len(self.server.active_connections) == active
for _, writer in clients:
writer.close()
await asyncio.sleep(0.2)
assert not self.server.active_connections

async def test_async_tls_server_failed_handshake(self):
"""Test failed TLS handshakes do not use up max_connections."""
await self.start_server(do_tls=True, max_connections=2)
assert self.server
for reader, writer in await self.open_clients(5):
writer.write(b"this is not a TLS handshake")
with suppress(OSError):
await asyncio.wait_for(reader.read(), timeout=1)
writer.close()
await asyncio.sleep(0.2)
assert not self.server.active_connections
clients = await self.open_clients(2, do_tls=True)
assert len(self.server.active_connections) == 2
for _, writer in clients:
writer.close()

@pytest.mark.parametrize(
("args", "limit"),
[
({}, 10),
({"do_tls": True}, 10),
({"do_udp": True}, 10),
({"max_connections": 0}, 0),
({"do_tls": True, "max_connections": 1000}, 1000),
({"do_udp": True, "max_connections": 3}, 3),
],
)
async def test_async_server_max_connections_param(self, args, limit):
"""Test the connection limit reaches the transport."""
await self.start_server(do_forever=False, **args)
assert self.server
assert self.server.comm_params.max_connections == limit

@pytest.mark.parametrize("args", [{}, {"do_tls": True}, {"do_udp": True}])
@pytest.mark.parametrize("limit", [-1, 1001, 999999])
async def test_async_server_illegal_max_connections(self, args, limit):
"""Test the connection limit is checked."""
with pytest.raises(ParameterException):
await self.start_server(do_forever=False, max_connections=limit, **args)

# -----------------------------------------------------------------------#
# Test ModbusTlsProtocol
# -----------------------------------------------------------------------#
Expand Down
48 changes: 48 additions & 0 deletions test/transport/test_protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from pymodbus.transport import (
CommType,
)
from pymodbus.transport.transport import RefusedConnection


COMM_TYPES = [
Expand Down Expand Up @@ -311,6 +312,53 @@ async def test_create_nullmodem(self, client, server):
client.close()
server.close()

async def test_connection_registered(self, server, dummy_protocol):
"""Test a connection is registered when it is established."""
protocol = server.handle_new_connection()
assert not server.active_connections
protocol.connection_made(dummy_protocol())
assert server.active_connections == {protocol.unique_id: protocol}

async def test_connection_closed_before_established(self, server):
"""Test a connection can be closed before it is registered."""
server.handle_new_connection().close()
assert not server.active_connections

async def test_handle_new_connection_full(self, server, dummy_protocol):
"""Test a full listener refuses the connection, and closes it."""
server.comm_params.max_connections = 1
server.handle_new_connection().connection_made(dummy_protocol())
assert server.is_full()
refused = server.handle_new_connection()
assert isinstance(refused, RefusedConnection)
transport = mock.Mock()
refused.connection_made(transport)
transport.abort.assert_called_once()
assert len(server.active_connections) == 1

@pytest.mark.parametrize("closing", [False, True])
async def test_connection_refused_late(self, server, closing, dummy_protocol):
"""Test a connection that is too late is aborted and never delivers data."""
server.comm_params.max_connections = 1
protocol = server.handle_new_connection()
protocol.callback_connected = mock.Mock()
protocol.callback_data = mock.Mock(return_value=0)
protocol.callback_disconnected = mock.Mock()
if closing:
server.is_closing = True
else:
server.handle_new_connection().connection_made(dummy_protocol())
active = dict(server.active_connections)
transport = mock.Mock()
protocol.connection_made(transport)
transport.abort.assert_called_once()
protocol.data_received(b"abc")
protocol.connection_lost(None)
assert server.active_connections == active
protocol.callback_connected.assert_not_called()
protocol.callback_data.assert_not_called()
protocol.callback_disconnected.assert_not_called()

async def test_handle_new_connection(self, client, server):
"""Test handle_new_connection()."""
server.handle_new_connection()
Expand Down
Loading