feat(agent): ONVIF WS-Discovery multicast camera discovery
Fixes #54 The agent now sends one UDP multicast probe (239.255.255.250:3702) per scan and collects ONVIF replies for ~5s, instead of relying solely on the per-IP TCP port sweep. This finds every ONVIF camera on the LAN — even those with TCP 3702 closed — in one request, with name/hardware from the WS-Discovery scopes (and the buggy 0.0.0.0 XAddrs fix). - ScanAsync runs the broadcast probes in parallel with the TCP sweep and merges results (dedupe by IP) - Factorized BuildFinalDeviceAsync (evidence filter + live stream test) shared by the TCP sweep and the multicast merge - Transposed from go2rtc pkg/onvif DiscoveryStreamingDevices
This commit is contained in:
1 parent
ddfa22bee6
commit
1bc4c73f23
1 file changed
+199
-21
@@ -82,6 +82,11 @@ public sealed class NetworkCameraScanner
|
||||
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;
|
||||
@@ -95,27 +100,9 @@ public sealed class NetworkCameraScanner
|
||||
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.
|
||||
var final = await BuildFinalDeviceAsync(device, credentialPool, ct).ConfigureAwait(false);
|
||||
if (final is not null)
|
||||
results.Add(final);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
@@ -132,11 +119,202 @@ public sealed class NetworkCameraScanner
|
||||
});
|
||||
|
||||
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;
|
||||
|
||||
// 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)
|
||||
return device with { StreamUrls = [.. alive] };
|
||||
|
||||
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(ct).ConfigureAwait(false));
|
||||
return devices;
|
||||
}
|
||||
|
||||
/// <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(CancellationToken ct)
|
||||
{
|
||||
var devices = new List<AgentDiscoveredDevice>();
|
||||
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..];
|
||||
|
||||
var name = FindScope(doc, "onvif://www.onvif.org/name/");
|
||||
var hardware = FindScope(doc, "onvif://www.onvif.org/hardware/");
|
||||
|
||||
devices.Add(new AgentDiscoveredDevice(
|
||||
Ip: result.RemoteEndPoint.Address.ToString(),
|
||||
IsReachable: true,
|
||||
OpenPorts: [],
|
||||
MacAddress: null,
|
||||
Vendor: null,
|
||||
Hostname: name,
|
||||
HttpServerHeader: null,
|
||||
HttpStatusCode: null,
|
||||
HttpPort: null,
|
||||
OnvifDeviceServiceUrl: serviceUrl,
|
||||
OnvifName: name,
|
||||
OnvifHardware: hardware,
|
||||
OnvifPort: 3702,
|
||||
HomeKitName: null,
|
||||
HomeKitDeviceId: null,
|
||||
HomeKitModel: null,
|
||||
CredentialLabel: null,
|
||||
StreamUrls: null));
|
||||
}
|
||||
|
||||
if (devices.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)
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user