Skip to content
Closed
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
5 changes: 3 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,10 @@ Avalonia 12. Use the `avalonia-docs` MCP before reaching for an API from memory.
## Security

The number arrives from a `tel:` link, which any web page or document can produce: it is
**hostile input**. It reaches the phone only after `TelUri` has reduced it to `0-9 * #` and a
**hostile input**. It reaches the phone only after `TelUri` has reduced it to digits and a
length cap — never a `;`, `\r`, `\n` or letter, which would let a link append its own AT
commands. A security fix gets a test that replays the attack. Dialling always goes through the
commands, and never `*` or `#`, which on a landline would let it set up call forwarding
(`*21*<number>#`) at the exchange. A security fix gets a test that replays the attack. Dialling always goes through the
confirm window; nothing dials silently.

## Tests
Expand Down
38 changes: 38 additions & 0 deletions src/Waehlhilfe.Domain/DialNumber.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
namespace Waehlhilfe.Domain;

/// <summary>The exact string sent after <c>ATD</c>: digits only.</summary>
public sealed record DialNumber
{
private DialNumber(string digits) => Digits = digits;

public string Digits { get; }

/// <exception cref="ArgumentException">The settings carry an invalid country code or prefix.</exception>
public static DialNumber From(TelUri uri, DialSettings settings)
{
ArgumentNullException.ThrowIfNull(uri);
ArgumentNullException.ThrowIfNull(settings);
if (!DialSettings.IsValidHomeCountryCode(settings.HomeCountryCode))
{
throw new ArgumentException("The home country code must be one to three digits.", nameof(settings));
}

if (!DialSettings.IsValidOutsideLinePrefix(settings.OutsideLinePrefix))
{
throw new ArgumentException("The outside line prefix must be at most four digits.", nameof(settings));
}

var number = uri.Number;
if (uri.IsGlobal)
{
var national = number[1..];
number = national.StartsWith(settings.HomeCountryCode, StringComparison.Ordinal)
? "0" + national[settings.HomeCountryCode.Length..]
: "00" + national;
}

return new DialNumber(settings.OutsideLinePrefix + number);
}

public override string ToString() => Digits;
}
16 changes: 16 additions & 0 deletions src/Waehlhilfe.Domain/DialSettings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
namespace Waehlhilfe.Domain;

/// <summary>How numbers are dialled and through which port.</summary>
/// <param name="PortName">Serial port of the phone's Bluetooth SPP service; empty until chosen.</param>
/// <param name="HomeCountryCode">Country code that a global number is dialled nationally for.</param>
/// <param name="OutsideLinePrefix">Amtsholung, dialled before every number behind a PBX; usually empty.</param>
public sealed record DialSettings(string PortName, string HomeCountryCode, string OutsideLinePrefix)
{
public static DialSettings Default { get; } = new(string.Empty, "49", string.Empty);

public static bool IsValidHomeCountryCode(string? code) =>
code is { Length: >= 1 and <= 3 } && code[0] != '0' && code.All(char.IsAsciiDigit);

public static bool IsValidOutsideLinePrefix(string? prefix) =>
prefix is { Length: <= 4 } && prefix.All(char.IsAsciiDigit);
}
110 changes: 110 additions & 0 deletions src/Waehlhilfe.Domain/TelUri.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
using System.Diagnostics.CodeAnalysis;
using System.Text;

namespace Waehlhilfe.Domain;

