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

745 lines
31 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.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 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);
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;
// 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;
// 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 alive = await TestStreamUrlsAsync(device, credentialPool, ct).ConfigureAwait(false);
if (alive.Count > 0)
{
results.Add(device with { StreamUrls = [.. alive] });
}
else 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)
results.Add(device with { StreamUrls = [.. fallback] });
}
// else: camera ports open but no live stream → not usable, skip.
}
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);
_logger.LogInformation("Camera discovery: {Found} candidate device(s) on {Subnet}", results.Count, subnetCidr);
return results.ToList();
}
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);
}
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);
return new OnvifProbe(deviceServiceUrl, detail?.Manufacturer, detail?.Model, detail?.CredentialLabel);
}
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 soap = BuildSoapEnvelope(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);
var doc = XDocument.Parse(responseXml);
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>
/// Build the GetDeviceInformation SOAP envelope, adding a WS-Security
/// UsernameToken when credentials are provided (PasswordDigest or
/// PasswordText, matching ONVIF interop requirements).
/// </summary>
private static string BuildSoapEnvelope(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>";
}
}
return $@"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope xmlns:soap=""{SoapNs.NamespaceName}""
xmlns:tds=""{TdsNs.NamespaceName}"">{securityHeader}
<soap:Body>
<tds:GetDeviceInformation />
</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 async Task<List<string>> TestStreamUrlsAsync(
AgentDiscoveredDevice device, IReadOnlyList<AgentCameraCredential>? credentialPool, CancellationToken ct)
{
var urls = BuildCandidateUrls(device, credentialPool);
if (urls.Count == 0)
return [];
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);
private sealed record OnvifDetail(string? Manufacturer, string? Model, string? CredentialLabel = null);
}