Files
Heimdall/src/Heimdall.Agent/Services/NetworkCameraScanner.cs
T

1206 lines
50 KiB
C#
Raw Normal View History

using System.Collections.Concurrent;
using System.Globalization;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Xml.Linq;
using Heimdall.Application.Discovery;
using Heimdall.Application.DTOs;
using Microsoft.Extensions.Logging;
namespace Heimdall.Agent.Services;
/// <summary>
/// Lightweight local-network camera scanner used by the agent.
/// The agent lives on the camera network (the Central usually does not), so it
/// probes its own subnet: TCP port scan for common camera ports, an HTTP
/// header probe, ONVIF WS-Discovery (unicast), and an ARP table lookup for the
/// MAC address. When the site's credential pool is available (shipped by the
/// Central in the agent config, encrypted), the scanner performs the
/// <b>authenticated</b> ONVIF GetDeviceInformation calls itself — protected
/// cameras that refuse anonymous probing are identified (manufacturer, model)
/// using each credential pair. Raw+enriched results are posted to the Central
/// (POST /api/agents/{id}/discovery), which only persists them.
/// </summary>
public sealed class NetworkCameraScanner
{
private static readonly int[] CameraPorts = [80, 443, 554, 8554, 3702, 8899, 37777, 34567, 34568, 8000];
private static readonly TimeSpan PortTimeout = TimeSpan.FromMilliseconds(750);
private static readonly TimeSpan HttpTimeout = TimeSpan.FromSeconds(2);
private static readonly TimeSpan RtspTimeout = TimeSpan.FromSeconds(2);
private static readonly TimeSpan StreamTestTimeout = TimeSpan.FromSeconds(3);
private static readonly TimeSpan OnvifUdpTimeout = TimeSpan.FromMilliseconds(500);
// ReSharper disable once InconsistentNaming
private static readonly XNamespace SoapNs = "http://www.w3.org/2003/05/soap-envelope";
// ReSharper disable once InconsistentNaming
private static readonly XNamespace WsdNs = "http://schemas.xmlsoap.org/ws/2005/04/discovery";
// ReSharper disable once InconsistentNaming
private static readonly XNamespace WsaNs = "http://schemas.xmlsoap.org/ws/2004/08/addressing";
// ReSharper disable once InconsistentNaming
private static readonly XNamespace TdnNs = "http://www.onvif.org/ver10/network/wsdl";
// ReSharper disable once InconsistentNaming
private static readonly XNamespace TdsNs = "http://www.onvif.org/ver10/device/wsdl";
// ReSharper disable once InconsistentNaming
private static readonly XNamespace MediaNs = "http://www.onvif.org/ver10/media/wsdl";
// ReSharper disable once InconsistentNaming
private static readonly XNamespace WsseNs = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
private readonly ILogger<NetworkCameraScanner> _logger;
private readonly string? _localIp;
private readonly string? _gatewayIp;
public NetworkCameraScanner(ILogger<NetworkCameraScanner> logger)
{
_logger = logger;
var (localIp, gatewayIp) = GetLocalNetworkInfo();
_localIp = localIp;
_gatewayIp = gatewayIp;
}
/// <summary>
/// Scan the local subnet for camera-like devices. Returns an empty list
/// when the local network cannot be determined. When <paramref name="credentialPool"/>
/// is provided, ONVIF device information is fetched with authentication
/// (each pair is tried, PasswordDigest then PasswordText) so protected
/// cameras are identified with their ONVIF manufacturer/model.
/// </summary>
public async Task<IReadOnlyList<AgentDiscoveredDevice>> ScanAsync(
CancellationToken ct, IReadOnlyList<AgentCameraCredential>? credentialPool = null)
{
var (subnetCidr, localIp) = GetLocalSubnetCidr();
if (subnetCidr is null)
{
_logger.LogWarning("Camera discovery: unable to determine local subnet, skipping scan");
return [];
}
var ips = ExpandSubnet(subnetCidr);
_logger.LogInformation("Camera discovery: scanning {Subnet} ({Count} hosts, {Pool} credential pair(s))",
subnetCidr, ips.Count, credentialPool?.Count ?? 0);
var results = new ConcurrentBag<AgentDiscoveredDevice>();
using var throttler = new SemaphoreSlim(40);
// Broadcast/multicast probes (ONVIF WS-Discovery, DVRIP) run in
// parallel with the TCP sweep — one multicast probe discovers every
// ONVIF camera on the LAN, including those with TCP 3702 closed.
var broadcastTask = DiscoverByBroadcastAsync(credentialPool, ct);
var tasks = ips.Select(async ip =>
{
if (ct.IsCancellationRequested) return;
// Skip the agent's own IP and the LAN gateway (NAT/router — never a camera).
if (ip == localIp || ip == _gatewayIp) return;
await throttler.WaitAsync(ct).ConfigureAwait(false);
try
{
var device = await ProbeHostAsync(ip, credentialPool, ct).ConfigureAwait(false);
if (device is null)
return;
var final = await BuildFinalDeviceAsync(device, credentialPool, ct).ConfigureAwait(false);
if (final is not null)
results.Add(final);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
// stop probing
}
catch (Exception ex)
{
_logger.LogTrace(ex, "Probe error for {Ip}", ip);
}
finally
{
throttler.Release();
}
});
await Task.WhenAll(tasks).ConfigureAwait(false);
// Merge multicast/broadcast-discovered devices (dedupe by IP — the TCP
// sweep already probed most of them).
var seenIps = new HashSet<string>(results.Select(r => r.Ip), StringComparer.Ordinal);
foreach (var device in await broadcastTask.ConfigureAwait(false))
{
if (device.Ip == localIp || device.Ip == _gatewayIp)
continue;
if (!seenIps.Add(device.Ip))
continue;
var final = await BuildFinalDeviceAsync(device, credentialPool, ct).ConfigureAwait(false);
if (final is not null)
results.Add(final);
}
_logger.LogInformation("Camera discovery: {Found} candidate device(s) on {Subnet}", results.Count, subnetCidr);
return results.ToList();
}
/// <summary>
/// Apply the camera-evidence filter + live stream test to a probed device and
/// return it with its final <see cref="AgentDiscoveredDevice.StreamUrls"/>,
/// or null when the device is not a usable camera.
/// </summary>
private async Task<AgentDiscoveredDevice?> BuildFinalDeviceAsync(
AgentDiscoveredDevice device, IReadOnlyList<AgentCameraCredential>? credentialPool, CancellationToken ct)
{
// Keep only devices with real camera evidence. Web servers with just
// 80/443 open (nginx, gunicorn, …) are filtered out here.
if (!HasDefinitiveCameraEvidence(device) && !HasCameraPorts(device))
return null;
// Real ONVIF GetStreamUri URLs (agent enrichment) take priority over
// guessed templates: keep them even when the stream test fails — the
// camera is already proven by ONVIF, the stream may just need auth.
if (device.StreamUrls is { Length: > 0 })
{
var alive = await TestUrlsAsync(device.StreamUrls, ct).ConfigureAwait(false);
return device with { StreamUrls = alive.Count > 0 ? [.. alive] : device.StreamUrls };
}
// Build + test candidate stream URLs (the agent is on the camera LAN,
// the Central is not — this is where the live stream is proven).
var tested = await TestStreamUrlsAsync(device, credentialPool, ct).ConfigureAwait(false);
if (tested.Count > 0)
return device with { StreamUrls = [.. tested] };
if (HasDefinitiveCameraEvidence(device))
{
// Authenticated/protected camera with no anonymous stream:
// keep it with the untested candidate URLs as a fallback.
var fallback = BuildCandidateUrls(device, credentialPool);
if (fallback.Count > 0)
return device with { StreamUrls = [.. fallback] };
}
// else: camera ports open but no live stream → not usable, skip.
return null;
}
/// <summary>
/// LAN-wide broadcast/multicast discovery: ONVIF WS-Discovery multicast
/// (UDP 239.255.255.250:3702) and Dahua/Imou DVRIP broadcast (port 34569).
/// Returns devices already enriched with ONVIF name/hardware where possible.
/// </summary>
private async Task<List<AgentDiscoveredDevice>> DiscoverByBroadcastAsync(
IReadOnlyList<AgentCameraCredential>? credentialPool, CancellationToken ct)
{
var devices = new List<AgentDiscoveredDevice>();
devices.AddRange(await DiscoverOnvifMulticastAsync(credentialPool, ct).ConfigureAwait(false));
devices.AddRange(await DiscoverDvripAsync(ct).ConfigureAwait(false));
return devices;
}
/// <summary>
/// Dahua/Imou DVRIP discovery broadcast (UDP port 34569): sends the DVRIP
/// probe 3 times (devices sometimes miss it) and parses the JSON
/// NetWork.NetCommon replies (HostIP, HostName, MAC, SN, HttpPort…).
/// Finds Dahua/Imou cameras even with RTSP/ONVIF disabled.
/// Transposed from go2rtc internal/dvrip.
/// </summary>
private async Task<List<AgentDiscoveredDevice>> DiscoverDvripAsync(CancellationToken ct)
{
var devices = new List<AgentDiscoveredDevice>();
try
{
using var udp = new UdpClient();
udp.Client.Bind(new IPEndPoint(IPAddress.Any, 34569));
udp.Client.ReceiveTimeout = 2000;
var probe = Convert.FromHexString("ff00000000000000000000000000fa0500000000");
var broadcast = new IPEndPoint(IPAddress.Broadcast, 34569);
for (var i = 0; i < 3; i++)
{
await udp.SendAsync(probe, broadcast, ct).ConfigureAwait(false);
await Task.Delay(100, ct).ConfigureAwait(false);
}
while (!ct.IsCancellationRequested)
{
UdpReceiveResult result;
try
{
result = await udp.ReceiveAsync(ct).ConfigureAwait(false);
}
catch (SocketException)
{
break; // receive timeout
}
catch (OperationCanceledException)
{
break;
}
var json = Encoding.UTF8.GetString(result.Buffer);
var info = ParseDvripNetCommon(json);
if (info is null || info.Ret is >= 0 and not 100)
continue; // error reply or non-DVRIP packet
devices.Add(new AgentDiscoveredDevice(
Ip: info.HostIp,
IsReachable: true,
OpenPorts: [37777],
MacAddress: info.Mac,
Vendor: "Dahua",
Hostname: info.HostName,
HttpServerHeader: null,
HttpStatusCode: null,
HttpPort: info.HttpPort > 0 ? info.HttpPort : null,
OnvifDeviceServiceUrl: null,
OnvifName: null,
OnvifHardware: null,
OnvifPort: null,
HomeKitName: null,
HomeKitDeviceId: null,
HomeKitModel: null,
CredentialLabel: null,
StreamUrls: null));
}
if (devices.Count > 0)
_logger.LogInformation("Camera discovery: {Count} DVRIP device(s) via broadcast", devices.Count);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
// cancelled
}
catch (Exception ex)
{
_logger.LogWarning(ex, "DVRIP discovery failed");
}
return devices;
}
private sealed record DvripNetCommon(string HostIp, string HostName, string? Mac, int HttpPort, int Ret);
private static DvripNetCommon? ParseDvripNetCommon(string json)
{
try
{
using var doc = JsonDocument.Parse(json);
if (!doc.RootElement.TryGetProperty("NetWork.NetCommon", out var nc))
return null;
var hostIp = GetJsonString(nc, "HostIP");
var hostName = GetJsonString(nc, "HostName");
if (string.IsNullOrEmpty(hostIp) || string.IsNullOrEmpty(hostName))
return null;
var ret = doc.RootElement.TryGetProperty("Ret", out var retEl) && retEl.TryGetInt32(out var r) ? r : -1;
return new DvripNetCommon(
hostIp, hostName, GetJsonString(nc, "MAC"), GetJsonInt(nc, "HttpPort"), ret);
}
catch
{
return null;
}
}
private static string? GetJsonString(JsonElement el, string name)
=> el.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() : null;
private static int GetJsonInt(JsonElement el, string name)
=> el.TryGetProperty(name, out var v) && v.TryGetInt32(out var i) ? i : 0;
/// <summary>
/// ONVIF WS-Discovery multicast probe (Feature Discovery spec §5.3):
/// send one UDP probe to 239.255.255.250:3702, collect replies for ~5 s.
/// Only responses mentioning ONVIF are kept (ignores printers, etc.).
/// Transposed from go2rtc pkg/onvif DiscoveryStreamingDevices.
/// </summary>
private async Task<List<AgentDiscoveredDevice>> DiscoverOnvifMulticastAsync(
IReadOnlyList<AgentCameraCredential>? credentialPool, CancellationToken ct)
{
var devices = new List<AgentDiscoveredDevice>();
var raw = new List<(string Ip, string ServiceUrl, string? Name, string? Hardware)>();
try
{
using var udp = new UdpClient();
var messageId = Guid.NewGuid().ToString();
var probe = $@"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope xmlns:soap=""{SoapNs.NamespaceName}""
xmlns:wsa=""{WsaNs.NamespaceName}""
xmlns:wsd=""{WsdNs.NamespaceName}""
xmlns:tdn=""{TdnNs.NamespaceName}"">
<soap:Header>
<wsa:Action soap:mustUnderstand=""1"">{WsdNs.NamespaceName}/Probe</wsa:Action>
<wsa:MessageID soap:mustUnderstand=""1"">uuid:{messageId}</wsa:MessageID>
<wsa:To soap:mustUnderstand=""1"">urn:schemas-xmlsoap-org:ws:2005:04:discovery</wsa:To>
</soap:Header>
<soap:Body>
<wsd:Probe>
<wsd:Types>tdn:NetworkVideoTransmitter</wsd:Types>
</wsd:Probe>
</soap:Body>
</soap:Envelope>";
var multicast = new IPEndPoint(IPAddress.Parse("239.255.255.250"), 3702);
await udp.SendAsync(Encoding.UTF8.GetBytes(probe), multicast, ct).ConfigureAwait(false);
udp.Client.ReceiveTimeout = 5000;
while (!ct.IsCancellationRequested)
{
UdpReceiveResult result;
try
{
result = await udp.ReceiveAsync(ct).ConfigureAwait(false);
}
catch (SocketException)
{
break; // receive timeout
}
catch (OperationCanceledException)
{
break;
}
var xml = Encoding.UTF8.GetString(result.Buffer);
if (!xml.Contains("onvif", StringComparison.OrdinalIgnoreCase))
continue; // ignore printers, etc.
XDocument doc;
try
{
doc = XDocument.Parse(xml);
}
catch
{
continue;
}
var xaddrs = doc.Descendants(XName.Get("XAddrs", WsdNs.NamespaceName))
.SelectMany(e => e.Value.Split(' ', StringSplitOptions.RemoveEmptyEntries))
.ToList();
if (xaddrs.Count == 0)
continue;
var serviceUrl = xaddrs[0];
// Fix buggy cameras: <wsdd:XAddrs>http://0.0.0.0:8080/onvif/device_service</wsdd:XAddrs>
if (serviceUrl.StartsWith("http://0.0.0.0", StringComparison.Ordinal))
serviceUrl = "http://" + result.RemoteEndPoint.Address + serviceUrl["http://0.0.0.0".Length..];
raw.Add((
result.RemoteEndPoint.Address.ToString(),
serviceUrl,
FindScope(doc, "onvif://www.onvif.org/name/"),
FindScope(doc, "onvif://www.onvif.org/hardware/")));
}
// Enrich each reply: vendor via GetDeviceInformation, real stream
// URLs via GetProfiles/GetStreamUri (authenticated when needed).
using var throttler = new SemaphoreSlim(8);
var tasks = raw.Select(async entry =>
{
await throttler.WaitAsync(ct).ConfigureAwait(false);
try
{
var detail = await GetDeviceInformationWithCredentialsAsync(
entry.ServiceUrl, credentialPool, ct).ConfigureAwait(false);
var streamUrls = await GetStreamUrisWithCredentialsAsync(
entry.ServiceUrl, credentialPool, entry.Ip, ct).ConfigureAwait(false);
devices.Add(new AgentDiscoveredDevice(
Ip: entry.Ip,
IsReachable: true,
OpenPorts: [],
MacAddress: null,
Vendor: detail?.Manufacturer,
Hostname: entry.Name,
HttpServerHeader: null,
HttpStatusCode: null,
HttpPort: null,
OnvifDeviceServiceUrl: entry.ServiceUrl,
OnvifName: entry.Name ?? detail?.Manufacturer,
OnvifHardware: entry.Hardware ?? detail?.Model,
OnvifPort: 3702,
HomeKitName: null,
HomeKitDeviceId: null,
HomeKitModel: null,
CredentialLabel: detail?.CredentialLabel,
StreamUrls: streamUrls.Length > 0 ? streamUrls : null));
}
finally
{
throttler.Release();
}
});
await Task.WhenAll(tasks).ConfigureAwait(false);
if (raw.Count > 0)
_logger.LogInformation(
"Camera discovery: {Count} ONVIF device(s) via WS-Discovery multicast", devices.Count);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
// cancelled
}
catch (Exception ex)
{
_logger.LogWarning(ex, "ONVIF WS-Discovery multicast failed");
}
return devices;
}
/// <summary>Extract an ONVIF scope value by prefix (e.g. onvif://www.onvif.org/name/).</summary>
private static string? FindScope(XDocument doc, string prefix)
{
var scopes = doc.Descendants(XName.Get("Scopes", WsdNs.NamespaceName)).FirstOrDefault()?.Value;
if (scopes is null)
return null;
foreach (var part in scopes.Split(' ', StringSplitOptions.RemoveEmptyEntries))
{
if (part.StartsWith(prefix, StringComparison.Ordinal))
return Uri.UnescapeDataString(part[prefix.Length..]);
}
return null;
}
private async Task<AgentDiscoveredDevice?> ProbeHostAsync(
string ip, IReadOnlyList<AgentCameraCredential>? credentialPool, CancellationToken ct)
{
var openPorts = await ScanPortsAsync(ip, ct).ConfigureAwait(false);
if (openPorts.Count == 0)
return null;
HttpProbe? http = null;
if (openPorts.Contains(80) || openPorts.Contains(443))
{
var webPort = openPorts.Contains(80) ? 80 : 443;
http = await ProbeHttpAsync(ip, webPort, ct).ConfigureAwait(false);
}
OnvifProbe? onvif = null;
if (openPorts.Contains(3702))
onvif = await ProbeOnvifAsync(ip, 3702, credentialPool, ct).ConfigureAwait(false);
var mac = GetArpMac(ip);
return new AgentDiscoveredDevice(
Ip: ip,
IsReachable: true,
OpenPorts: [.. openPorts],
MacAddress: mac,
Vendor: null,
Hostname: null,
HttpServerHeader: http?.ServerHeader,
HttpStatusCode: http?.StatusCode,
HttpPort: http?.Port,
OnvifDeviceServiceUrl: onvif?.DeviceServiceUrl,
OnvifName: onvif?.Name,
OnvifHardware: onvif?.Hardware,
OnvifPort: onvif is not null ? 3702 : null,
HomeKitName: null,
HomeKitDeviceId: null,
HomeKitModel: null,
CredentialLabel: onvif?.CredentialLabel,
StreamUrls: onvif?.StreamUrls);
}
private static async Task<List<int>> ScanPortsAsync(string ip, CancellationToken ct)
{
var open = new ConcurrentBag<int>();
var tasks = CameraPorts.Select(async port =>
{
using var client = new TcpClient();
var connectTask = client.ConnectAsync(IPAddress.Parse(ip), port, ct).AsTask();
var completed = await Task.WhenAny(connectTask, Task.Delay(PortTimeout, ct)).ConfigureAwait(false);
if (completed == connectTask && client.Connected)
open.Add(port);
client.Close();
});
await Task.WhenAll(tasks).ConfigureAwait(false);
return [.. open.Order()];
}
private async Task<HttpProbe?> ProbeHttpAsync(string ip, int port, CancellationToken ct)
{
try
{
using var handler = new HttpClientHandler
{
AllowAutoRedirect = false,
ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator,
};
using var client = new HttpClient(handler) { Timeout = HttpTimeout };
using var request = new HttpRequestMessage(HttpMethod.Get, $"http://{ip}:{port}/");
request.Headers.UserAgent.ParseAdd("HeimdallAgent/1.0");
using var response = await client.SendAsync(request, ct).ConfigureAwait(false);
var serverHeader = response.Headers.TryGetValues("Server", out var values)
? string.Join(",", values)
: null;
return new HttpProbe(port, (int)response.StatusCode, serverHeader);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger.LogTrace(ex, "HTTP probe failed for {Ip}:{Port}", ip, port);
return null;
}
}
private async Task<OnvifProbe?> ProbeOnvifAsync(
string ip, int port, IReadOnlyList<AgentCameraCredential>? credentialPool, CancellationToken ct)
{
try
{
using var udp = new UdpClient();
udp.Client.ReceiveTimeout = (int)OnvifUdpTimeout.TotalMilliseconds;
udp.Connect(ip, port);
var messageId = Guid.NewGuid().ToString();
var probe = $@"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope xmlns:soap=""{SoapNs.NamespaceName}""
xmlns:wsa=""{WsaNs.NamespaceName}""
xmlns:wsd=""{WsdNs.NamespaceName}""
xmlns:tdn=""{TdnNs.NamespaceName}"">
<soap:Header>
<wsa:Action soap:mustUnderstand=""1"">{WsdNs.NamespaceName}/Probe</wsa:Action>
<wsa:MessageID soap:mustUnderstand=""1"">uuid:{messageId}</wsa:MessageID>
<wsa:To soap:mustUnderstand=""1"">urn:schemas-xmlsoap-org:ws:2005:04:discovery</wsa:To>
</soap:Header>
<soap:Body>
<wsd:Probe>
<wsd:Types>tdn:NetworkVideoTransmitter</wsd:Types>
</wsd:Probe>
</soap:Body>
</soap:Envelope>";
await udp.SendAsync(Encoding.UTF8.GetBytes(probe), ct).ConfigureAwait(false);
var result = await udp.ReceiveAsync(ct).ConfigureAwait(false);
var xml = Encoding.UTF8.GetString(result.Buffer);
var doc = XDocument.Parse(xml);
var xaddrs = doc.Descendants(XName.Get("XAddrs", WsdNs.NamespaceName))
.SelectMany(e => e.Value.Split(' ', StringSplitOptions.RemoveEmptyEntries))
.ToList();
if (xaddrs.Count == 0)
return null;
var deviceServiceUrl = xaddrs[0];
var detail = await GetDeviceInformationWithCredentialsAsync(deviceServiceUrl, credentialPool, ct).ConfigureAwait(false);
var streamUrls = await GetStreamUrisWithCredentialsAsync(deviceServiceUrl, credentialPool, ip, ct).ConfigureAwait(false);
return new OnvifProbe(
deviceServiceUrl, detail?.Manufacturer, detail?.Model, detail?.CredentialLabel,
streamUrls.Length > 0 ? streamUrls : null);
}
catch (SocketException ex) when (ex.SocketErrorCode is SocketError.TimedOut or SocketError.ConnectionRefused)
{
return null;
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
throw;
}
catch (Exception ex)
{
_logger.LogTrace(ex, "ONVIF probe failed for {Ip}:{Port}", ip, port);
return null;
}
}
/// <summary>
/// Fetch ONVIF device information, trying the site credential pool so that
/// protected cameras respond. Order: anonymous first (open cameras), then
/// each pair of the pool (PasswordDigest, then PasswordText for laxer
/// WS-Security implementations). Returns null when nothing works.
/// </summary>
private async Task<OnvifDetail?> GetDeviceInformationWithCredentialsAsync(
string deviceServiceUrl, IReadOnlyList<AgentCameraCredential>? credentialPool, CancellationToken ct)
{
// 1. Anonymous (cameras without auth or with default-open ONVIF).
var anonymous = await GetDeviceInformationAsync(deviceServiceUrl, null, null, null, ct).ConfigureAwait(false);
if (anonymous is not null)
return anonymous;
// 2. Credential pool, if provided by the Central.
if (credentialPool is not null)
{
foreach (var credential in credentialPool)
{
var digest = await GetDeviceInformationAsync(
deviceServiceUrl, credential.Username, credential.Password, "PasswordDigest", ct).ConfigureAwait(false);
if (digest is not null)
{
_logger.LogInformation(
"ONVIF auth succeeded with credential '{Label}' for {Url}", credential.Label, deviceServiceUrl);
return digest with { CredentialLabel = credential.Label };
}
var text = await GetDeviceInformationAsync(
deviceServiceUrl, credential.Username, credential.Password, "PasswordText", ct).ConfigureAwait(false);
if (text is not null)
{
_logger.LogInformation(
"ONVIF auth (PasswordText) succeeded with credential '{Label}' for {Url}", credential.Label, deviceServiceUrl);
return text with { CredentialLabel = credential.Label };
}
}
}
return null;
}
private async Task<OnvifDetail?> GetDeviceInformationAsync(
string deviceServiceUrl, string? username, string? password, string? passwordType, CancellationToken ct)
{
try
{
using var client = new HttpClient { Timeout = HttpTimeout };
var doc = await PostSoapAsync(client, deviceServiceUrl, "GetDeviceInformation", null, username, password, passwordType, ct).ConfigureAwait(false);
if (doc is null)
return null;
var info = doc.Root?.Element(SoapNs + "Body")?.Element(XName.Get("GetDeviceInformationResponse", TdsNs.NamespaceName));
if (info is null)
return null;
return new OnvifDetail(
info.Element(XName.Get("Manufacturer", TdsNs.NamespaceName))?.Value,
info.Element(XName.Get("Model", TdsNs.NamespaceName))?.Value);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger.LogTrace(ex, "GetDeviceInformation failed for {Url}", deviceServiceUrl);
return null;
}
}
/// <summary>
/// Fetch the camera's real stream URLs via ONVIF GetProfiles + GetStreamUri
/// (media service), trying the credential pool. Returns the URLs with
/// credentials injected and the host normalized to the probed IP.
/// Transposed from Strix pkg/tester/source_onvif.go / go2rtc api/onvif.
/// </summary>
private async Task<string[]> GetStreamUrisWithCredentialsAsync(
string deviceServiceUrl, IReadOnlyList<AgentCameraCredential>? credentialPool, string expectedIp, CancellationToken ct)
{
var anonymous = await GetStreamUrisAsync(deviceServiceUrl, null, null, null, expectedIp, ct).ConfigureAwait(false);
if (anonymous.Length > 0)
return anonymous;
if (credentialPool is not null)
{
foreach (var credential in credentialPool)
{
var digest = await GetStreamUrisAsync(
deviceServiceUrl, credential.Username, credential.Password, "PasswordDigest", expectedIp, ct).ConfigureAwait(false);
if (digest.Length > 0)
return digest;
var text = await GetStreamUrisAsync(
deviceServiceUrl, credential.Username, credential.Password, "PasswordText", expectedIp, ct).ConfigureAwait(false);
if (text.Length > 0)
return text;
}
}
return [];
}
private async Task<string[]> GetStreamUrisAsync(
string deviceServiceUrl, string? username, string? password, string? passwordType,
string expectedIp, CancellationToken ct)
{
try
{
using var client = new HttpClient { Timeout = HttpTimeout };
var profiles = await PostSoapAsync(client, deviceServiceUrl, "GetProfiles", null, username, password, passwordType, ct).ConfigureAwait(false);
if (profiles is null)
return [];
var tokens = profiles.Descendants(MediaNs + "Profiles")
.Select(e => (string?)e.Attribute("token"))
.Where(t => !string.IsNullOrEmpty(t))
.Select(t => t!)
.Distinct()
.Take(4) // main streams only
.ToList();
if (tokens.Count == 0)
return [];
var urls = new List<string>();
foreach (var token in tokens)
{
var body = $"<trt:GetStreamUri><trt:StreamSetup><trt:Stream>RTP-Unicast</trt:Stream>"
+ $"<trt:Transport><trt:Protocol>RTSP</trt:Protocol></trt:Transport></trt:StreamSetup>"
+ $"<trt:ProfileToken>{token}</trt:ProfileToken></trt:GetStreamUri>";
var resp = await PostSoapAsync(client, deviceServiceUrl, "GetStreamUri", body, username, password, passwordType, ct).ConfigureAwait(false);
if (resp is null)
continue;
var uri = resp.Descendants(MediaNs + "Uri").FirstOrDefault()?.Value;
if (string.IsNullOrEmpty(uri))
continue;
urls.Add(NormalizeStreamUri(uri, expectedIp, username, password));
}
return [.. urls.Distinct(StringComparer.OrdinalIgnoreCase)];
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger.LogTrace(ex, "GetStreamUri failed for {Url}", deviceServiceUrl);
return [];
}
}
/// <summary>
/// Normalize a stream URL returned by GetStreamUri: replace a buggy host
/// (0.0.0.0 or an IP different from the probed one) and inject the
/// credentials so the URL is directly usable by the Central.
/// </summary>
private static string NormalizeStreamUri(string uri, string expectedIp, string? username, string? password)
{
try
{
var u = new Uri(uri);
var host = u.Host;
if (host == "0.0.0.0" || !string.Equals(host, expectedIp, StringComparison.Ordinal))
host = expectedIp;
var builder = new UriBuilder(u) { Host = host };
if (!string.IsNullOrEmpty(username))
{
builder.UserName = Uri.EscapeDataString(username);
builder.Password = Uri.EscapeDataString(password ?? "");
}
return builder.Uri.ToString();
}
catch
{
return uri;
}
}
/// <summary>POST a SOAP operation to an ONVIF service and parse the response.</summary>
private static async Task<XDocument?> PostSoapAsync(
HttpClient client, string deviceServiceUrl, string operation, string? bodyContent,
string? username, string? password, string? passwordType, CancellationToken ct)
{
var soap = BuildSoapEnvelope(operation, bodyContent, username, password, passwordType);
using var content = new StringContent(soap, Encoding.UTF8, "application/soap+xml");
using var response = await client.PostAsync(deviceServiceUrl, content, ct).ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
return null;
var responseXml = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
return XDocument.Parse(responseXml);
}
/// <summary>
/// Build a SOAP envelope for an ONVIF operation, adding a WS-Security
/// UsernameToken when credentials are provided (PasswordDigest or
/// PasswordText, matching ONVIF interop requirements).
/// </summary>
private static string BuildSoapEnvelope(
string operation, string? bodyContent, string? username, string? password, string? passwordType)
{
var securityHeader = string.Empty;
if (username is not null && passwordType is not null)
{
if (passwordType == "PasswordDigest")
{
var nonce = new byte[16];
RandomNumberGenerator.Fill(nonce);
var created = DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture);
// ONVIF WS-Security PasswordDigest is defined by the standard to use SHA1
// (digest = Base64(SHA1(nonce + created + password))). Required for
// interoperability with ONVIF cameras — not used for application security.
#pragma warning disable CA5350 // Do Not Use Weak Cryptographic Algorithms
var digest = SHA1.HashData([.. nonce, .. Encoding.UTF8.GetBytes(created + password)]);
#pragma warning restore CA5350
securityHeader = $@"
<soap:Header>
<Security xmlns=""{WsseNs.NamespaceName}"">
<UsernameToken>
<Username>{username}</Username>
<Password Type=""{WsseNs.NamespaceName}#PasswordDigest"">{Convert.ToBase64String(digest)}</Password>
<Nonce>{Convert.ToBase64String(nonce)}</Nonce>
<Created>{created}</Created>
</UsernameToken>
</Security>
</soap:Header>";
}
else
{
securityHeader = $@"
<soap:Header>
<Security xmlns=""{WsseNs.NamespaceName}"">
<UsernameToken>
<Username>{username}</Username>
<Password Type=""{WsseNs.NamespaceName}#PasswordText"">{password}</Password>
</UsernameToken>
</Security>
</soap:Header>";
}
}
var body = operation switch
{
"GetDeviceInformation" => "<tds:GetDeviceInformation />",
"GetProfiles" => "<trt:GetProfiles />",
_ => bodyContent ?? string.Empty,
};
return $@"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope xmlns:soap=""{SoapNs.NamespaceName}""
xmlns:tds=""{TdsNs.NamespaceName}""
xmlns:trt=""{MediaNs.NamespaceName}"">{securityHeader}
<soap:Body>
{body}
</soap:Body>
</soap:Envelope>";
}
// ─── Camera evidence filtering ───────────────────────────────────
/// <summary>
/// True when the device has unambiguous camera evidence (ONVIF, HomeKit,
/// known camera vendor in the HTTP Server header, or a dedicated
/// camera/NVR port that generic appliances never expose).
/// </summary>
private static bool HasDefinitiveCameraEvidence(AgentDiscoveredDevice device)
{
if (!string.IsNullOrEmpty(device.OnvifDeviceServiceUrl)
|| !string.IsNullOrEmpty(device.OnvifHardware)
|| !string.IsNullOrEmpty(device.OnvifName))
return true;
if (!string.IsNullOrEmpty(device.HomeKitName) && !string.IsNullOrEmpty(device.HomeKitDeviceId))
return true;
var server = device.HttpServerHeader?.ToLowerInvariant() ?? string.Empty;
if (KnownCameraServers.Any(s => server.Contains(s)))
return true;
// Dedicated ports that generic appliances never open:
// 8899 Dahua NVR API, 37777 Dahua/Imou DVRIP, 34567/34568 Imou SDK,
// 8000 Hikvision SDK.
return device.OpenPorts.Any(p => p is 8899 or 37777 or 34567 or 34568 or 8000);
}
/// <summary>True when the device exposes a camera network port (RTSP/ONVIF).</summary>
private static bool HasCameraPorts(AgentDiscoveredDevice device)
=> device.OpenPorts.Any(p => p is 554 or 8554 or 3702);
private static readonly string[] KnownCameraServers =
[
"hikvision", "dahua", "imou", "lechange", "axis", "vivotek", "amcrest",
"uniview", "tp-link", "tapo", "panasonic", "bosch", "samsung", "sony",
"reolink", "annke", "ezviz", "ubiquiti", "unifi", "geovision", "avtech",
];
/// <summary>Build the candidate stream URLs for a device (shared templates).</summary>
private static List<string> BuildCandidateUrls(AgentDiscoveredDevice device, IReadOnlyList<AgentCameraCredential>? credentialPool)
{
var username = credentialPool is { Count: > 0 } ? credentialPool[0].Username : null;
var password = credentialPool is { Count: > 0 } ? credentialPool[0].Password : null;
var ids = new List<string> { "p:onvif", "p:rtsp-h264", "p:rtsp-h265", "p:mjpeg" };
var vendorKey = (device.Vendor ?? device.OnvifName)?.ToLowerInvariant();
if (vendorKey is not null && CameraStreamTemplates.StreamTemplates.ContainsKey($"b:{vendorKey}"))
ids.Insert(0, $"b:{vendorKey}");
return CameraStreamTemplates.BuildUrls(
[.. ids], device.Ip, username, password, channel: 0,
device.OpenPorts.Contains(554) ? [554] : device.OpenPorts);
}
/// <summary>
/// Test candidate stream URLs from the agent (it is on the camera LAN).
/// RTSP: OPTIONS handshake (200 or 401 = real RTSP server). HTTP: MJPEG
/// content-type check. Returns the URLs that answered.
/// </summary>
private Task<List<string>> TestStreamUrlsAsync(
AgentDiscoveredDevice device, IReadOnlyList<AgentCameraCredential>? credentialPool, CancellationToken ct)
=> TestUrlsAsync(BuildCandidateUrls(device, credentialPool), ct);
private async Task<List<string>> TestUrlsAsync(IEnumerable<string> urls, CancellationToken ct)
{
var alive = new List<string>();
using var throttler = new SemaphoreSlim(6);
var tasks = urls.Select(async url =>
{
await throttler.WaitAsync(ct).ConfigureAwait(false);
try
{
if (await IsStreamUrlAliveAsync(url, ct).ConfigureAwait(false))
lock (alive) alive.Add(url);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
// cancelled
}
catch (Exception ex)
{
_logger.LogTrace(ex, "Stream test failed for {Url}", url);
}
finally
{
throttler.Release();
}
});
await Task.WhenAll(tasks).ConfigureAwait(false);
return alive;
}
private async Task<bool> IsStreamUrlAliveAsync(string url, CancellationToken ct)
{
if (url.StartsWith("rtsp://", StringComparison.OrdinalIgnoreCase))
{
try
{
var uri = new Uri(url);
using var client = new TcpClient();
var connectTask = client.ConnectAsync(uri.Host, uri.Port, ct).AsTask();
var connected = await Task.WhenAny(connectTask, Task.Delay(RtspTimeout, ct)).ConfigureAwait(false);
if (connected != connectTask || !client.Connected)
return false;
var options = $"OPTIONS rtsp://{uri.Host}:{uri.Port}/ RTSP/1.0\r\nCSeq: 1\r\nUser-Agent: HeimdallAgent/1.0\r\n\r\n";
var stream = client.GetStream();
var bytes = Encoding.UTF8.GetBytes(options);
var sendTask = stream.WriteAsync(bytes, ct).AsTask();
var sent = await Task.WhenAny(sendTask, Task.Delay(RtspTimeout, ct)).ConfigureAwait(false);
if (sent != sendTask)
return false;
var buffer = new byte[512];
var readTask = stream.ReadAsync(buffer, ct).AsTask();
var read = await Task.WhenAny(readTask, Task.Delay(RtspTimeout, ct)).ConfigureAwait(false);
if (read != readTask)
return false;
var n = await readTask.ConfigureAwait(false);
if (n == 0)
return false;
var response = Encoding.UTF8.GetString(buffer, 0, n);
// 200 = open stream, 401 = stream exists but needs credentials.
return response.StartsWith("RTSP/1.0 200", StringComparison.OrdinalIgnoreCase)
|| response.StartsWith("RTSP/1.0 401", StringComparison.OrdinalIgnoreCase);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger.LogTrace(ex, "RTSP probe failed for {Url}", url);
return false;
}
}
if (url.StartsWith("http://", StringComparison.OrdinalIgnoreCase)
|| url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
try
{
using var handler = new HttpClientHandler { AllowAutoRedirect = true };
using var client = new HttpClient(handler) { Timeout = StreamTestTimeout };
using var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.UserAgent.ParseAdd("HeimdallAgent/1.0");
using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
return false;
var contentType = response.Content.Headers.ContentType?.MediaType?.ToLowerInvariant() ?? string.Empty;
// MJPEG endpoints advertise image/jpeg or multipart/x-mixed-replace.
return contentType.Contains("jpeg", StringComparison.Ordinal)
|| contentType.Contains("multipart", StringComparison.Ordinal)
|| contentType.Contains("mjpg", StringComparison.Ordinal);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger.LogTrace(ex, "HTTP stream probe failed for {Url}", url);
return false;
}
}
return false;
}
// ─── Network helpers ────────────────────────────────────────────────
private static (string? LocalIp, string? GatewayIp) GetLocalNetworkInfo()
{
foreach (var ni in NetworkInterface.GetAllNetworkInterfaces())
{
if (ni.OperationalStatus != OperationalStatus.Up)
continue;
foreach (var addr in ni.GetIPProperties().UnicastAddresses)
{
if (!IsCandidateNetwork(addr.Address))
continue;
var gateway = ni.GetIPProperties().GatewayAddresses
.FirstOrDefault(g => g.Address.AddressFamily == AddressFamily.InterNetwork)
?.Address.ToString();
return (addr.Address.ToString(), gateway);
}
}
return (null, null);
}
/// <summary>
/// True for a routable private IPv4 that is a plausible camera LAN.
/// Excludes loopback and common virtualisation/docker ranges
/// (172.16.0.0/12, 100.64.0.0/10) so the scanner targets the real LAN.
/// </summary>
private static bool IsCandidateNetwork(IPAddress address)
{
if (address.AddressFamily != AddressFamily.InterNetwork || IPAddress.IsLoopback(address))
return false;
var b = address.GetAddressBytes();
if (b[0] == 172 && b[1] is >= 16 and <= 31)
return false; // docker / private virtualisation
if (b[0] == 100 && b[1] is >= 64 and <= 127)
return false; // CGNAT
return true;
}
/// <summary>Return the local subnet as CIDR (e.g. 192.168.1.0/24) plus the local IP.</summary>
private (string? Cidr, string? LocalIp) GetLocalSubnetCidr()
{
foreach (var ni in NetworkInterface.GetAllNetworkInterfaces())
{
if (ni.OperationalStatus != OperationalStatus.Up)
continue;
foreach (var addr in ni.GetIPProperties().UnicastAddresses)
{
if (!IsCandidateNetwork(addr.Address))
continue;
var mask = addr.IPv4Mask;
if (mask is null)
continue;
var prefix = CountPrefixBits(mask.GetAddressBytes());
var network = NetworkAddress(addr.Address.GetAddressBytes(), mask.GetAddressBytes());
var cidr = $"{new IPAddress(network)}/{prefix}";
_logger.LogDebug("Local subnet detected: {Cidr} (interface {Interface})", cidr, ni.Name);
return (cidr, addr.Address.ToString());
}
}
return (null, null);
}
private static int CountPrefixBits(byte[] mask)
{
var count = 0;
foreach (var b in mask)
{
for (var i = 7; i >= 0; i--)
{
if ((b & (1 << i)) == 0)
return count;
count++;
}
}
return count;
}
private static byte[] NetworkAddress(byte[] ip, byte[] mask)
{
var network = new byte[4];
for (var i = 0; i < 4; i++)
network[i] = (byte)(ip[i] & mask[i]);
return network;
}
/// <summary>Expand a CIDR to host IPs (skipping network/broadcast, capped at 65 536).</summary>
internal static List<string> ExpandSubnet(string subnetCidr)
{
var parts = subnetCidr.Split('/');
if (parts.Length != 2)
return [];
if (!IPAddress.TryParse(parts[0], out var ip))
return [];
if (!int.TryParse(parts[1], out var prefixLength) || prefixLength is < 0 or > 32)
return [];
var ipBytes = ip.GetAddressBytes();
if (BitConverter.IsLittleEndian)
Array.Reverse(ipBytes);
var uintIp = BitConverter.ToUInt32(ipBytes, 0);
uint mask;
long hostCount;
int startOffset;
if (prefixLength >= 32)
{
mask = uint.MaxValue;
hostCount = 1;
startOffset = 0;
}
else if (prefixLength == 31)
{
mask = uint.MaxValue << 1;
hostCount = 2;
startOffset = 0;
}
else
{
mask = uint.MaxValue << (32 - prefixLength);
hostCount = (1L << (32 - prefixLength)) - 2;
startOffset = 1;
}
if (hostCount < 0)
hostCount = 0;
if (hostCount > 65536)
hostCount = 65536;
var network = uintIp & mask;
var ips = new List<string>((int)hostCount);
for (var i = 0; i < hostCount; i++)
{
var hostIp = network + (uint)(i + startOffset);
var bytes = BitConverter.GetBytes(hostIp);
if (BitConverter.IsLittleEndian)
Array.Reverse(bytes);
ips.Add(new IPAddress(bytes).ToString());
}
return ips;
}
/// <summary>Read the ARP table (/proc/net/arp) to resolve an IP's MAC address.</summary>
private static string? GetArpMac(string ip)
{
try
{
var lines = File.ReadAllLines("/proc/net/arp");
foreach (var line in lines.Skip(1))
{
var fields = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (fields.Length >= 4 && fields[0] == ip && fields[3] != "00:00:00:00:00:00")
return fields[3];
}
}
catch (Exception)
{
// ARP table unavailable (non-Linux or restricted container) — best effort.
}
return null;
}
private sealed record HttpProbe(int Port, int StatusCode, string? ServerHeader);
private sealed record OnvifProbe(
string DeviceServiceUrl, string? Name, string? Hardware, string? CredentialLabel = null,
string[]? StreamUrls = null);
private sealed record OnvifDetail(string? Manufacturer, string? Model, string? CredentialLabel = null);
}