/// <summary>
/// A <c>tel:</c> link (RFC 3966) reduced to the number it names. <see cref="Number"/> holds only
/// digits, with a leading <c>+</c> for a global number: the link comes from whatever page or
/// document the user clicked, and whatever reaches the phone after <c>ATD</c> is executed by it.
/// That rules out <c>*</c> and <c>#</c> too — on a landline <c>*21*&lt;number&gt;#</c> sets up call
/// forwarding at the exchange.
/// </summary>
public sealed record TelUri
{
public const int MaxDigits = 32;

// Far above any real link; checked before decoding, so a huge argument costs nothing.
private const int MaxLinkLength = 256;

private const string Scheme = "tel:";

private TelUri(string number) => Number = number;

public string Number { get; }

public bool IsGlobal => Number.StartsWith('+');

public static bool TryParse(string? link, [MaybeNullWhen(false)] out TelUri uri)
{
uri = null;
if (link is null || link.Length > MaxLinkLength)
{
return false;
}

var text = link.Trim();
if (!text.StartsWith(Scheme, StringComparison.OrdinalIgnoreCase))
{
return false;
}

text = text[Scheme.Length..];
if (text.StartsWith("//", StringComparison.Ordinal))
{
text = text[2..];
}

var separator = text.IndexOf(';', StringComparison.Ordinal);
var numberPart = separator < 0 ? text : text[..separator];
if (separator >= 0 && !AreParametersClean(text[(separator + 1)..]))
{
return false;
}

if (!TryClean(Uri.UnescapeDataString(numberPart), out var number))
{
return false;
}

uri = new TelUri(number);
return true;
}

// Parameters (ext, isub, phone-context, …) never reach the phone, but a link carrying a
// control character anywhere is not one a person wrote, so it is refused as a whole.
private static bool AreParametersClean(string parameters) =>
!Uri.UnescapeDataString(parameters).Any(char.IsControl);

private static bool TryClean(string raw, [MaybeNullWhen(false)] out string number)
{
number = null;
var global = raw.StartsWith('+');
if (global)
{
// "+49 (0)89 …" is how German numbers are often printed; the (0) is not dialled.
raw = raw[1..].Replace("(0)", string.Empty, StringComparison.Ordinal);
}

var digits = new StringBuilder(raw.Length + 1);
if (global)
{
digits.Append('+');
}

foreach (var c in raw)
{
if (char.IsAsciiDigit(c))
{
digits.Append(c);
}
else if (!IsVisualSeparator(c))
{
return false;
}
}

var count = digits.Length - (global ? 1 : 0);
if (count is 0 or > MaxDigits)
{
return false;
}

number = digits.ToString();
return true;
}

// RFC 3966's visual separators, plus the space, no-break space and slash that German
// numbers are printed with ("089 / 1234567"). Never \r, \n or any other control character.
private static bool IsVisualSeparator(char c) => c is '-' or '.' or '(' or ')' or ' ' or ' ' or '/';
}
139 changes: 139 additions & 0 deletions src/Waehlhilfe.Modem/AtDialer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
using Waehlhilfe.Domain;

namespace Waehlhilfe.Modem;

/// <summary>
/// One dial is one connection: open the port, <c>AT</c>, <c>ATD &lt;number&gt;</c>, close. The
/// DL500A keeps the call up on the base once the link is gone, so nothing is held open.
/// </summary>
public sealed class AtDialer
{
/// <summary>Opening the port opens the Bluetooth link, which takes seconds.</summary>
public static readonly TimeSpan ConnectTimeout = TimeSpan.FromSeconds(10);

public static readonly TimeSpan ResponseTimeout = TimeSpan.FromSeconds(15);

/// <summary>How long to wait for <c>CONNECT</c> after <c>OK</c> before closing anyway.</summary>
public static readonly TimeSpan ConnectGrace = TimeSpan.FromSeconds(5);

private readonly IAtChannelFactory _channels;
private readonly TimeProvider _time;

public AtDialer(IAtChannelFactory channels, TimeProvider? time = null)
{
ArgumentNullException.ThrowIfNull(channels);
_channels = channels;
_time = time ?? TimeProvider.System;
}

/// <summary>Checks that the phone answers, without placing a call.</summary>
public Task<DialResult> ProbeAsync(string portName, CancellationToken cancellationToken = default) =>
RunAsync(portName, dial: null, cancellationToken);

public Task<DialResult> DialAsync(string portName, DialNumber number, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(number);
return RunAsync(portName, number, cancellationToken);
}

private async Task<DialResult> RunAsync(string portName, DialNumber? dial, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(portName))
{
return DialResult.PortNotSet;
}

try
{
using var connect = new CancellationTokenSource(ConnectTimeout, _time);
using var connectOrCancel = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, connect.Token);
await using var channel = await _channels.OpenAsync(portName, connectOrCancel.Token);

var answer = await CommandAsync(channel, "AT", connectOrCancel.Token);
if (answer != DialResult.Answered || dial is null)
{
return answer;
}

using var response = new CancellationTokenSource(ResponseTimeout, _time);
using var responseOrCancel = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, response.Token);
var result = await CommandAsync(channel, "ATD " + dial.Digits, responseOrCancel.Token);
if (result == DialResult.Answered)
{
await AwaitConnectAsync(channel, cancellationToken);
return DialResult.Dialled;
}

