using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Titano.Protocol;
using Titano.Server.Api;
using Titano.Server.Configuration;
namespace Titano.Server.Hosting;
///
/// LAN discovery (BRIEF ยง14.9, TITANO_DISCOVERY): every few seconds a is broadcast on
/// UDP port of every IPv4 network, so clients can offer this server on first run.
/// Switching discovery off in the settings stops it without a restart. In a container the broadcasts reach the LAN
/// only with host networking; on a bridge network they stay on the bridge.
///
public sealed class DiscoveryBeaconService(ServerOptions options, ServerState state, IServer server, ILogger logger) : BackgroundService
{
private static readonly TimeSpan Interval = TimeSpan.FromSeconds(5);
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var udp = new UdpClient(AddressFamily.InterNetwork) { EnableBroadcast = true };
var warned = false;
while (!stoppingToken.IsCancellationRequested)
{
if (options.Discovery)
{
try
{
await SendOnceAsync(udp, BroadcastTargets(), stoppingToken);
}
catch (SocketException ex) when (!warned)
{
warned = true;
logger.LogInformation("LAN discovery beacon cannot be sent: {Reason}", ex.Message);
}
catch (SocketException)
{
// Already reported once; networks may come and go.
}
}
try
{
await Task.Delay(Interval, stoppingToken);
}
catch (OperationCanceledException)
{
return;
}
}
}
///
/// The beacon for the ports clients reach: the public ports when set, else the ports Kestrel actually listens on
/// (HTTPS 0 when TLS is terminated elsewhere).
///
public DiscoveryBeacon CreateBeacon() => new(
options.ServerName,
SystemEndpoints.Version,
options.PublicHttpPort ?? BoundPort(Uri.UriSchemeHttp) ?? options.HttpPort,
state.TlsFingerprint is null ? 0 : options.PublicHttpsPort ?? BoundPort(Uri.UriSchemeHttps) ?? options.HttpsPort,
state.TlsFingerprint);
public async Task SendOnceAsync(UdpClient udp, IEnumerable targets, CancellationToken cancellationToken)
{
var datagram = CreateBeacon().ToBytes();
foreach (var target in targets) await udp.SendAsync(datagram, target, cancellationToken);
}
/// The limited broadcast address plus the directed broadcast of each IPv4 interface that is up.
private static List BroadcastTargets()
{
var targets = new List { new(IPAddress.Broadcast, DiscoveryBeacon.Port) };
foreach (var nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus != OperationalStatus.Up || nic.NetworkInterfaceType == NetworkInterfaceType.Loopback) continue;
foreach (var unicast in nic.GetIPProperties().UnicastAddresses)
{
if (unicast.Address.AddressFamily != AddressFamily.InterNetwork || unicast.IPv4Mask is not { } mask) continue;
var address = unicast.Address.GetAddressBytes();
var bits = mask.GetAddressBytes();
for (var i = 0; i < 4; i++) address[i] = (byte)(address[i] | ~bits[i]);
var broadcast = new IPEndPoint(new IPAddress(address), DiscoveryBeacon.Port);
if (!targets.Contains(broadcast)) targets.Add(broadcast);
}
}
return targets;
}
private int? BoundPort(string scheme)
{
var addresses = server.Features.Get()?.Addresses ?? [];
foreach (var address in addresses)
{
if (Uri.TryCreate(address.Replace("[::]", "localhost", StringComparison.Ordinal).Replace("0.0.0.0", "localhost", StringComparison.Ordinal),
UriKind.Absolute, out var uri) && uri.Scheme == scheme)
return uri.Port;
}
return null;
}
}