From 76a336af02e4494418d603e9f7ba26579bdf68b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20M=C3=BCller?= <1005065+DeepDiver1975@users.noreply.github.com> Date: Mon, 26 Oct 2026 22:41:09 +0100 Subject: [PATCH 1/2] build: fake DL500A on a pseudo-terminal for testing without the phone MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit tools/fake-dl500a.py answers AT and ATD like the DL500A, with scenarios for every result code and a silent one for the Hands-Free trap, and logs each line it receives so hostile tel: links can be checked on the wire. A pty has no modem lines, so SerialPort's DtrEnable fails with ENOTTY; tools/pty-modem-lines.c is an LD_PRELOAD shim that lets those ioctls pass on devices that reject them. `make fake-phone` and `make run-fake` wire it up. Nothing under src/ changes. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Thomas Müller <1005065+DeepDiver1975@users.noreply.github.com> --- Makefile | 17 +++++- README.md | 16 ++++++ tools/fake-dl500a.py | 118 ++++++++++++++++++++++++++++++++++++++++ tools/pty-modem-lines.c | 43 +++++++++++++++ 4 files changed, 192 insertions(+), 2 deletions(-) create mode 100755 tools/fake-dl500a.py create mode 100644 tools/pty-modem-lines.c diff --git a/Makefile b/Makefile index c63452f..c2745f9 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,10 @@ SLN := Freizeichen.slnx APP := src/Freizeichen.App/Freizeichen.App.csproj +SHIM := tools/obj/pty-modem-lines.so +SCENARIO ?= ok +PHONE_PORT ?= /dev/rfcomm9 -.PHONY: help restore build test ci format format-check run clean +.PHONY: help restore build test ci format format-check run fake-phone run-fake clean help: ## Show this help @grep -E '^[a-zA-Z_-]+:.*?## ' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " %-14s %s\n", $$1, $$2}' @@ -29,5 +32,15 @@ format-check: ## Fail if dotnet format would change anything run: ## Run the app (ARGS=tel:0891234567 to open the dial window) dotnet run --project $(APP) -- $(ARGS) +fake-phone: ## Play a DL500A on /dev/rfcomm9 (SCENARIO=ok|error|busy|nocarrier|nodialtone|silent; Linux) + python3 tools/fake-dl500a.py --link $(PHONE_PORT) --scenario $(SCENARIO) + +run-fake: $(SHIM) ## Run the app so it can open the fake phone's pseudo-terminal (Linux) + LD_PRELOAD=$(CURDIR)/$(SHIM) dotnet run --project $(APP) -- $(ARGS) + +$(SHIM): tools/pty-modem-lines.c + mkdir -p $(@D) + cc -Wall -Wextra -shared -fPIC -o $@ $< -ldl + clean: ## Remove build output - find src tests -type d \( -name bin -o -name obj \) -prune -exec rm -rf {} + + find src tests tools -type d \( -name bin -o -name obj \) -prune -exec rm -rf {} + diff --git a/README.md b/README.md index 9cb0128..77178fa 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,22 @@ auf; das Gespräch wird am Telefon geführt. Das DL500A stellt über Bluetooth eine serielle Schnittstelle (SPP) bereit und versteht dort AT-Befehle. Freizeichen öffnet diese Schnittstelle, sendet `ATD ` und schließt sie wieder. +## Ohne Telefon testen + +Unter Linux spielt `tools/fake-dl500a.py` ein DL500A auf einem Pseudo-Terminal und zeigt jede +Zeile, die Freizeichen sendet: + +```sh +make fake-phone # legt /dev/rfcomm9 an (fragt per sudo), SCENARIO=ok +make run-fake # Einstellungen: /dev/rfcomm9 wählen, „Testen“ +make run-fake ARGS=tel:0891234567 # Wählfenster +``` + +`SCENARIO` steuert die Antwort auf `ATD`: `ok`, `error`, `busy`, `nocarrier`, `nodialtone` oder +`silent` – Letzteres antwortet gar nicht, wie das DL500A bei bestehender Audioverbindung. +`make run-fake` startet Freizeichen mit `tools/pty-modem-lines.c`, weil ein Pseudo-Terminal keine +DTR/RTS-Leitungen hat und der Port sonst nicht aufgeht. + ## Status In Entwicklung. Hintergrund: CodeForFire/lagebuch#617. diff --git a/tools/fake-dl500a.py b/tools/fake-dl500a.py new file mode 100755 index 0000000..d1cf8bb --- /dev/null +++ b/tools/fake-dl500a.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python3 +"""A fake Gigaset DL500A on a pseudo-terminal, for trying Freizeichen without the phone. + +It answers the AT commands Freizeichen sends the way the DL500A does over Bluetooth SPP, and +prints every line it receives, so you can see exactly what a tel: link put on the wire. + + python3 tools/fake-dl500a.py # prints the port to choose in Freizeichen + python3 tools/fake-dl500a.py --link /dev/rfcomm9 --scenario silent + +--link makes the port appear in Freizeichen's port list (Linux lists /dev/rfcomm*, macOS +/dev/cu.*). Linking into /dev needs root, so the script calls sudo for that step alone. +Linux only so far; run Freizeichen with `make run-fake` so it can open the pty. +""" + +import argparse +import os +import re +import subprocess +import sys +import tty + +# What the phone answers to ATD, per scenario. "silent" answers nothing at all, not even AT: that +# is what the DL500A does while the PC also holds its Hands-Free audio connection. +DIAL_ANSWERS = { + "ok": ["OK", "CLIP:EXTERN", "CONNECT"], + "error": ["ERROR"], + "busy": ["BUSY"], + "nocarrier": ["NO CARRIER"], + "nodialtone": ["NO DIALTONE"], + "silent": [], +} + + +def answer(command, scenario): + if scenario == "silent": + return [] + if command == "AT": + return ["OK"] + if command == "AT+CGMI": + return ["Gigaset Communications GmbH", "OK"] + if command.startswith("ATD"): + return DIAL_ANSWERS[scenario] + return ["ERROR"] + + +def check(command): + # Anything after ATD other than digits is what TelUri must never let through. + if command.startswith("ATD") and not re.fullmatch(r"ATD \d+", command): + print(f"!!! not just digits after ATD: {command!r}", flush=True) + elif not command.startswith("AT"): + print(f"!!! not an AT command: {command!r}", flush=True) + + +def link(target, name): + try: + if os.path.lexists(name): + os.remove(name) + os.symlink(target, name) + except PermissionError: + subprocess.run(["sudo", "ln", "-sfn", target, name], check=True) + + +def unlink(name): + try: + os.remove(name) + except PermissionError: + subprocess.run(["sudo", "rm", "-f", name], check=False) + except FileNotFoundError: + pass + + +def serve(master, scenario): + pending = b"" + while True: + try: + chunk = os.read(master, 1024) + except OSError: + # Every slave fd closed; cannot happen while we hold ours, but end cleanly if it does. + return + pending += chunk + *lines, pending = re.split(rb"\r\n|\r|\n", pending) + for raw in lines: + if not raw: + continue + command = raw.decode("ascii", errors="backslashreplace") + print(f"<- {command!r}", flush=True) + check(command) + for reply in answer(command.strip(), scenario): + print(f"-> {reply}", flush=True) + os.write(master, f"\r\n{reply}\r\n".encode("ascii")) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--scenario", choices=DIAL_ANSWERS, default="ok", help="how the phone answers ATD (default: ok)") + parser.add_argument("--link", metavar="PATH", help="also expose the port under this name, e.g. /dev/rfcomm9") + args = parser.parse_args() + + master, slave = os.openpty() + # Holding the slave open keeps the pty alive between dials, and raw mode stops it echoing. + tty.setraw(slave) + port = os.ttyname(slave) + if args.link: + link(port, args.link) + port = args.link + + print(f"Fake DL500A ({args.scenario}) on {port} – choose it in Freizeichen. Ctrl+C ends.", flush=True) + try: + serve(master, args.scenario) + except KeyboardInterrupt: + pass + finally: + if args.link: + unlink(args.link) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/pty-modem-lines.c b/tools/pty-modem-lines.c new file mode 100644 index 0000000..be11dd3 --- /dev/null +++ b/tools/pty-modem-lines.c @@ -0,0 +1,43 @@ +// LD_PRELOAD shim for trying Freizeichen against tools/fake-dl500a.py on Linux. +// +// A pseudo-terminal has no modem control lines, so the TIOCM* ioctls fail with ENOTTY and +// .NET's SerialPort refuses to open it with DtrEnable/RtsEnable set. This shim lets exactly those +// calls succeed when the device rejects them, and reports carrier, DSR and CTS as up. Every other +// ioctl, and every TIOCM* call on a real serial port, goes through unchanged. +// +// gcc -shared -fPIC -o pty-modem-lines.so pty-modem-lines.c -ldl +// LD_PRELOAD=$PWD/pty-modem-lines.so dotnet run --project src/Freizeichen.App + +#define _GNU_SOURCE +#include +#include +#include +#include + +int ioctl(int fd, unsigned long request, ...) +{ + static int (*real_ioctl)(int, unsigned long, ...); + if (!real_ioctl) + real_ioctl = (int (*)(int, unsigned long, ...))dlsym(RTLD_NEXT, "ioctl"); + + va_list args; + va_start(args, request); + void *arg = va_arg(args, void *); + va_end(args); + + int result = real_ioctl(fd, request, arg); + if (result == 0 || (errno != ENOTTY && errno != EINVAL)) + return result; + + switch (request) { + case TIOCMGET: + *(int *)arg = TIOCM_CAR | TIOCM_DSR | TIOCM_CTS | TIOCM_DTR | TIOCM_RTS; + return 0; + case TIOCMSET: + case TIOCMBIS: + case TIOCMBIC: + return 0; + default: + return result; + } +} From 2d69e63a1928ed2e1de7664dde89e010123d98e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20M=C3=BCller?= <1005065+DeepDiver1975@users.noreply.github.com> Date: Mon, 26 Oct 2026 23:20:17 +0100 Subject: [PATCH 2/2] fix(modem): open serial ports that have no modem control lines MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SerialPorts set DtrEnable and RtsEnable before Open, so a device without DTR/RTS (a pseudo-terminal) failed Open with "Inappropriate ioctl for device". That IOException was classified Unreachable and shown as the Hands-Free hint, although the phone was never asked anything. Raise DTR and RTS after Open and carry on if the device refuses them. The fake phone in tools/ now works with a plain `make run`, so the LD_PRELOAD shim and `make run-fake` go. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Thomas Müller <1005065+DeepDiver1975@users.noreply.github.com> --- Makefile | 12 +--- README.md | 6 +- src/Freizeichen.Modem/SerialPorts.cs | 19 +++++- .../Freizeichen.Modem.Tests.csproj | 2 + .../Freizeichen.Modem.Tests/PseudoTerminal.cs | 63 +++++++++++++++++++ .../SerialPortsTests.cs | 15 +++++ tools/fake-dl500a.py | 2 +- tools/pty-modem-lines.c | 43 ------------- 8 files changed, 102 insertions(+), 60 deletions(-) create mode 100644 tests/Freizeichen.Modem.Tests/PseudoTerminal.cs delete mode 100644 tools/pty-modem-lines.c diff --git a/Makefile b/Makefile index c2745f9..90da49c 100644 --- a/Makefile +++ b/Makefile @@ -1,10 +1,9 @@ SLN := Freizeichen.slnx APP := src/Freizeichen.App/Freizeichen.App.csproj -SHIM := tools/obj/pty-modem-lines.so SCENARIO ?= ok PHONE_PORT ?= /dev/rfcomm9 -.PHONY: help restore build test ci format format-check run fake-phone run-fake clean +.PHONY: help restore build test ci format format-check run fake-phone clean help: ## Show this help @grep -E '^[a-zA-Z_-]+:.*?## ' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " %-14s %s\n", $$1, $$2}' @@ -35,12 +34,5 @@ run: ## Run the app (ARGS=tel:0891234567 to open the dial window) fake-phone: ## Play a DL500A on /dev/rfcomm9 (SCENARIO=ok|error|busy|nocarrier|nodialtone|silent; Linux) python3 tools/fake-dl500a.py --link $(PHONE_PORT) --scenario $(SCENARIO) -run-fake: $(SHIM) ## Run the app so it can open the fake phone's pseudo-terminal (Linux) - LD_PRELOAD=$(CURDIR)/$(SHIM) dotnet run --project $(APP) -- $(ARGS) - -$(SHIM): tools/pty-modem-lines.c - mkdir -p $(@D) - cc -Wall -Wextra -shared -fPIC -o $@ $< -ldl - clean: ## Remove build output - find src tests tools -type d \( -name bin -o -name obj \) -prune -exec rm -rf {} + + find src tests -type d \( -name bin -o -name obj \) -prune -exec rm -rf {} + diff --git a/README.md b/README.md index 77178fa..a8c9033 100644 --- a/README.md +++ b/README.md @@ -20,14 +20,12 @@ Zeile, die Freizeichen sendet: ```sh make fake-phone # legt /dev/rfcomm9 an (fragt per sudo), SCENARIO=ok -make run-fake # Einstellungen: /dev/rfcomm9 wählen, „Testen“ -make run-fake ARGS=tel:0891234567 # Wählfenster +make run # Einstellungen: /dev/rfcomm9 wählen, „Verbindung testen“ +make run ARGS=tel:0891234567 # Wählfenster ``` `SCENARIO` steuert die Antwort auf `ATD`: `ok`, `error`, `busy`, `nocarrier`, `nodialtone` oder `silent` – Letzteres antwortet gar nicht, wie das DL500A bei bestehender Audioverbindung. -`make run-fake` startet Freizeichen mit `tools/pty-modem-lines.c`, weil ein Pseudo-Terminal keine -DTR/RTS-Leitungen hat und der Port sonst nicht aufgeht. ## Status diff --git a/src/Freizeichen.Modem/SerialPorts.cs b/src/Freizeichen.Modem/SerialPorts.cs index 9d4900b..2908aae 100644 --- a/src/Freizeichen.Modem/SerialPorts.cs +++ b/src/Freizeichen.Modem/SerialPorts.cs @@ -61,8 +61,6 @@ public async Task OpenAsync(string portName, CancellationToken cance ArgumentException.ThrowIfNullOrWhiteSpace(portName); var port = new SerialPort(portName, BaudRate) { - DtrEnable = true, - RtsEnable = true, WriteTimeout = (int)AtDialer.ConnectTimeout.TotalMilliseconds, }; @@ -84,9 +82,26 @@ public async Task OpenAsync(string portName, CancellationToken cance throw new PortUnavailableException(portName, failure, e); } + RaiseModemLines(port); return new StreamAtChannel(port.BaseStream, port); } + // DTR and RTS are raised once the port is open, and only where the device has them: a + // pseudo-terminal, such as the one tools/fake-dl500a.py plays the phone on, has no modem + // control lines, and asking for them before Open made Open itself fail. + private static void RaiseModemLines(SerialPort port) + { + try + { + port.DtrEnable = true; + port.RtsEnable = true; + } + catch (IOException) + { + // No modem control lines on this device: talk without them. + } + } + private static int TrailingNumber(string name) { var digits = name[name.TrimEnd("0123456789".ToCharArray()).Length..]; diff --git a/tests/Freizeichen.Modem.Tests/Freizeichen.Modem.Tests.csproj b/tests/Freizeichen.Modem.Tests/Freizeichen.Modem.Tests.csproj index 6afe610..d63e72a 100644 --- a/tests/Freizeichen.Modem.Tests/Freizeichen.Modem.Tests.csproj +++ b/tests/Freizeichen.Modem.Tests/Freizeichen.Modem.Tests.csproj @@ -3,6 +3,8 @@ false true + + true diff --git a/tests/Freizeichen.Modem.Tests/PseudoTerminal.cs b/tests/Freizeichen.Modem.Tests/PseudoTerminal.cs new file mode 100644 index 0000000..e4001a5 --- /dev/null +++ b/tests/Freizeichen.Modem.Tests/PseudoTerminal.cs @@ -0,0 +1,63 @@ +using System.Runtime.InteropServices; +using System.Text; +using Microsoft.Win32.SafeHandles; + +namespace Freizeichen.Modem.Tests; + +/// +/// A Unix pseudo-terminal: a serial device with no modem control lines, like the one +/// tools/fake-dl500a.py plays the phone on. is the far end. +/// +internal sealed partial class PseudoTerminal : IDisposable +{ + private const int ReadWrite = 2; + + private PseudoTerminal(FileStream phone, string port) + { + Phone = phone; + Port = port; + } + + /// The device a program opens, as it would open /dev/rfcomm0. + public string Port { get; } + + public FileStream Phone { get; } + + public static PseudoTerminal Open() + { + var fd = PosixOpenpt(ReadWrite | NoControllingTerminal()); + if (fd < 0 || Grantpt(fd) != 0 || Unlockpt(fd) != 0) + { + throw new IOException($"No pseudo-terminal: errno {Marshal.GetLastPInvokeError()}."); + } + + var name = new byte[128]; + if (PtsnameR(fd, name, name.Length) != 0) + { + throw new IOException($"No pseudo-terminal name: errno {Marshal.GetLastPInvokeError()}."); + } + + var phone = new FileStream(new SafeFileHandle(fd, ownsHandle: true), FileAccess.ReadWrite, bufferSize: 0); + return new PseudoTerminal(phone, Encoding.ASCII.GetString(name, 0, Array.IndexOf(name, (byte)0))); + } + + public void Dispose() => Phone.Dispose(); + + private static int NoControllingTerminal() => OperatingSystem.IsMacOS() ? 0x20000 : 0x100; + + [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)] + [LibraryImport("libc", EntryPoint = "posix_openpt", SetLastError = true)] + private static partial int PosixOpenpt(int flags); + + [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)] + [LibraryImport("libc", EntryPoint = "grantpt", SetLastError = true)] + private static partial int Grantpt(int fd); + + [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)] + [LibraryImport("libc", EntryPoint = "unlockpt", SetLastError = true)] + private static partial int Unlockpt(int fd); + + [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)] + [LibraryImport("libc", EntryPoint = "ptsname_r", SetLastError = true)] + private static partial int PtsnameR(int fd, [Out] byte[] buffer, nint length); +} diff --git a/tests/Freizeichen.Modem.Tests/SerialPortsTests.cs b/tests/Freizeichen.Modem.Tests/SerialPortsTests.cs index b48ddcc..04c66fa 100644 --- a/tests/Freizeichen.Modem.Tests/SerialPortsTests.cs +++ b/tests/Freizeichen.Modem.Tests/SerialPortsTests.cs @@ -1,3 +1,5 @@ +using System.Text; + namespace Freizeichen.Modem.Tests; public sealed class SerialPortsTests @@ -46,4 +48,17 @@ public void Leaves_unrelated_exceptions_alone() { Assert.Null(SerialPorts.Classify(new InvalidOperationException())); } + + [Fact] + public async Task Talks_to_a_port_without_modem_control_lines() + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "Pseudo-terminals are Unix only."); + var cancellationToken = TestContext.Current.CancellationToken; + using var terminal = PseudoTerminal.Open(); + + await using var channel = await new SerialPorts().OpenAsync(terminal.Port, cancellationToken); + await terminal.Phone.WriteAsync(Encoding.ASCII.GetBytes("OK\r\n"), cancellationToken); + + Assert.Equal("OK", await channel.ReadLineAsync(cancellationToken)); + } } diff --git a/tools/fake-dl500a.py b/tools/fake-dl500a.py index d1cf8bb..6c9142a 100755 --- a/tools/fake-dl500a.py +++ b/tools/fake-dl500a.py @@ -9,7 +9,7 @@ --link makes the port appear in Freizeichen's port list (Linux lists /dev/rfcomm*, macOS /dev/cu.*). Linking into /dev needs root, so the script calls sudo for that step alone. -Linux only so far; run Freizeichen with `make run-fake` so it can open the pty. +Tried on Linux only. """ import argparse diff --git a/tools/pty-modem-lines.c b/tools/pty-modem-lines.c deleted file mode 100644 index be11dd3..0000000 --- a/tools/pty-modem-lines.c +++ /dev/null @@ -1,43 +0,0 @@ -// LD_PRELOAD shim for trying Freizeichen against tools/fake-dl500a.py on Linux. -// -// A pseudo-terminal has no modem control lines, so the TIOCM* ioctls fail with ENOTTY and -// .NET's SerialPort refuses to open it with DtrEnable/RtsEnable set. This shim lets exactly those -// calls succeed when the device rejects them, and reports carrier, DSR and CTS as up. Every other -// ioctl, and every TIOCM* call on a real serial port, goes through unchanged. -// -// gcc -shared -fPIC -o pty-modem-lines.so pty-modem-lines.c -ldl -// LD_PRELOAD=$PWD/pty-modem-lines.so dotnet run --project src/Freizeichen.App - -#define _GNU_SOURCE -#include -#include -#include -#include - -int ioctl(int fd, unsigned long request, ...) -{ - static int (*real_ioctl)(int, unsigned long, ...); - if (!real_ioctl) - real_ioctl = (int (*)(int, unsigned long, ...))dlsym(RTLD_NEXT, "ioctl"); - - va_list args; - va_start(args, request); - void *arg = va_arg(args, void *); - va_end(args); - - int result = real_ioctl(fd, request, arg); - if (result == 0 || (errno != ENOTTY && errno != EINVAL)) - return result; - - switch (request) { - case TIOCMGET: - *(int *)arg = TIOCM_CAR | TIOCM_DSR | TIOCM_CTS | TIOCM_DTR | TIOCM_RTS; - return 0; - case TIOCMSET: - case TIOCMBIS: - case TIOCMBIC: - return 0; - default: - return result; - } -}