2026-08-11 16:15:41 +02:00
|
|
|
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;
|
2026-08-11 21:13:32 +02:00
|
|
|
using System.Text.Json;
|
2026-08-11 16:15:41 +02:00
|
|
|
using System.Xml.Linq;
|
2026-08-11 20:47:27 +02:00
|
|
|
using Heimdall.Application.Discovery;
|
2026-08-11 16:15:41 +02:00
|
|
|
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
|
|
|
|
|
{
|
2026-08-11 22:04:10 +02:00
|
|
|
// 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];
|
2026-08-11 20:47:27 +02:00
|
|
|
private static readonly TimeSpan PortTimeout = TimeSpan.FromMilliseconds(750);
|
2026-08-11 16:15:41 +02:00
|
|
|
private static readonly TimeSpan HttpTimeout = TimeSpan.FromSeconds(2);
|
2026-08-11 20:47:27 +02:00
|
|
|
private static readonly TimeSpan RtspTimeout = TimeSpan.FromSeconds(2);
|
|
|
|
|
private static readonly TimeSpan StreamTestTimeout = TimeSpan.FromSeconds(3);
|
2026-08-11 16:15:41 +02:00
|
|
|
private static readonly TimeSpan OnvifUdpTimeout = TimeSpan.FromMilliseconds(500);
|
2026-08-11 22:04:45 +02:00
|
|
|
private static readonly TimeSpan ReverseDnsTimeout = TimeSpan.FromMilliseconds(500);
|
2026-08-11 22:22:31 +02:00
|
|
|
private static readonly TimeSpan DvripTimeout = TimeSpan.FromSeconds(3);
|
2026-08-11 22:57:42 +02:00
|
|
|
private static readonly TimeSpan ScreenshotTimeout = TimeSpan.FromSeconds(6);
|
|
|
|
|
private const int MaxScreenshotBytes = 512 * 1024; // 512 KB max per frame
|
2026-08-11 16:15:41 +02:00
|
|
|
|
|
|
|
|
// 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
|
2026-08-11 21:18:26 +02:00
|
|
|
private static readonly XNamespace MediaNs = "http://www.onvif.org/ver10/media/wsdl";
|
|
|
|
|
// ReSharper disable once InconsistentNaming
|
2026-08-11 16:15:41 +02:00
|
|
|
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;
|
2026-08-11 22:16:19 +02:00
|
|
|
private readonly HomeKitMdnsProbe _homeKitProbe;
|
2026-08-12 08:45:18 +02:00
|
|
|
private readonly ICameraDatabase? _cameraDatabase;
|
2026-08-11 16:15:41 +02:00
|
|
|
private readonly string? _localIp;
|
2026-08-11 20:47:27 +02:00
|
|
|
private readonly string? _gatewayIp;
|
2026-08-11 16:15:41 +02:00
|
|
|
|
2026-10-11 21:23:16 +02:00
|
|
|
public NetworkCameraScanner(
|
2026-08-11 22:16:19 +02:00
|
|
|
ILogger<NetworkCameraScanner> logger,
|
2026-10-11 21:23:16 +02:00
|
|
|
ILoggerFactory loggerFactory,
|
2026-08-12 08:45:18 +02:00
|
|
|
HomeKitMdnsProbe? homeKitProbe = null,
|
|
|
|
|
ICameraDatabase? cameraDatabase = null)
|
2026-08-11 16:15:41 +02:00
|
|
|
{
|
|
|
|
|
_logger = logger;
|
2026-10-24 23:23:16 +02:00
|
|
|
_homeKitProbe = homeKitProbe ?? new HomeKitMdnsProbe(loggerFactory.CreateLogger<HomeKitMdnsProbe>());
|
2026-08-12 08:45:18 +02:00
|
|
|
_cameraDatabase = cameraDatabase;
|
2026-08-11 20:47:27 +02:00
|
|
|
var (localIp, gatewayIp) = GetLocalNetworkInfo();
|
|
|
|
|
_localIp = localIp;
|
|
|
|
|
_gatewayIp = gatewayIp;
|
2026-08-11 16:15:41 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <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);
|
|
|
|
|
|
2026-10-24 23:23:16 +02:00
|
|
|
// Broadcast/multicast probes (ONVIF WS-Discovery, DVRIP, HomeKit mDNS) run in
|
2026-08-11 21:11:45 +02:00
|
|
|
// 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);
|
|
|
|
|
|
2026-08-11 16:15:41 +02:00
|
|
|
var tasks = ips.Select(async ip =>
|
|
|
|
|
{
|
|
|
|
|
if (ct.IsCancellationRequested) return;
|
2026-08-11 20:47:27 +02:00
|
|
|
// Skip the agent's own IP and the LAN gateway (NAT/router — never a camera).
|
|
|
|
|
if (ip == localIp || ip == _gatewayIp) return;
|
2026-08-11 16:15:41 +02:00
|
|
|
|
|
|
|
|
await throttler.WaitAsync(ct).ConfigureAwait(false);
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
var device = await ProbeHostAsync(ip, credentialPool, ct).ConfigureAwait(false);
|
2026-08-11 20:47:27 +02:00
|
|
|
if (device is null)
|
|
|
|
|
return;
|
|
|
|
|
|
2026-08-11 21:11:45 +02:00
|
|
|
var final = await BuildFinalDeviceAsync(device, credentialPool, ct).ConfigureAwait(false);
|
|
|
|
|
if (final is not null)
|
|
|
|
|
results.Add(final);
|
2026-08-11 16:15:41 +02:00
|
|
|
}
|
|
|
|
|
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
|
|
|
|
{
|
|
|
|
|
// stop probing
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
2026-10-20 07:16:44 +02:00
|
|
|
_logger.LogTrace("Probe error for {Ip} (error type {ErrorType})", ip, ex.GetType().Name);
|
2026-08-11 16:15:41 +02:00
|
|
|
}
|
|
|
|
|
finally
|
|
|
|
|
{
|
|
|
|
|
throttler.Release();
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
await Task.WhenAll(tasks).ConfigureAwait(false);
|
2026-08-11 21:11:45 +02:00
|
|
|
|
2026-10-24 23:23:16 +02:00
|
|
|
// 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);
|
2026-08-11 21:11:45 +02:00
|
|
|
foreach (var device in await broadcastTask.ConfigureAwait(false))
|
|
|
|
|
{
|
|
|
|
|
if (device.Ip == localIp || device.Ip == _gatewayIp)
|
|
|
|
|
continue;
|
2026-10-24 23:23:16 +02:00
|
|
|
|
|
|
|
|
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
|
|
|
|
|
};
|
2026-08-11 21:11:45 +02:00
|
|
|
continue;
|
2026-10-24 23:23:16 +02:00
|
|
|
}
|
2026-08-11 21:11:45 +02:00
|
|
|
|
|
|
|
|
var final = await BuildFinalDeviceAsync(device, credentialPool, ct).ConfigureAwait(false);
|
|
|
|
|
if (final is not null)
|
2026-10-24 23:23:16 +02:00
|
|
|
{
|
|
|
|
|
resultIndexes.Add(device.Ip, mergedResults.Count);
|
|
|
|
|
mergedResults.Add(final);
|
|
|
|
|
}
|
2026-08-11 21:11:45 +02:00
|
|
|
}
|
|
|
|
|
|
2026-10-24 23:23:16 +02:00
|
|
|
_logger.LogInformation("Camera discovery: {Found} candidate device(s) on {Subnet}", mergedResults.Count, subnetCidr);
|
2026-08-11 16:15:41 +02:00
|
|
|
|
2026-10-24 23:23:16 +02:00
|
|
|
return mergedResults;
|
2026-08-11 16:15:41 +02:00
|
|
|
}
|
|
|
|
|
|
2026-08-11 21:11:45 +02:00
|
|
|
/// <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)
|
|
|
|
|
{
|
2026-08-11 22:16:19 +02:00
|
|
|
// 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;
|
|
|
|
|
|
2026-10-24 23:23:16 +02:00
|
|
|
// 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;
|
|
|
|
|
|
2026-08-11 21:18:26 +02:00
|
|
|
// 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);
|
2026-08-11 22:57:42 +02:00
|
|
|
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,
|
|
|
|
|
};
|
2026-08-11 21:18:26 +02:00
|
|
|
}
|
|
|
|
|
|
2026-08-11 21:11:45 +02:00
|
|
|
// Build + test candidate stream URLs (the agent is on the camera LAN,
|
|
|
|
|
// the Central is not — this is where the live stream is proven).
|
2026-08-11 21:18:26 +02:00
|
|
|
var tested = await TestStreamUrlsAsync(device, credentialPool, ct).ConfigureAwait(false);
|
|
|
|
|
if (tested.Count > 0)
|
2026-08-11 22:57:42 +02:00
|
|
|
{
|
|
|
|
|
var screenshot = device.ScreenshotBase64 is null
|
|
|
|
|
? await CaptureScreenshotAsync(tested[0], ct).ConfigureAwait(false)
|
|
|
|
|
: device.ScreenshotBase64;
|
|
|
|
|
return device with { StreamUrls = [.. tested], ScreenshotBase64 = screenshot };
|
|
|
|
|
}
|
2026-08-11 21:11:45 +02:00
|
|
|
|
|
|
|
|
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>();
|
2026-08-11 21:18:26 +02:00
|
|
|
devices.AddRange(await DiscoverOnvifMulticastAsync(credentialPool, ct).ConfigureAwait(false));
|
2026-08-11 21:13:32 +02:00
|
|
|
devices.AddRange(await DiscoverDvripAsync(ct).ConfigureAwait(false));
|
2026-08-11 22:16:19 +02:00
|
|
|
devices.AddRange(await DiscoverHomeKitAsync(ct).ConfigureAwait(false));
|
|
|
|
|
return devices;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// 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.
|
|
|
|
|
/// </summary>
|
|
|
|
|
private async Task<List<AgentDiscoveredDevice>> DiscoverHomeKitAsync(CancellationToken ct)
|
|
|
|
|
{
|
|
|
|
|
var devices = new List<AgentDiscoveredDevice>();
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
var found = await _homeKitProbe.DiscoverAsync(ct).ConfigureAwait(false);
|
|
|
|
|
foreach (var accessory in found)
|
|
|
|
|
{
|
|
|
|
|
devices.Add(new AgentDiscoveredDevice(
|
|
|
|
|
Ip: accessory.Ip,
|
|
|
|
|
IsReachable: true,
|
2026-10-24 23:23:16 +02:00
|
|
|
OpenPorts: accessory.Port > 0 ? [accessory.Port] : [],
|
2026-08-11 22:16:19 +02:00
|
|
|
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,
|
2026-10-24 23:23:16 +02:00
|
|
|
StreamUrls: null,
|
|
|
|
|
HomeKitCategory: accessory.Category,
|
|
|
|
|
HomeKitIsPaired: accessory.IsPaired,
|
|
|
|
|
HomeKitPort: accessory.Port));
|
2026-08-11 22:16:19 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
2026-10-20 07:16:44 +02:00
|
|
|
_logger.LogWarning("HomeKit mDNS discovery failed (error type {ErrorType})", ex.GetType().Name);
|
2026-08-11 22:16:19 +02:00
|
|
|
}
|
|
|
|
|
|
2026-08-11 21:11:45 +02:00
|
|
|
return devices;
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-11 21:13:32 +02:00
|
|
|
/// <summary>
|
|
|
|
|
/// 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.
|
|
|
|
|
/// </summary>
|
|
|
|
|
private async Task<List<AgentDiscoveredDevice>> DiscoverDvripAsync(CancellationToken ct)
|
|
|
|
|
{
|
|
|
|
|
var devices = new List<AgentDiscoveredDevice>();
|
|
|
|
|
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);
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-11 21:36:48 +02:00
|
|
|
// 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)
|
2026-08-11 21:13:32 +02:00
|
|
|
{
|
|
|
|
|
UdpReceiveResult result;
|
2026-08-11 21:36:48 +02:00
|
|
|
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);
|
2026-08-11 21:13:32 +02:00
|
|
|
|
|
|
|
|
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)
|
|
|
|
|
{
|
2026-10-20 07:16:44 +02:00
|
|
|
_logger.LogWarning("DVRIP discovery failed (error type {ErrorType})", ex.GetType().Name);
|
2026-08-11 21:13:32 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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;
|
|
|
|
|
|
2026-08-11 21:11:45 +02:00
|
|
|
/// <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>
|
2026-08-11 21:18:26 +02:00
|
|
|
private async Task<List<AgentDiscoveredDevice>> DiscoverOnvifMulticastAsync(
|
|
|
|
|
IReadOnlyList<AgentCameraCredential>? credentialPool, CancellationToken ct)
|
2026-08-11 21:11:45 +02:00
|
|
|
{
|
|
|
|
|
var devices = new List<AgentDiscoveredDevice>();
|
2026-08-11 21:18:26 +02:00
|
|
|
var raw = new List<(string Ip, string ServiceUrl, string? Name, string? Hardware)>();
|
2026-08-11 21:11:45 +02:00
|
|
|
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);
|
|
|
|
|
|
2026-08-11 21:36:48 +02:00
|
|
|
// 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)
|
2026-08-11 21:11:45 +02:00
|
|
|
{
|
|
|
|
|
UdpReceiveResult result;
|
2026-08-11 21:36:48 +02:00
|
|
|
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);
|
2026-08-11 21:11:45 +02:00
|
|
|
|
|
|
|
|
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..];
|
|
|
|
|
|
2026-08-11 21:18:26 +02:00
|
|
|
raw.Add((
|
|
|
|
|
result.RemoteEndPoint.Address.ToString(),
|
|
|
|
|
serviceUrl,
|
|
|
|
|
FindScope(doc, "onvif://www.onvif.org/name/"),
|
|
|
|
|
FindScope(doc, "onvif://www.onvif.org/hardware/")));
|
2026-08-11 21:11:45 +02:00
|
|
|
}
|
|
|
|
|
|
2026-08-11 21:18:26 +02:00
|
|
|
// 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)
|
2026-08-11 21:11:45 +02:00
|
|
|
_logger.LogInformation(
|
|
|
|
|
"Camera discovery: {Count} ONVIF device(s) via WS-Discovery multicast", devices.Count);
|
|
|
|
|
}
|
|
|
|
|
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
|
|
|
|
{
|
|
|
|
|
// cancelled
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
2026-10-20 07:16:44 +02:00
|
|
|
_logger.LogWarning("ONVIF WS-Discovery multicast failed (error type {ErrorType})", ex.GetType().Name);
|
2026-08-11 21:11:45 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-11 16:15:41 +02:00
|
|
|
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);
|
|
|
|
|
|
2026-08-11 22:04:45 +02:00
|
|
|
// Reverse DNS as a fallback hostname (ONVIF/DVRIP/mDNS names win).
|
|
|
|
|
var hostname = onvif?.Name is null ? await ResolveHostnameAsync(ip, ct).ConfigureAwait(false) : null;
|
|
|
|
|
|
2026-08-11 16:15:41 +02:00
|
|
|
return new AgentDiscoveredDevice(
|
|
|
|
|
Ip: ip,
|
|
|
|
|
IsReachable: true,
|
|
|
|
|
OpenPorts: [.. openPorts],
|
|
|
|
|
MacAddress: mac,
|
|
|
|
|
Vendor: null,
|
2026-08-11 22:04:45 +02:00
|
|
|
Hostname: hostname,
|
2026-08-11 16:15:41 +02:00
|
|
|
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,
|
2026-08-11 21:18:26 +02:00
|
|
|
CredentialLabel: onvif?.CredentialLabel,
|
|
|
|
|
StreamUrls: onvif?.StreamUrls);
|
2026-08-11 16:15:41 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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)
|
|
|
|
|
{
|
2026-10-20 07:16:44 +02:00
|
|
|
_logger.LogTrace("HTTP probe failed for {Ip}:{Port} (error type {ErrorType})", ip, port, ex.GetType().Name);
|
2026-08-11 16:15:41 +02:00
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async Task<OnvifProbe?> ProbeOnvifAsync(
|
|
|
|
|
string ip, int port, IReadOnlyList<AgentCameraCredential>? credentialPool, CancellationToken ct)
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
using var udp = new UdpClient();
|
|
|
|
|
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);
|
2026-08-11 21:36:48 +02:00
|
|
|
|
|
|
|
|
// 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);
|
2026-08-11 16:15:41 +02:00
|
|
|
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);
|
2026-08-11 21:18:26 +02:00
|
|
|
var streamUrls = await GetStreamUrisWithCredentialsAsync(deviceServiceUrl, credentialPool, ip, ct).ConfigureAwait(false);
|
2026-08-11 16:15:41 +02:00
|
|
|
|
2026-08-11 21:18:26 +02:00
|
|
|
return new OnvifProbe(
|
|
|
|
|
deviceServiceUrl, detail?.Manufacturer, detail?.Model, detail?.CredentialLabel,
|
|
|
|
|
streamUrls.Length > 0 ? streamUrls : null);
|
2026-08-11 16:15:41 +02:00
|
|
|
}
|
|
|
|
|
catch (SocketException ex) when (ex.SocketErrorCode is SocketError.TimedOut or SocketError.ConnectionRefused)
|
|
|
|
|
{
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
|
|
|
|
{
|
|
|
|
|
throw;
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
2026-10-20 07:16:44 +02:00
|
|
|
_logger.LogTrace("ONVIF probe failed for {Ip}:{Port} (error type {ErrorType})", ip, port, ex.GetType().Name);
|
2026-08-11 16:15:41 +02:00
|
|
|
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(
|
2026-10-20 07:16:44 +02:00
|
|
|
"ONVIF auth succeeded with credential '{Label}'", credential.Label);
|
2026-08-11 16:15:41 +02:00
|
|
|
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(
|
2026-10-20 07:16:44 +02:00
|
|
|
"ONVIF auth (PasswordText) succeeded with credential '{Label}'", credential.Label);
|
2026-08-11 16:15:41 +02:00
|
|
|
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 };
|
2026-08-11 21:18:26 +02:00
|
|
|
var doc = await PostSoapAsync(client, deviceServiceUrl, "GetDeviceInformation", null, username, password, passwordType, ct).ConfigureAwait(false);
|
|
|
|
|
if (doc is null)
|
2026-08-11 16:15:41 +02:00
|
|
|
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)
|
|
|
|
|
{
|
2026-10-20 07:16:44 +02:00
|
|
|
_logger.LogTrace("GetDeviceInformation failed for [camera endpoint]");
|
2026-08-11 16:15:41 +02:00
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
2026-08-11 21:18:26 +02:00
|
|
|
/// 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.
|
|
|
|
|
/// </summary>
|
|
|
|
|
private async Task<string[]> GetStreamUrisWithCredentialsAsync(
|
|
|
|
|
string deviceServiceUrl, IReadOnlyList<AgentCameraCredential>? 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<string[]> 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<string>();
|
|
|
|
|
foreach (var token in tokens)
|
|
|
|
|
{
|
|
|
|
|
var body = $"<trt:GetStreamUri><trt:StreamSetup><trt:Stream>RTP-Unicast</trt:Stream>"
|
|
|
|
|
+ $"<trt:Transport><trt:Protocol>RTSP</trt:Protocol></trt:Transport></trt:StreamSetup>"
|
|
|
|
|
+ $"<trt:ProfileToken>{token}</trt:ProfileToken></trt:GetStreamUri>";
|
|
|
|
|
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)
|
|
|
|
|
{
|
2026-10-20 07:16:44 +02:00
|
|
|
_logger.LogTrace("GetStreamUri failed for [camera endpoint]");
|
2026-08-11 21:18:26 +02:00
|
|
|
return [];
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// 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.
|
|
|
|
|
/// </summary>
|
|
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>POST a SOAP operation to an ONVIF service and parse the response.</summary>
|
|
|
|
|
private static async Task<XDocument?> 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);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Build a SOAP envelope for an ONVIF operation, adding a WS-Security
|
2026-08-11 16:15:41 +02:00
|
|
|
/// UsernameToken when credentials are provided (PasswordDigest or
|
|
|
|
|
/// PasswordText, matching ONVIF interop requirements).
|
|
|
|
|
/// </summary>
|
2026-08-11 21:18:26 +02:00
|
|
|
private static string BuildSoapEnvelope(
|
|
|
|
|
string operation, string? bodyContent, string? username, string? password, string? passwordType)
|
2026-08-11 16:15:41 +02:00
|
|
|
{
|
|
|
|
|
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>";
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-11 21:18:26 +02:00
|
|
|
var body = operation switch
|
|
|
|
|
{
|
|
|
|
|
"GetDeviceInformation" => "<tds:GetDeviceInformation />",
|
|
|
|
|
"GetProfiles" => "<trt:GetProfiles />",
|
|
|
|
|
_ => bodyContent ?? string.Empty,
|
|
|
|
|
};
|
|
|
|
|
|
2026-08-11 16:15:41 +02:00
|
|
|
return $@"<?xml version=""1.0"" encoding=""utf-8""?>
|
|
|
|
|
<soap:Envelope xmlns:soap=""{SoapNs.NamespaceName}""
|
2026-08-11 21:18:26 +02:00
|
|
|
xmlns:tds=""{TdsNs.NamespaceName}""
|
|
|
|
|
xmlns:trt=""{MediaNs.NamespaceName}"">{securityHeader}
|
2026-08-11 16:15:41 +02:00
|
|
|
<soap:Body>
|
2026-08-11 21:18:26 +02:00
|
|
|
{body}
|
2026-08-11 16:15:41 +02:00
|
|
|
</soap:Body>
|
|
|
|
|
</soap:Envelope>";
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-11 20:47:27 +02:00
|
|
|
// ─── 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>
|
2026-08-12 08:45:18 +02:00
|
|
|
private List<string> BuildCandidateUrls(AgentDiscoveredDevice device, IReadOnlyList<AgentCameraCredential>? credentialPool)
|
2026-08-11 20:47:27 +02:00
|
|
|
{
|
|
|
|
|
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}");
|
|
|
|
|
|
2026-08-11 22:22:31 +02:00
|
|
|
// 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");
|
|
|
|
|
|
2026-08-12 08:45:18 +02:00
|
|
|
// 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<string> { $"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];
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-11 20:47:27 +02:00
|
|
|
return CameraStreamTemplates.BuildUrls(
|
|
|
|
|
[.. ids], device.Ip, username, password, channel: 0,
|
2026-08-11 22:04:10 +02:00
|
|
|
device.OpenPorts.Length > 0 ? device.OpenPorts : null);
|
2026-08-11 20:47:27 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <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>
|
2026-08-11 21:18:26 +02:00
|
|
|
private Task<List<string>> TestStreamUrlsAsync(
|
2026-08-11 20:47:27 +02:00
|
|
|
AgentDiscoveredDevice device, IReadOnlyList<AgentCameraCredential>? credentialPool, CancellationToken ct)
|
2026-08-11 21:18:26 +02:00
|
|
|
=> TestUrlsAsync(BuildCandidateUrls(device, credentialPool), ct);
|
2026-08-11 20:47:27 +02:00
|
|
|
|
2026-08-11 21:18:26 +02:00
|
|
|
private async Task<List<string>> TestUrlsAsync(IEnumerable<string> urls, CancellationToken ct)
|
|
|
|
|
{
|
2026-08-11 20:47:27 +02:00
|
|
|
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
|
|
|
|
|
}
|
2026-10-20 07:16:44 +02:00
|
|
|
catch (Exception)
|
2026-08-11 20:47:27 +02:00
|
|
|
{
|
2026-10-20 07:16:44 +02:00
|
|
|
_logger.LogTrace("Stream test failed for [camera endpoint]");
|
2026-08-11 20:47:27 +02:00
|
|
|
}
|
|
|
|
|
finally
|
|
|
|
|
{
|
|
|
|
|
throttler.Release();
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
await Task.WhenAll(tasks).ConfigureAwait(false);
|
|
|
|
|
return alive;
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-11 22:25:59 +02:00
|
|
|
internal async Task<bool> IsStreamUrlAliveAsync(string url, CancellationToken ct)
|
2026-08-11 20:47:27 +02:00
|
|
|
{
|
2026-08-11 22:22:31 +02:00
|
|
|
if (url.StartsWith("dvrip://", StringComparison.OrdinalIgnoreCase))
|
|
|
|
|
return await IsDvripUrlAliveAsync(url, ct).ConfigureAwait(false);
|
|
|
|
|
|
2026-08-11 22:25:59 +02:00
|
|
|
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);
|
|
|
|
|
|
2026-08-11 20:47:27 +02:00
|
|
|
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)
|
|
|
|
|
{
|
2026-10-20 07:16:44 +02:00
|
|
|
_logger.LogTrace("RTSP probe failed for [camera endpoint]");
|
2026-08-11 20:47:27 +02:00
|
|
|
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)
|
|
|
|
|
{
|
2026-10-20 07:16:44 +02:00
|
|
|
_logger.LogTrace("HTTP stream probe failed for [camera endpoint]");
|
2026-08-11 20:47:27 +02:00
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-11 22:22:31 +02:00
|
|
|
// ─── DVRIP (Dahua/Imou) ──────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// 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.
|
|
|
|
|
/// </summary>
|
|
|
|
|
private async Task<bool> 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();
|
|
|
|
|
var connectTask = client.ConnectAsync(host, port, ct).AsTask();
|
|
|
|
|
var connected = await Task.WhenAny(connectTask, Task.Delay(DvripTimeout, ct)).ConfigureAwait(false);
|
|
|
|
|
if (connected != connectTask || !client.Connected)
|
|
|
|
|
return false;
|
|
|
|
|
await connectTask.ConfigureAwait(false);
|
|
|
|
|
|
|
|
|
|
var stream = client.GetStream();
|
|
|
|
|
|
|
|
|
|
// Login request: {"EncryptType":"MD5","LoginType":"DVRIP-Web","PassWord":"<sofia>","UserName":"<user>"}\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)
|
|
|
|
|
{
|
2026-10-20 07:16:44 +02:00
|
|
|
_logger.LogDebug("DVRIP login OK for [camera endpoint]");
|
2026-08-11 22:22:31 +02:00
|
|
|
return true;
|
|
|
|
|
}
|
2026-10-20 07:16:44 +02:00
|
|
|
_logger.LogDebug("DVRIP login rejected (Ret={Ret}) for [camera endpoint]", ret);
|
2026-08-11 22:22:31 +02:00
|
|
|
}
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
|
|
|
|
{
|
2026-10-20 07:16:44 +02:00
|
|
|
_logger.LogTrace("DVRIP probe failed for [camera endpoint]");
|
2026-08-11 22:22:31 +02:00
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>Build a DVRIP packet: 20-byte header + JSON payload.</summary>
|
|
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// 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.
|
|
|
|
|
/// </summary>
|
|
|
|
|
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();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>Read exactly <paramref name="buffer"/>.Length bytes with a timeout (Task.WhenAny, never Socket.ReceiveTimeout on async).</summary>
|
|
|
|
|
private static async Task<bool> 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;
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-11 22:25:59 +02:00
|
|
|
// ─── RTMP / Bubble / HomeKit ─────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// 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.
|
|
|
|
|
/// </summary>
|
|
|
|
|
private async Task<bool> IsRtmpUrlAliveAsync(string url, CancellationToken ct)
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
var uri = new Uri(url);
|
|
|
|
|
var port = uri.IsDefaultPort ? 1935 : uri.Port;
|
|
|
|
|
|
|
|
|
|
using var client = new TcpClient();
|
|
|
|
|
var connectTask = client.ConnectAsync(uri.Host, port, ct).AsTask();
|
|
|
|
|
var connected = await Task.WhenAny(connectTask, Task.Delay(DvripTimeout, ct)).ConfigureAwait(false);
|
|
|
|
|
if (connected != connectTask || !client.Connected)
|
|
|
|
|
return false;
|
|
|
|
|
await connectTask.ConfigureAwait(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;
|
2026-10-20 07:16:44 +02:00
|
|
|
_logger.LogDebug("RTMP probe {Result} for [camera endpoint]", alive ? "OK" : "failed");
|
2026-08-11 22:25:59 +02:00
|
|
|
return alive;
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
|
|
|
|
{
|
2026-10-20 07:16:44 +02:00
|
|
|
_logger.LogTrace("RTMP probe failed for [camera endpoint]");
|
2026-08-11 22:25:59 +02:00
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Bubble (Uniview) liveness check: TCP connect + HTTP GET with the Bubble
|
|
|
|
|
/// binary preamble. A real Bubble server answers with an HTTP response.
|
|
|
|
|
/// </summary>
|
|
|
|
|
private async Task<bool> 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();
|
|
|
|
|
var connectTask = client.ConnectAsync(uri.Host, port, ct).AsTask();
|
|
|
|
|
var connected = await Task.WhenAny(connectTask, Task.Delay(DvripTimeout, ct)).ConfigureAwait(false);
|
|
|
|
|
if (connected != connectTask || !client.Connected)
|
|
|
|
|
return false;
|
|
|
|
|
await connectTask.ConfigureAwait(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);
|
2026-10-20 07:16:44 +02:00
|
|
|
_logger.LogDebug("Bubble probe {Result} for [camera endpoint]", alive ? "OK" : "failed");
|
2026-08-11 22:25:59 +02:00
|
|
|
return alive;
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
|
|
|
|
{
|
2026-10-20 07:16:44 +02:00
|
|
|
_logger.LogTrace("Bubble probe failed for [camera endpoint]");
|
2026-08-11 22:25:59 +02:00
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// 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.
|
|
|
|
|
/// </summary>
|
|
|
|
|
private async Task<bool> IsHomeKitUrlAliveAsync(string url, CancellationToken ct)
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
var uri = new Uri(url);
|
|
|
|
|
var port = uri.IsDefaultPort ? 8080 : uri.Port;
|
|
|
|
|
|
|
|
|
|
using var client = new TcpClient();
|
|
|
|
|
var connectTask = client.ConnectAsync(uri.Host, port, ct).AsTask();
|
|
|
|
|
var connected = await Task.WhenAny(connectTask, Task.Delay(DvripTimeout, ct)).ConfigureAwait(false);
|
|
|
|
|
if (connected != connectTask || !client.Connected)
|
|
|
|
|
return false;
|
|
|
|
|
await connectTask.ConfigureAwait(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);
|
2026-10-20 07:16:44 +02:00
|
|
|
_logger.LogDebug("HomeKit probe {Result} for [camera endpoint] ({Response})", alive ? "OK" : "failed", response.Split('\r')[0]);
|
2026-08-11 22:25:59 +02:00
|
|
|
return alive;
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
|
|
|
|
{
|
2026-10-20 07:16:44 +02:00
|
|
|
_logger.LogTrace("HomeKit probe failed for [camera endpoint]");
|
2026-08-11 22:25:59 +02:00
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-11 22:57:42 +02:00
|
|
|
// ─── Screenshot capture ──────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// 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.
|
|
|
|
|
/// </summary>
|
|
|
|
|
private async Task<string?> 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);
|
2026-08-20 14:13:06 +02:00
|
|
|
_ = process.StandardError.ReadToEndAsync(cts.Token); // drain stderr to prevent deadlock
|
2026-08-11 22:57:42 +02:00
|
|
|
|
|
|
|
|
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;
|
|
|
|
|
}
|
2026-10-20 07:16:44 +02:00
|
|
|
catch (Exception)
|
2026-08-11 22:57:42 +02:00
|
|
|
{
|
2026-10-20 07:16:44 +02:00
|
|
|
_logger?.LogTrace("Screenshot capture failed for [camera endpoint]");
|
2026-08-11 22:57:42 +02:00
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private static void TryKill(System.Diagnostics.Process process)
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
if (!process.HasExited)
|
|
|
|
|
process.Kill(entireProcessTree: true);
|
|
|
|
|
}
|
|
|
|
|
catch
|
|
|
|
|
{
|
|
|
|
|
// best effort
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-11 16:15:41 +02:00
|
|
|
// ─── Network helpers ────────────────────────────────────────────────
|
|
|
|
|
|
2026-08-11 20:47:27 +02:00
|
|
|
private static (string? LocalIp, string? GatewayIp) GetLocalNetworkInfo()
|
2026-08-11 16:15:41 +02:00
|
|
|
{
|
|
|
|
|
foreach (var ni in NetworkInterface.GetAllNetworkInterfaces())
|
|
|
|
|
{
|
|
|
|
|
if (ni.OperationalStatus != OperationalStatus.Up)
|
|
|
|
|
continue;
|
|
|
|
|
foreach (var addr in ni.GetIPProperties().UnicastAddresses)
|
|
|
|
|
{
|
2026-08-11 20:47:27 +02:00
|
|
|
if (!IsCandidateNetwork(addr.Address))
|
|
|
|
|
continue;
|
|
|
|
|
|
|
|
|
|
var gateway = ni.GetIPProperties().GatewayAddresses
|
|
|
|
|
.FirstOrDefault(g => g.Address.AddressFamily == AddressFamily.InterNetwork)
|
|
|
|
|
?.Address.ToString();
|
|
|
|
|
return (addr.Address.ToString(), gateway);
|
2026-08-11 16:15:41 +02:00
|
|
|
}
|
|
|
|
|
}
|
2026-08-11 20:47:27 +02:00
|
|
|
return (null, null);
|
2026-08-11 16:15:41 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <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;
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-11 22:04:45 +02:00
|
|
|
/// <summary>
|
|
|
|
|
/// Best-effort reverse DNS lookup (PTR) with a short timeout so a slow DNS
|
|
|
|
|
/// server never blocks the scan. Returns null on failure (silent).
|
|
|
|
|
/// </summary>
|
|
|
|
|
private static async Task<string?> 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;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-11 16:15:41 +02:00
|
|
|
/// <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);
|
2026-08-11 21:18:26 +02:00
|
|
|
private sealed record OnvifProbe(
|
|
|
|
|
string DeviceServiceUrl, string? Name, string? Hardware, string? CredentialLabel = null,
|
|
|
|
|
string[]? StreamUrls = null);
|
2026-08-11 16:15:41 +02:00
|
|
|
private sealed record OnvifDetail(string? Manufacturer, string? Model, string? CredentialLabel = null);
|
|
|
|
|
}
|