diff --git a/src/Heimdall.Agent/Services/NetworkCameraScanner.cs b/src/Heimdall.Agent/Services/NetworkCameraScanner.cs index 85a3606..6d1e4ab 100644 --- a/src/Heimdall.Agent/Services/NetworkCameraScanner.cs +++ b/src/Heimdall.Agent/Services/NetworkCameraScanner.cs @@ -82,6 +82,11 @@ public sealed class NetworkCameraScanner var results = new ConcurrentBag(); 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(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(); } + /// + /// Apply the camera-evidence filter + live stream test to a probed device and + /// return it with its final , + /// or null when the device is not a usable camera. + /// + private async Task BuildFinalDeviceAsync( + AgentDiscoveredDevice device, IReadOnlyList? 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; + } + + /// + /// 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. + /// + private async Task> DiscoverByBroadcastAsync( + IReadOnlyList? credentialPool, CancellationToken ct) + { + var devices = new List(); + devices.AddRange(await DiscoverOnvifMulticastAsync(ct).ConfigureAwait(false)); + return devices; + } + + /// + /// 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. + /// + private async Task> DiscoverOnvifMulticastAsync(CancellationToken ct) + { + var devices = new List(); + try + { + using var udp = new UdpClient(); + var messageId = Guid.NewGuid().ToString(); + var probe = $@" + + + {WsdNs.NamespaceName}/Probe + uuid:{messageId} + urn:schemas-xmlsoap-org:ws:2005:04:discovery + + + + tdn:NetworkVideoTransmitter + + +"; + + 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: http://0.0.0.0:8080/onvif/device_service + 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; + } + + /// Extract an ONVIF scope value by prefix (e.g. onvif://www.onvif.org/name/). + 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 ProbeHostAsync( string ip, IReadOnlyList? credentialPool, CancellationToken ct) {