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; /// /// 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 /// authenticated 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. /// public sealed class NetworkCameraScanner { // Ports probés sur chaque hôte (Strix defaultPorts + ports Heimdall déjà // connus) : 554/8554/5544/10554/7070/7447 RTSP, 80/81/88/8080/8081/8090/8000/8001 HTTP/SDK, // 1935 RTMP, 3702 ONVIF WS-Discovery, 8899 Dahua NVR API, 37777/34567/34568 DVRIP/Imou SDK, // 51826 Hikvision SDK. private static readonly int[] CameraPorts = [80, 81, 88, 443, 554, 1935, 3702, 5544, 7070, 7447, 8000, 8001, 8080, 8081, 8090, 8554, 8899, 10554, 34567, 34568, 37777, 51826]; 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); private static readonly TimeSpan ReverseDnsTimeout = TimeSpan.FromMilliseconds(500); private static readonly TimeSpan DvripTimeout = TimeSpan.FromSeconds(3); private static readonly TimeSpan ScreenshotTimeout = TimeSpan.FromSeconds(6); private const int MaxScreenshotBytes = 512 * 1024; // 512 KB max per frame // 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 _logger; private readonly HomeKitMdnsProbe _homeKitProbe; private readonly ICameraDatabase? _cameraDatabase; private readonly string? _localIp; private readonly string? _gatewayIp; public NetworkCameraScanner( ILogger logger, ILoggerFactory loggerFactory, HomeKitMdnsProbe? homeKitProbe = null, ICameraDatabase? cameraDatabase = null) { _logger = logger; _homeKitProbe = homeKitProbe ?? new HomeKitMdnsProbe(loggerFactory.CreateLogger()); _cameraDatabase = cameraDatabase; var (localIp, gatewayIp) = GetLocalNetworkInfo(); _localIp = localIp; _gatewayIp = gatewayIp; } /// /// Scan the local subnet for camera-like devices. Returns an empty list /// when the local network cannot be determined. When /// 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. /// public async Task> ScanAsync( CancellationToken ct, IReadOnlyList? 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(); using var throttler = new SemaphoreSlim(40); // Broadcast/multicast probes (ONVIF WS-Discovery, DVRIP, HomeKit mDNS) 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("Probe error for {Ip} (error type {ErrorType})", ip, ex.GetType().Name); } finally { throttler.Release(); } }); await Task.WhenAll(tasks).ConfigureAwait(false); // Merge multicast/broadcast-discovered devices, preserving HomeKit // advertisement data even when the TCP sweep found that IP first. var mergedResults = results.ToList(); var resultIndexes = mergedResults .Select((device, index) => (device.Ip, index)) .ToDictionary(x => x.Ip, x => x.index, StringComparer.Ordinal); foreach (var device in await broadcastTask.ConfigureAwait(false)) { if (device.Ip == localIp || device.Ip == _gatewayIp) continue; if (resultIndexes.TryGetValue(device.Ip, out var existingIndex)) { // A TCP scan may have found the host first. Keep the mDNS // HomeKit metadata, which is the authoritative category and // pairing information for these accessories. if (!string.IsNullOrEmpty(device.HomeKitName)) mergedResults[existingIndex] = mergedResults[existingIndex] with { HomeKitName = device.HomeKitName, HomeKitDeviceId = device.HomeKitDeviceId, HomeKitModel = device.HomeKitModel, HomeKitCategory = device.HomeKitCategory, HomeKitIsPaired = device.HomeKitIsPaired, HomeKitPort = device.HomeKitPort, StreamUrls = null, ScreenshotBase64 = null, CredentialLabel = null }; continue; } var final = await BuildFinalDeviceAsync(device, credentialPool, ct).ConfigureAwait(false); if (final is not null) { resultIndexes.Add(device.Ip, mergedResults.Count); mergedResults.Add(final); } } _logger.LogInformation("Camera discovery: {Found} candidate device(s) on {Subnet}", mergedResults.Count, subnetCidr); return mergedResults; } /// /// 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) { // HomeKit accessories are proven by the mDNS advertisement (category // ci=17/18): no RTSP candidates apply — the stream is a HAP session // (GetImage snapshot test, ticket #67/#65), never a guessed rtsp:// URL. if (!string.IsNullOrEmpty(device.HomeKitName)) return device; // 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); var screenshot = device.ScreenshotBase64 is null && alive.Count > 0 ? await CaptureScreenshotAsync(alive[0], ct).ConfigureAwait(false) : device.ScreenshotBase64; return device with { StreamUrls = alive.Count > 0 ? [.. alive] : device.StreamUrls, ScreenshotBase64 = screenshot, }; } // 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) { var screenshot = device.ScreenshotBase64 is null ? await CaptureScreenshotAsync(tested[0], ct).ConfigureAwait(false) : device.ScreenshotBase64; return device with { StreamUrls = [.. tested], ScreenshotBase64 = screenshot }; } 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(credentialPool, ct).ConfigureAwait(false)); devices.AddRange(await DiscoverDvripAsync(ct).ConfigureAwait(false)); devices.AddRange(await DiscoverHomeKitAsync(ct).ConfigureAwait(false)); return devices; } /// /// HomeKit accessory discovery via mDNS multicast (_hap._tcp.local, /// 224.0.0.251:5353). Only camera (ci=17) and doorbell (ci=18) categories /// are kept; the HomeKit* fields of the device are filled for the Central /// ClassifyAgentDevice HomeKit path. /// internal async Task> DiscoverHomeKitAsync(CancellationToken ct) { var devices = new List(); try { var found = await _homeKitProbe.DiscoverAsync(ct).ConfigureAwait(false); foreach (var accessory in found) { devices.Add(new AgentDiscoveredDevice( Ip: accessory.Ip, IsReachable: true, OpenPorts: accessory.Port > 0 ? [accessory.Port] : [], MacAddress: null, Vendor: "Apple", Hostname: accessory.Name, HttpServerHeader: null, HttpStatusCode: null, HttpPort: null, OnvifDeviceServiceUrl: null, OnvifName: null, OnvifHardware: null, OnvifPort: null, HomeKitName: accessory.Name, HomeKitDeviceId: accessory.DeviceId, HomeKitModel: accessory.Model, CredentialLabel: null, StreamUrls: null, HomeKitCategory: accessory.Category, HomeKitIsPaired: accessory.IsPaired, HomeKitPort: accessory.Port)); } } catch (Exception ex) { _logger.LogWarning("HomeKit mDNS discovery failed (error type {ErrorType})", ex.GetType().Name); } return devices; } /// /// 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. /// private async Task> DiscoverDvripAsync(CancellationToken ct) { var devices = new List(); 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); } // Socket.ReceiveTimeout does NOT apply to async ReceiveAsync — // enforce the window explicitly or the scan hangs forever. var listenUntil = DateTime.UtcNow + TimeSpan.FromSeconds(2); while (!ct.IsCancellationRequested && DateTime.UtcNow < listenUntil) { UdpReceiveResult result; var receiveTask = udp.ReceiveAsync(ct).AsTask(); var completed = await Task.WhenAny(receiveTask, Task.Delay(TimeSpan.FromSeconds(2), ct)).ConfigureAwait(false); if (completed != receiveTask) break; // no more replies expected result = await receiveTask.ConfigureAwait(false); 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("DVRIP discovery failed (error type {ErrorType})", ex.GetType().Name); } 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; /// /// 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( IReadOnlyList? credentialPool, CancellationToken ct) { var devices = new List(); 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 = $@" {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); // Socket.ReceiveTimeout does NOT apply to async ReceiveAsync — // enforce the window explicitly or the scan hangs forever. var listenUntil = DateTime.UtcNow + TimeSpan.FromSeconds(5); while (!ct.IsCancellationRequested && DateTime.UtcNow < listenUntil) { UdpReceiveResult result; var receiveTask = udp.ReceiveAsync(ct).AsTask(); var completed = await Task.WhenAny(receiveTask, Task.Delay(TimeSpan.FromSeconds(5), ct)).ConfigureAwait(false); if (completed != receiveTask) break; // no more replies expected result = await receiveTask.ConfigureAwait(false); 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..]; 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("ONVIF WS-Discovery multicast failed (error type {ErrorType})", ex.GetType().Name); } 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) { 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); // Reverse DNS as a fallback hostname (ONVIF/DVRIP/mDNS names win). var hostname = onvif?.Name is null ? await ResolveHostnameAsync(ip, ct).ConfigureAwait(false) : null; return new AgentDiscoveredDevice( Ip: ip, IsReachable: true, OpenPorts: [.. openPorts], MacAddress: mac, Vendor: null, Hostname: hostname, 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> ScanPortsAsync(string ip, CancellationToken ct) { var open = new ConcurrentBag(); var tasks = CameraPorts.Select(async port => { using var client = new TcpClient(); if (await ConnectWithTimeoutAsync( token => client.ConnectAsync(IPAddress.Parse(ip), port, token), PortTimeout, ct) .ConfigureAwait(false)) open.Add(port); }); await Task.WhenAll(tasks).ConfigureAwait(false); return [.. open.Order()]; } internal static async Task ConnectWithTimeoutAsync( Func connectAsync, TimeSpan timeout, CancellationToken cancellationToken) { using var timeoutSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); timeoutSource.CancelAfter(timeout); try { await connectAsync(timeoutSource.Token).ConfigureAwait(false); return true; } catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) { return false; } catch (SocketException) { return false; } } private async Task 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("HTTP probe failed for {Ip}:{Port} (error type {ErrorType})", ip, port, ex.GetType().Name); return null; } } private async Task ProbeOnvifAsync( string ip, int port, IReadOnlyList? credentialPool, CancellationToken ct) { try { using var udp = new UdpClient(); udp.Connect(ip, port); var messageId = Guid.NewGuid().ToString(); var probe = $@" {WsdNs.NamespaceName}/Probe uuid:{messageId} urn:schemas-xmlsoap-org:ws:2005:04:discovery tdn:NetworkVideoTransmitter "; await udp.SendAsync(Encoding.UTF8.GetBytes(probe), ct).ConfigureAwait(false); // Socket.ReceiveTimeout does NOT apply to async ReceiveAsync — // enforce the window explicitly or the probe hangs forever. var receiveTask = udp.ReceiveAsync(ct).AsTask(); var completed = await Task.WhenAny(receiveTask, Task.Delay(OnvifUdpTimeout, ct)).ConfigureAwait(false); if (completed != receiveTask) return null; var result = await receiveTask.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("ONVIF probe failed for {Ip}:{Port} (error type {ErrorType})", ip, port, ex.GetType().Name); return null; } } /// /// 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. /// private async Task GetDeviceInformationWithCredentialsAsync( string deviceServiceUrl, IReadOnlyList? 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}'", credential.Label); 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}'", credential.Label); return text with { CredentialLabel = credential.Label }; } } } return null; } private async Task 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("GetDeviceInformation failed for [camera endpoint]"); return null; } } /// /// 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. /// private async Task GetStreamUrisWithCredentialsAsync( string deviceServiceUrl, IReadOnlyList? 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 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(); foreach (var token in tokens) { var body = $"RTP-Unicast" + $"RTSP" + $"{token}"; 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("GetStreamUri failed for [camera endpoint]"); return []; } } /// /// 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. /// 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; } } /// POST a SOAP operation to an ONVIF service and parse the response. private static async Task 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); } /// /// Build a SOAP envelope for an ONVIF operation, adding a WS-Security /// UsernameToken when credentials are provided (PasswordDigest or /// PasswordText, matching ONVIF interop requirements). /// 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 = $@" {username} {Convert.ToBase64String(digest)} {Convert.ToBase64String(nonce)} {created} "; } else { securityHeader = $@" {username} {password} "; } } var body = operation switch { "GetDeviceInformation" => "", "GetProfiles" => "", _ => bodyContent ?? string.Empty, }; return $@" {securityHeader} {body} "; } // ─── Camera evidence filtering ─────────────────────────────────── /// /// 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). /// 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); } /// True when the device exposes a camera network port (RTSP/ONVIF). 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", ]; /// Build the candidate stream URLs for a device (shared templates). private List BuildCandidateUrls(AgentDiscoveredDevice device, IReadOnlyList? 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 { "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}"); // DVRIP devices (Dahua/Imou with 37777/34567/34568 open) get a dvrip:// candidate. if (device.OpenPorts.Any(p => p is 34567 or 34568 or 37777) && !ids.Contains("p:dvrrip")) ids.Insert(0, "p:dvrrip"); // StrixCamDB: prefer the real brand stream patterns when the vendor is // known (e.g. b:hikvision → real Hikvision URL patterns, not just // generic templates). Falls back to the shared templates otherwise. if (_cameraDatabase?.IsAvailable == true && vendorKey is not null) { var dbIds = new List { $"b:{vendorKey}" }; var dbUrls = _cameraDatabase.BuildStreams( [.. dbIds], device.Ip, username, password, channel: 0, device.OpenPorts.Length > 0 ? device.OpenPorts : null); if (dbUrls.Count > 0) return [.. dbUrls]; } return CameraStreamTemplates.BuildUrls( [.. ids], device.Ip, username, password, channel: 0, device.OpenPorts.Length > 0 ? device.OpenPorts : null); } /// /// 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. /// private Task> TestStreamUrlsAsync( AgentDiscoveredDevice device, IReadOnlyList? credentialPool, CancellationToken ct) => TestUrlsAsync(BuildCandidateUrls(device, credentialPool), ct); private async Task> TestUrlsAsync(IEnumerable urls, CancellationToken ct) { var alive = new List(); 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) { _logger.LogTrace("Stream test failed for [camera endpoint]"); } finally { throttler.Release(); } }); await Task.WhenAll(tasks).ConfigureAwait(false); return alive; } internal async Task IsStreamUrlAliveAsync(string url, CancellationToken ct) { if (url.StartsWith("dvrip://", StringComparison.OrdinalIgnoreCase)) return await IsDvripUrlAliveAsync(url, ct).ConfigureAwait(false); if (url.StartsWith("rtmp://", StringComparison.OrdinalIgnoreCase) || url.StartsWith("rtmps://", StringComparison.OrdinalIgnoreCase)) return await IsRtmpUrlAliveAsync(url, ct).ConfigureAwait(false); if (url.StartsWith("bubble://", StringComparison.OrdinalIgnoreCase)) return await IsBubbleUrlAliveAsync(url, ct).ConfigureAwait(false); if (url.StartsWith("homekit://", StringComparison.OrdinalIgnoreCase)) return await IsHomeKitUrlAliveAsync(url, ct).ConfigureAwait(false); if (url.StartsWith("rtsp://", StringComparison.OrdinalIgnoreCase)) { try { var uri = new Uri(url); using var client = new TcpClient(); if (!await ConnectWithTimeoutAsync( token => client.ConnectAsync(uri.Host, uri.Port, token), RtspTimeout, ct) .ConfigureAwait(false)) 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("RTSP probe failed for [camera endpoint]"); 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("HTTP stream probe failed for [camera endpoint]"); return false; } } return false; } // ─── DVRIP (Dahua/Imou) ────────────────────────────────────────────── /// /// Test a dvrip:// URL by performing the DVRIP login handshake (Sofia MD5 /// hash, DVRIP-Web login type). Transposed from go2rtc pkg/dvrip/client.go: /// the login itself proves the stream credentials and channel work — a /// camera that answers Ret=100/515 is a live DVRIP camera. /// private async Task IsDvripUrlAliveAsync(string url, CancellationToken ct) { try { var uri = new Uri(url); var host = uri.Host; var port = uri.IsDefaultPort ? 34567 : uri.Port; var credentials = uri.UserInfo.Split(':', 2); var username = credentials.Length > 0 ? Uri.UnescapeDataString(credentials[0]) : "admin"; var password = credentials.Length > 1 ? Uri.UnescapeDataString(credentials[1]) : ""; using var client = new TcpClient(); if (!await ConnectWithTimeoutAsync( token => client.ConnectAsync(host, port, token), DvripTimeout, ct) .ConfigureAwait(false)) return false; var stream = client.GetStream(); // Login request: {"EncryptType":"MD5","LoginType":"DVRIP-Web","PassWord":"","UserName":""}\x0A\x00 var payload = "{\"EncryptType\":\"MD5\",\"LoginType\":\"DVRIP-Web\",\"PassWord\":\"" + SofiaHash(password) + "\",\"UserName\":\"" + username + "\"}\x0A\x00"; var packet = BuildDvripPacket(payload, cmd: 1000, session: 0, seq: 0); var writeTask = stream.WriteAsync(packet, ct).AsTask(); var written = await Task.WhenAny(writeTask, Task.Delay(DvripTimeout, ct)).ConfigureAwait(false); if (written != writeTask) return false; await writeTask.ConfigureAwait(false); // Response header (20 bytes): [0]=0xFF, [4..7]=session, [8..11]=seq, // [14..15]=cmd, [16..19]=payload length. var header = new byte[20]; var headerRead = await ReadExactWithTimeoutAsync(stream, header, DvripTimeout, ct).ConfigureAwait(false); if (!headerRead || header[0] != 0xFF) return false; var size = BitConverter.ToUInt32(header, 16); if (size is 0 or > 1_000_000) return false; var body = new byte[size]; var bodyRead = await ReadExactWithTimeoutAsync(stream, body, DvripTimeout, ct).ConfigureAwait(false); if (!bodyRead) return false; // Response JSON ends with \x0A\x00; parse and check Ret == 100 (OK) or 515 (already logged in). var jsonText = Encoding.UTF8.GetString(body); var trimmed = jsonText.TrimEnd('\0', '\n', '\r'); using var doc = JsonDocument.Parse(trimmed); if (doc.RootElement.TryGetProperty("Ret", out var retEl) && retEl.TryGetInt32(out var ret)) { if (ret is 100 or 515) { _logger.LogDebug("DVRIP login OK for [camera endpoint]"); return true; } _logger.LogDebug("DVRIP login rejected (Ret={Ret}) for [camera endpoint]", ret); } return false; } catch (Exception ex) when (ex is not OperationCanceledException) { _logger.LogTrace("DVRIP probe failed for [camera endpoint]"); return false; } } /// Build a DVRIP packet: 20-byte header + JSON payload. private static byte[] BuildDvripPacket(string payload, int cmd, uint session, uint seq) { var payloadBytes = Encoding.UTF8.GetBytes(payload); var packet = new byte[20 + payloadBytes.Length]; packet[0] = 0xFF; BitConverter.TryWriteBytes(packet.AsSpan(4, 4), session); BitConverter.TryWriteBytes(packet.AsSpan(8, 4), seq); BitConverter.TryWriteBytes(packet.AsSpan(14, 2), (ushort)cmd); BitConverter.TryWriteBytes(packet.AsSpan(16, 4), (uint)payloadBytes.Length); Array.Copy(payloadBytes, 0, packet, 20, payloadBytes.Length); return packet; } /// /// Sofia MD5 hash (Dahua/Imou DVRIP): md5(password) then map each byte /// pair to one of 62 alphanumeric chars. Transposed from go2rtc /// pkg/dvrip/client.go SofiaHash. /// private static string SofiaHash(string password) { const string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // MD5 is mandated by the Dahua/Imou DVRIP protocol (Sofia hash) — it is // a wire-format requirement, not used for application security. #pragma warning disable CA5351 // Do Not Use Broken Cryptographic Algorithms var hash = MD5.HashData(Encoding.UTF8.GetBytes(password)); #pragma warning restore CA5351 var sb = new StringBuilder(8); for (var i = 0; i < hash.Length; i += 2) { var j = (ushort)(hash[i] + hash[i + 1]); sb.Append(chars[j % 62]); } return sb.ToString(); } /// Read exactly .Length bytes with a timeout (Task.WhenAny, never Socket.ReceiveTimeout on async). private static async Task ReadExactWithTimeoutAsync( NetworkStream stream, byte[] buffer, TimeSpan timeout, CancellationToken ct) { var offset = 0; while (offset < buffer.Length) { var readTask = stream.ReadAsync(buffer.AsMemory(offset), ct).AsTask(); var completed = await Task.WhenAny(readTask, Task.Delay(timeout, ct)).ConfigureAwait(false); if (completed != readTask) return false; var n = await readTask.ConfigureAwait(false); if (n == 0) return false; offset += n; } return true; } // ─── RTMP / Bubble / HomeKit ───────────────────────────────────────── /// /// Minimal RTMP liveness check: TCP connect + C0/C1 handshake. A real RTMP /// server answers C0 (0x03) + C1 (1536 bytes) — receiving C0 proves the /// server speaks RTMP on that port. /// private async Task IsRtmpUrlAliveAsync(string url, CancellationToken ct) { try { var uri = new Uri(url); var port = uri.IsDefaultPort ? 1935 : uri.Port; using var client = new TcpClient(); if (!await ConnectWithTimeoutAsync( token => client.ConnectAsync(uri.Host, port, token), DvripTimeout, ct) .ConfigureAwait(false)) return false; var stream = client.GetStream(); // C0 (version 3) + C1 (timestamp 0 + zero + random 1528 bytes). var c01 = new byte[1 + 1536]; c01[0] = 0x03; RandomNumberGenerator.Fill(c01.AsSpan(9)); var writeTask = stream.WriteAsync(c01, ct).AsTask(); var written = await Task.WhenAny(writeTask, Task.Delay(DvripTimeout, ct)).ConfigureAwait(false); if (written != writeTask) return false; await writeTask.ConfigureAwait(false); // Server must answer C0 (1 byte) + C1 (1536 bytes). var c0 = new byte[1]; var readTask = stream.ReadAsync(c0, ct).AsTask(); var read = await Task.WhenAny(readTask, Task.Delay(DvripTimeout, ct)).ConfigureAwait(false); if (read != readTask) return false; var n = await readTask.ConfigureAwait(false); if (n == 0) return false; var c1 = new byte[1536]; var c1Read = await ReadExactWithTimeoutAsync(stream, c1, DvripTimeout, ct).ConfigureAwait(false); var alive = c0[0] == 0x03 && c1Read; _logger.LogDebug("RTMP probe {Result} for [camera endpoint]", alive ? "OK" : "failed"); return alive; } catch (Exception ex) when (ex is not OperationCanceledException) { _logger.LogTrace("RTMP probe failed for [camera endpoint]"); return false; } } /// /// Bubble (Uniview) liveness check: TCP connect + HTTP GET with the Bubble /// binary preamble. A real Bubble server answers with an HTTP response. /// private async Task IsBubbleUrlAliveAsync(string url, CancellationToken ct) { try { var uri = new Uri(url); var port = uri.IsDefaultPort ? 80 : uri.Port; var path = string.IsNullOrEmpty(uri.AbsolutePath) ? "/bubble/live?ch=0&stream=0" : uri.PathAndQuery; using var client = new TcpClient(); if (!await ConnectWithTimeoutAsync( token => client.ConnectAsync(uri.Host, port, token), DvripTimeout, ct) .ConfigureAwait(false)) return false; var stream = client.GetStream(); // Bubble frames the HTTP request with a binary preamble // (0x01 0x00 0x00 0x00 + length) — same as go2rtc pkg/bubble. var httpRequest = $"GET {path} HTTP/1.1\r\nHost: {uri.Host}\r\nUser-Agent: HeimdallAgent/1.0\r\n\r\n"; var httpBytes = Encoding.ASCII.GetBytes(httpRequest); var frame = new byte[8 + httpBytes.Length]; frame[0] = 0x01; frame[4] = (byte)(httpBytes.Length & 0xFF); frame[5] = (byte)((httpBytes.Length >> 8) & 0xFF); Array.Copy(httpBytes, 0, frame, 8, httpBytes.Length); var writeTask = stream.WriteAsync(frame, ct).AsTask(); var written = await Task.WhenAny(writeTask, Task.Delay(DvripTimeout, ct)).ConfigureAwait(false); if (written != writeTask) return false; await writeTask.ConfigureAwait(false); var buffer = new byte[512]; var readTask = stream.ReadAsync(buffer, ct).AsTask(); var read = await Task.WhenAny(readTask, Task.Delay(DvripTimeout, ct)).ConfigureAwait(false); if (read != readTask) return false; var n = await readTask.ConfigureAwait(false); if (n == 0) return false; var response = Encoding.ASCII.GetString(buffer, 0, n); // Skip the binary preamble in the response, look for the HTTP status. var httpIndex = response.IndexOf("HTTP/1.", StringComparison.Ordinal); var alive = httpIndex >= 0 && response.AsSpan(httpIndex).StartsWith("HTTP/1.1 200", StringComparison.OrdinalIgnoreCase); _logger.LogDebug("Bubble probe {Result} for [camera endpoint]", alive ? "OK" : "failed"); return alive; } catch (Exception ex) when (ex is not OperationCanceledException) { _logger.LogTrace("Bubble probe failed for [camera endpoint]"); return false; } } /// /// HomeKit liveness check: TCP connect to the HAP port + GET /accessories. /// The HAP HTTP server answers even to unpaired clients (401 + pairing /// required is still a HAP service on that port). Best-effort — the mDNS /// advertisement already proved the accessory exists. /// private async Task IsHomeKitUrlAliveAsync(string url, CancellationToken ct) { try { var uri = new Uri(url); var port = uri.IsDefaultPort ? 8080 : uri.Port; using var client = new TcpClient(); if (!await ConnectWithTimeoutAsync( token => client.ConnectAsync(uri.Host, port, token), DvripTimeout, ct) .ConfigureAwait(false)) return false; var stream = client.GetStream(); var request = $"GET /accessories HTTP/1.1\r\nHost: {uri.Host}\r\n\r\n"; var writeTask = stream.WriteAsync(Encoding.ASCII.GetBytes(request), ct).AsTask(); var written = await Task.WhenAny(writeTask, Task.Delay(DvripTimeout, ct)).ConfigureAwait(false); if (written != writeTask) return false; await writeTask.ConfigureAwait(false); var buffer = new byte[512]; var readTask = stream.ReadAsync(buffer, ct).AsTask(); var read = await Task.WhenAny(readTask, Task.Delay(DvripTimeout, ct)).ConfigureAwait(false); if (read != readTask) return false; var n = await readTask.ConfigureAwait(false); if (n == 0) return false; var response = Encoding.ASCII.GetString(buffer, 0, n); // 200, 401 (pairing required) and 470 (auth required) all prove a live HAP service. var alive = response.StartsWith("HTTP/1.1", StringComparison.OrdinalIgnoreCase); _logger.LogDebug("HomeKit probe {Result} for [camera endpoint] ({Response})", alive ? "OK" : "failed", response.Split('\r')[0]); return alive; } catch (Exception ex) when (ex is not OperationCanceledException) { _logger.LogTrace("HomeKit probe failed for [camera endpoint]"); return false; } } // ─── Screenshot capture ────────────────────────────────────────────── /// /// Capture one JPEG frame from a stream URL with ffmpeg (the agent image /// ships ffmpeg). Best-effort: returns null on any failure (no ffmpeg, /// timeout, unreadable stream) — the discovery must never fail because of /// a screenshot. ArgumentList is used (never Arguments) to avoid RTSP /// argument injection. /// private async Task CaptureScreenshotAsync(string url, CancellationToken ct) { try { using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct); cts.CancelAfter(ScreenshotTimeout); var psi = new System.Diagnostics.ProcessStartInfo { FileName = "ffmpeg", RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true, }; psi.ArgumentList.Add("-hide_banner"); psi.ArgumentList.Add("-loglevel"); psi.ArgumentList.Add("error"); psi.ArgumentList.Add("-rtsp_transport"); psi.ArgumentList.Add("tcp"); psi.ArgumentList.Add("-i"); psi.ArgumentList.Add(url); psi.ArgumentList.Add("-frames:v"); psi.ArgumentList.Add("1"); psi.ArgumentList.Add("-f"); psi.ArgumentList.Add("image2pipe"); psi.ArgumentList.Add("-vcodec"); psi.ArgumentList.Add("mjpeg"); psi.ArgumentList.Add("pipe:1"); using var process = System.Diagnostics.Process.Start(psi); if (process is null) return null; using var ms = new MemoryStream(); var copyTask = process.StandardOutput.BaseStream.CopyToAsync(ms, cts.Token); _ = process.StandardError.ReadToEndAsync(cts.Token); // drain stderr to prevent deadlock var completed = await Task.WhenAny(copyTask, Task.Delay(ScreenshotTimeout, ct)).ConfigureAwait(false); if (completed != copyTask) { TryKill(process); return null; } await copyTask.ConfigureAwait(false); if (!process.HasExited) { var exitTask = process.WaitForExitAsync(cts.Token); var exited = await Task.WhenAny(exitTask, Task.Delay(TimeSpan.FromSeconds(2), ct)).ConfigureAwait(false); if (exited != exitTask) { TryKill(process); return null; } } var bytes = ms.ToArray(); if (bytes.Length is 0 or > MaxScreenshotBytes) return null; return Convert.ToBase64String(bytes); } catch (OperationCanceledException) when (ct.IsCancellationRequested) { return null; } catch (Exception) { _logger?.LogTrace("Screenshot capture failed for [camera endpoint]"); return null; } } private static void TryKill(System.Diagnostics.Process process) { try { if (!process.HasExited) process.Kill(entireProcessTree: true); } catch { // best effort } } // ─── 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); } /// /// 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. /// 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; } /// Return the local subnet as CIDR (e.g. 192.168.1.0/24) plus the local IP. 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; } /// Expand a CIDR to host IPs (skipping network/broadcast, capped at 65 536). internal static List 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((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; } /// /// Best-effort reverse DNS lookup (PTR) with a short timeout so a slow DNS /// server never blocks the scan. Returns null on failure (silent). /// private static async Task ResolveHostnameAsync(string ip, CancellationToken ct) { try { var lookupTask = Dns.GetHostEntryAsync(ip, ct); var completed = await Task.WhenAny(lookupTask, Task.Delay(ReverseDnsTimeout, ct)).ConfigureAwait(false); if (completed != lookupTask) return null; var entry = await lookupTask.ConfigureAwait(false); var hostname = entry.HostName; if (string.IsNullOrEmpty(hostname) || hostname.Equals(ip, StringComparison.OrdinalIgnoreCase)) return null; return hostname; } catch (Exception ex) when (ex is not OperationCanceledException) { // Reverse DNS failure is not fatal — no hostname, that's fine. return null; } } /// Read the ARP table (/proc/net/arp) to resolve an IP's MAC address. 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); }