return result;
}
catch (PortUnavailableException e)
{
return e.Failure switch
{
PortFailure.Busy => DialResult.PortBusy,
PortFailure.Unreachable => DialResult.NoResponse,
_ => DialResult.PortMissing,
};
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
return DialResult.NoResponse;
}
catch (IOException)
{
// The Bluetooth link went away after the port opened: phone switched off, out of
// range, or the OS dropped the RFCOMM channel.
return DialResult.NoResponse;
}
}

// Sends one command and reads up to its final result code; OK and CONNECT come back as
// Answered. The echo, blank lines and unsolicited codes (RING, CLIP:…) are skipped.
private static async Task<DialResult> CommandAsync(IAtChannel channel, string command, CancellationToken cancellationToken)
{
await channel.WriteLineAsync(command, cancellationToken);
while (await channel.ReadLineAsync(cancellationToken) is { } line)
{
if (FinalResult(line.Trim()) is { } result)
{
return result;
}
}

return DialResult.NoResponse;
}

// After OK the base dials on its own; CONNECT confirms it. Closing earlier would most likely
// be fine too, but waiting a moment costs nothing and keeps the link until it is confirmed.
private async Task AwaitConnectAsync(IAtChannel channel, CancellationToken cancellationToken)
{
using var grace = new CancellationTokenSource(ConnectGrace, _time);
using var graceOrCancel = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, grace.Token);
try
{
while (await channel.ReadLineAsync(graceOrCancel.Token) is { } line)
{
if (FinalResult(line.Trim()) is not null)
{
return;
}
}
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
// The grace period ran out: the call was accepted with OK, so it still counts.
}
}

private static DialResult? FinalResult(string line) => line switch
{
"OK" => DialResult.Answered,
"ERROR" => DialResult.Rejected,
"BUSY" => DialResult.LineBusy,
"NO CARRIER" or "NO ANSWER" => DialResult.NoCarrier,
"NO DIALTONE" => DialResult.NoDialTone,
_ when line.StartsWith("CONNECT", StringComparison.Ordinal) => DialResult.Answered,
_ when line.StartsWith("+CME ERROR", StringComparison.Ordinal) => DialResult.Rejected,
_ => null,
};
}
32 changes: 32 additions & 0 deletions src/Waehlhilfe.Modem/DialResult.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
namespace Waehlhilfe.Modem;

public enum DialResult
{
/// <summary>The phone accepted <c>ATD</c> and is setting up the call.</summary>
Dialled,

/// <summary>The phone answered <c>AT</c>; returned by a probe only.</summary>
Answered,

/// <summary>No port has been chosen yet.</summary>
PortNotSet,

PortMissing,

PortBusy,

/// <summary>
/// The port opened but the phone never answered. With a DL500A this is what an audio
/// (Hands-Free) connection to the same PC does to the serial port.
/// </summary>
NoResponse,

/// <summary><c>ERROR</c> or <c>+CME ERROR</c>.</summary>
Rejected,

LineBusy,

NoCarrier,

NoDialTone,
}
16 changes: 16 additions & 0 deletions src/Waehlhilfe.Modem/IAtChannel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
namespace Waehlhilfe.Modem;

/// <summary>A line-oriented connection to the phone's AT command interpreter.</summary>
public interface IAtChannel : IAsyncDisposable
{
Task WriteLineAsync(string line, CancellationToken cancellationToken = default);

/// <returns>The next line without its terminator, or <c>null</c> once the link has dropped.</returns>
Task<string?> ReadLineAsync(CancellationToken cancellationToken = default);
}

public interface IAtChannelFactory
{
/// <exception cref="PortUnavailableException">The port does not exist or another program holds it.</exception>
Task<IAtChannel> OpenAsync(string portName, CancellationToken cancellationToken = default);
}
Loading
Loading