fix(agent): camera discovery — host-network compose, parasite filtering, auto stream detection
- Compose (dev+prod): agent on host network (bridge 172.x was skipped by the scanner), listen on 8081 (ntfy owns 8080), CentralUrl via host/domain, healthcheck adapted, no Docker DNS - Scanner: skip the LAN gateway (NAT router, never a camera); wider camera ports (+34567/34568 Imou SDK, +8000 Hikvision SDK); 750 ms port timeout; keep only devices with real camera evidence; RTSP OPTIONS + MJPEG content-type probes prove live streams from the agent (it is on the LAN) - Central: drop Unknown devices (nginx/gunicorn/gateway) on submit; classify 37777 DVRIP as Standard camera (not NVR), 8899 alone as NVR; persist agent-tested stream URLs flagged IsAlive; shared CameraStreamTemplates with the agent so both build identical candidate URLs - UI: discoveries popup auto-selects the agent-verified main stream — no manual stream choice
This commit is contained in:
1 parent
0136bf33ec
commit
ddfa22bee6
8 files changed
+357
-90
No files matched your search
@@ -6,6 +6,7 @@ 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;
|
||||
|
||||
@@ -25,9 +26,11 @@ namespace Heimdall.Agent.Services;
|
||||
/// </summary>
|
||||
public sealed class NetworkCameraScanner
|
||||
{
|
||||
private static readonly int[] CameraPorts = [80, 443, 554, 8554, 3702, 8899, 37777];
|
||||
private static readonly TimeSpan PortTimeout = TimeSpan.FromMilliseconds(250);
|
||||
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
|
||||
@@ -45,11 +48,14 @@ public sealed class NetworkCameraScanner
|
||||
|
||||
private readonly ILogger<NetworkCameraScanner> _logger;
|
||||
private readonly string? _localIp;
|
||||
private readonly string? _gatewayIp;
|
||||
|
||||
public NetworkCameraScanner(ILogger<NetworkCameraScanner> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
_localIp = GetLocalIpv4();
|
||||
var (localIp, gatewayIp) = GetLocalNetworkInfo();
|
||||
_localIp = localIp;
|
||||
_gatewayIp = gatewayIp;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -79,14 +85,37 @@ public sealed class NetworkCameraScanner
|
||||
var tasks = ips.Select(async ip =>
|
||||
{
|
||||
if (ct.IsCancellationRequested) return;
|
||||
if (ip == localIp) 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 not null)
|
||||
results.Add(device);
|
||||
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)
|
||||
{
|
||||
@@ -377,9 +406,174 @@ public sealed class NetworkCameraScanner
|
||||
</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? GetLocalIpv4()
|
||||
private static (string? LocalIp, string? GatewayIp) GetLocalNetworkInfo()
|
||||
{
|
||||
foreach (var ni in NetworkInterface.GetAllNetworkInterfaces())
|
||||
{
|
||||
@@ -387,11 +581,16 @@ public sealed class NetworkCameraScanner
|
||||
continue;
|
||||
foreach (var addr in ni.GetIPProperties().UnicastAddresses)
|
||||
{
|
||||
if (IsCandidateNetwork(addr.Address))
|
||||
return addr.Address.ToString();
|
||||
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;
|
||||
return (null, null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
Reference in new issue
Block a user