From bc492573ff8d0601970ed4ae0184d4f3a8828219 Mon Sep 17 00:00:00 2001 From: Gavin Ying Date: Tue, 10 Nov 2026 15:02:58 +0800 Subject: [PATCH 1/2] feat!: listen on Modbus port 502 by default Default the listener to the standard Modbus port (502 for TCP and UDP, 802 for Modbus/TLS) so modpoll reaches a local simulator without --tcp-port. When the operating system reserves the port, fail before starting and explain how to rerun with sudo or pick a port above 1023. Managed deployments keep their explicit server port. BREAKING CHANGE: modsim without --port now listens on 502 instead of 5020; pass --port 5020 to keep the previous port. Co-Authored-By: Claude Opus 5.5 --- README.md | 7 +++++ docs/site/model-validation.md | 4 +++ modsim/main.py | 32 ++++++++++++++++++++++- modsim/utils.py | 8 +++--- tests/test_modsim.py | 49 +++++++++++++++++++++++++++++++++++ 5 files changed, 95 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 224df1d..ad4e68b 100644 --- a/README.md +++ b/README.md @@ -180,6 +180,13 @@ uv run modsim --config examples/models/products/advantech/adam-5017uh/models/ada --scenario examples/models/products/advantech/adam-5017uh/simulation/adam-5017uh.sim.json ``` +Without `--port`, modsim listens on 502, the standard Modbus TCP port, so +`modpoll --tcp 127.0.0.1` reaches it without `--tcp-port`. Linux, and macOS +when binding to `127.0.0.1`, reserve ports below 1024 for administrators: run +the command with sudo (with uvx, `sudo "$(command -v uvx)" modsim ...`) or pass +`--port 5020` and read it with `modpoll --tcp-port 5020`. modsim prints the same +hint when the port is refused. Windows does not reserve these ports. + The single-device model runtime currently supports TCP. The unconfigured demo also supports TCP, UDP, TLS, RTU and ASCII; its datastore is shared by all Unit IDs. TLS loads `certificates/pymodbus.crt` and `certificates/pymodbus.key` from diff --git a/docs/site/model-validation.md b/docs/site/model-validation.md index 50360fa..c57d175 100644 --- a/docs/site/model-validation.md +++ b/docs/site/model-validation.md @@ -12,6 +12,10 @@ uv run modsim --config examples/models/advantech/adam-5017uh/adam-5017uh.tm.json --scenario examples/models/advantech/adam-5017uh/simulation/adam-5017uh.sim.json ``` +Without `--port`, the listener uses 502, which needs administrator rights on +Linux and on macOS for `127.0.0.1`; modsim then explains how to rerun with sudo +or choose a port above 1023. + `--config` also accepts HTTPS model URLs. GitHub `blob` links are converted to raw file URLs. Prefer a tag or commit SHA for repeatable runs; branch URLs change. Downloads have a 15-second timeout and a 1 MiB limit, and use the shared bounded diff --git a/modsim/main.py b/modsim/main.py index ae011df..37718de 100644 --- a/modsim/main.py +++ b/modsim/main.py @@ -5,6 +5,7 @@ import json import ssl import asyncio +import socket import signal import logging from contextlib import suppress @@ -108,6 +109,28 @@ def setup_server(args: Any) -> Any: return args +def privileged_port_hint(port: Any) -> str: + """Explain how to listen on a port the operating system reserves.""" + return ( + f"Port {port} needs administrator rights on this system. Run the same " + 'command with sudo; with uvx that is sudo "$(command -v uvx)" followed by ' + "the rest of the command. Or listen on a port above 1023, for example " + "--port 5020, and point the client at it (modpoll --tcp-port 5020)." + ) + + +def require_bindable(host: str, port: Any, kind: int = socket.SOCK_STREAM) -> None: + """Fail early with a clear message when binding needs elevated rights.""" + with socket.socket(socket.AF_INET, kind) as probe: + try: + probe.bind((host, int(port))) + except PermissionError as exc: + raise OSError(privileged_port_hint(port)) from exc + except OSError: + # Occupied ports and other failures are reported by the server itself. + return + + async def run_async_server(args: Any) -> Any: """Run server.""" txt = f"Start ASYNC server, listening on {args.port} - {args.comm}" @@ -119,6 +142,7 @@ async def run_async_server(args: Any) -> Any: or ("127.0.0.1" if getattr(args, "runtimes", None) else ""), args.port, ) + require_bindable(address[0], args.port) server = ModbusTcpServer( context=args.context, identity=args.identity, @@ -148,6 +172,7 @@ async def run_async_server(args: Any) -> Any: return server elif args.comm == "udp": address = ("127.0.0.1", args.port) + require_bindable(address[0], args.port, socket.SOCK_DGRAM) server = ModbusUdpServer( context=args.context, identity=args.identity, @@ -173,6 +198,7 @@ async def run_async_server(args: Any) -> Any: return None elif args.comm == "tls": address = ("", args.port) + require_bindable(address[0], args.port) # Create SSL context from cert and key files sslctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) sslctx.load_cert_chain( @@ -217,7 +243,11 @@ def app() -> None: except (ValueError, OSError) as exc: _logger.error("Invalid model configuration: %s", exc) raise SystemExit(2) from exc - asyncio.run(_run_server_with_signals(run_args), debug=True) + try: + asyncio.run(_run_server_with_signals(run_args), debug=True) + except OSError as exc: + _logger.error("%s", exc) + raise SystemExit(2) from exc _logger.info("exiting.") diff --git a/modsim/utils.py b/modsim/utils.py index f6faad5..bed8f9c 100644 --- a/modsim/utils.py +++ b/modsim/utils.py @@ -65,7 +65,7 @@ def get_parser() -> argparse.ArgumentParser: ) parser.add_argument( "--port", - help="set port", + help="set port; defaults to 502 for TCP and UDP and 802 for TLS", type=str, ) parser.add_argument( @@ -129,10 +129,10 @@ def get_commandline() -> argparse.Namespace: # set defaults comm_defaults: Dict[str, list] = { - "tcp": ["socket", 5020], - "udp": ["socket", 5020], + "tcp": ["socket", 502], + "udp": ["socket", 502], "serial": ["rtu", "/dev/ptyp0"], - "tls": ["tls", 5020], + "tls": ["tls", 802], } framers: Dict[str, Any] = { "ascii": FramerType.ASCII, diff --git a/tests/test_modsim.py b/tests/test_modsim.py index d441134..7635fde 100644 --- a/tests/test_modsim.py +++ b/tests/test_modsim.py @@ -1,3 +1,4 @@ +import os import socket import signal import subprocess @@ -412,3 +413,51 @@ def test_local_tls_server_with_ephemeral_certificate(tmp_path): if process.poll() is None: process.kill() process.wait(timeout=5) + + +def test_privileged_port_reports_how_to_run(monkeypatch): + from modsim import main + + def refuse(self, address): + raise PermissionError(13, "Permission denied") + + monkeypatch.setattr(socket.socket, "bind", refuse) + with pytest.raises(OSError) as error: + main.require_bindable("127.0.0.1", 502) + message = str(error.value) + assert "Port 502 needs administrator rights" in message + assert 'sudo "$(command -v uvx)"' in message + assert "--port 5020" in message + + +def test_default_tcp_port_is_502(monkeypatch): + from modsim.utils import get_commandline + + monkeypatch.setattr(sys, "argv", ["modsim"]) + assert get_commandline().port == 502 + + +def _unprivileged_low_ports(): + try: + with open("/proc/sys/net/ipv4/ip_unprivileged_port_start") as handle: + return int(handle.read()) <= 502 + except OSError: + return True + + +@pytest.mark.integration +@pytest.mark.skipif( + not sys.platform.startswith("linux") + or os.geteuid() == 0 + or _unprivileged_low_ports(), + reason="needs a non-root Linux user without access to port 502", +) +def test_default_port_without_rights_fails_with_hint(): + result = subprocess.run( + [sys.executable, "-m", "modsim", "--log", "error"], + capture_output=True, + text=True, + timeout=5, + ) + assert result.returncode == 2 + assert "Port 502 needs administrator rights" in result.stderr From 532c0fe88de41be3528dafa0b2101830fed3dea8 Mon Sep 17 00:00:00 2001 From: Gavin Ying Date: Tue, 10 Nov 2026 16:05:38 +0800 Subject: [PATCH 2/2] chore: prepare 2.0.0a5 Co-Authored-By: Claude Opus 5.5 --- docs/preview-notes.md | 21 +++++++++++++++++++-- modsim/__init__.py | 2 +- pyproject.toml | 2 +- uv.lock | 2 +- 4 files changed, 22 insertions(+), 5 deletions(-) diff --git a/docs/preview-notes.md b/docs/preview-notes.md index c556d68..d81abca 100644 --- a/docs/preview-notes.md +++ b/docs/preview-notes.md @@ -1,4 +1,22 @@ -# Modsim 2.0.0a4 preview +# Modsim 2.0.0a5 preview + +Without `--port`, modsim now listens on the standard Modbus port: 502 for TCP +and UDP, 802 for Modbus/TLS. A simulator started from a ModioHub Thing Model is +then read with `modpoll --tcp 127.0.0.1`, without `--tcp-port`: + +```sh +uvx --prerelease allow modsim==2.0.0a5 --config https://example.org/device.tm.json +``` + +Linux, and macOS when binding to `127.0.0.1`, reserve ports below 1024 for +administrators. modsim then exits before starting and explains how to rerun it +with sudo (`sudo "$(command -v uvx)" modsim ...`) or choose a port above 1023, +for example `--port 5020`. Managed deployments keep their explicit server port. +This preview still pins modpoll-wot 0.2.0a4. + +### Previous preview + +#### Modsim 2.0.0a4 Remote models and scenarios load directly from a site such as ModioHub: @@ -11,7 +29,6 @@ HTTPS requests identify themselves as `modsim/`, because some CDNs reje the default Python agent. `--scenario` accepts an HTTPS URL; a remote scenario cannot name a behavior script. This preview still pins modpoll-wot 0.2.0a4. -### Previous preview #### Modsim 2.0.0a3 diff --git a/modsim/__init__.py b/modsim/__init__.py index 981a129..dbfe9c5 100644 --- a/modsim/__init__.py +++ b/modsim/__init__.py @@ -1 +1 @@ -__version__ = "2.0.0a4" +__version__ = "2.0.0a5" diff --git a/pyproject.toml b/pyproject.toml index cf2c945..71ca43b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "modsim" -version = "2.0.0a4" +version = "2.0.0a5" description = "A Simple Modbus TCP Device Simulator used for modpoll tool" authors = [{ name = "Ying Shaodong", email = "helloysd@gmail.com" }] readme = "README.md" diff --git a/uv.lock b/uv.lock index cd769f6..16e6ef1 100644 --- a/uv.lock +++ b/uv.lock @@ -843,7 +843,7 @@ wheels = [ [[package]] name = "modsim" -version = "2.0.0a4" +version = "2.0.0a5" source = { editable = "." } dependencies = [ { name = "jsonschema", marker = "python_full_version < '3.15'" },