feat(agent): découverte mDNS/HomeKit — probe multicast _hap._tcp (Fixes #62)

- HomeKitMdnsProbe : paquet DNS PTR brut sur 224.0.0.251:5353, écoute 2 s
  avec timeout explicite Task.WhenAny (jamais de hang, cf. 491a253)
- Parseur DNS complet : PTR/SRV/TXT/A avec pointeurs de compression, TXT
  (ci/id/md/sf), dédup par IP, mapping IP via SRV target
- Filtre catégories 17 (camera) et 18 (doorbell) — Strix pkg/probe/mdns.go
- Intégré au scan broadcast de NetworkCameraScanner ; devices HomeKit avec
  HomeKitName/HomeKitDeviceId/HomeKitModel remplis → classés HomeKit côté central
- Les devices HomeKit ne génèrent plus de fausses URLs RTSP (flux HAP)
- Tests : 4 (parseur PTR/SRV/TXT/A, filtrage catégories, dédup, no-hang)
This commit is contained in:
Arnaud Dartois committed 2026-08-11 22:16:19 +02:00
1 parent f713abc7ca
commit e5b035745d
4 files changed
+714 -1

No files matched your search

+1
View File
@@ -64,6 +64,7 @@ builder.Services.AddSingleton<AgentState>(sp =>
builder.Services.AddSingleton<SystemMetricsProvider>();
builder.Services.AddSingleton<NetworkCameraScanner>();
builder.Services.AddSingleton<HomeKitMdnsProbe>();
builder.Services.AddSingleton<DiscoveryScanTrigger>();
builder.Services.AddSingleton<AgentCredentialStore>();
builder.Services.AddSingleton<RuntimeLogLevel>();
@@ -0,0 +1,421 @@
using System.Buffers.Binary;
using System.Net;
using System.Net.Sockets;
using System.Text;
using Microsoft.Extensions.Logging;
namespace Heimdall.Agent.Services;
/// <summary>Parsed HomeKit accessory (camera/doorbell) found via mDNS.</summary>
public sealed record HomeKitDevice(
string Ip,
string Name,
string DeviceId,
string Model,
int Category,
bool IsPaired,
int Port);
/// <summary>
/// mDNS/HomeKit discovery probe (multicast). Transposed from Strix
/// pkg/probe/mdns.go (QueryHAP) and go2rtc internal/homekit.
/// Sends a raw DNS PTR query for <c>_hap._tcp.local.</c> to the mDNS
/// multicast group 224.0.0.251:5353, listens ~2 s, parses PTR/SRV/TXT/A
/// replies and keeps accessories with category <c>ci=17</c> (camera) or
/// <c>ci=18</c> (doorbell).
/// </summary>
/// <remarks>
/// The listener uses an explicit <c>Task.WhenAny(receive, Task.Delay(...))</c>
/// window — <see cref="Socket.ReceiveTimeout"/> does NOT apply to async
/// ReceiveAsync (bug réel découvert en prod, fix 491a253).
/// </remarks>
public sealed class HomeKitMdnsProbe
{
private const string MulticastAddress = "224.0.0.251";
private const int MdnsPort = 5353;
private static readonly TimeSpan ListenWindow = TimeSpan.FromSeconds(2);
private static readonly TimeSpan ReplyDelay = TimeSpan.FromMilliseconds(250);
private readonly ILogger<HomeKitMdnsProbe> _logger;
public HomeKitMdnsProbe(ILogger<HomeKitMdnsProbe> logger)
{
_logger = logger;
}
/// <summary>
/// Run one global multicast probe for HomeKit camera/doorbell accessories.
/// Returns devices deduplicated by IP. Never throws; failures are logged
/// and an empty list is returned (scan must never hang).
/// </summary>
public async Task<IReadOnlyList<HomeKitDevice>> DiscoverAsync(CancellationToken ct)
{
var devices = new List<HomeKitDevice>();
try
{
using var udp = new UdpClient(AddressFamily.InterNetwork);
udp.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
udp.Client.Bind(new IPEndPoint(IPAddress.Any, MdnsPort));
udp.Client.MulticastLoopback = false;
udp.JoinMulticastGroup(IPAddress.Parse(MulticastAddress));
// DNS-SD PTR question for _hap._tcp.local. (mDNS: QU with unicast-response bit)
var query = BuildPtrQuery("_hap._tcp.local");
var multicast = new IPEndPoint(IPAddress.Parse(MulticastAddress), MdnsPort);
// Send 3 probes (devices sometimes miss the first one).
for (var i = 0; i < 3; i++)
{
await udp.SendAsync(query, multicast, ct).ConfigureAwait(false);
await Task.Delay(ReplyDelay, ct).ConfigureAwait(false);
}
var collected = new List<MdnsReply>();
var listenUntil = DateTime.UtcNow + ListenWindow;
while (!ct.IsCancellationRequested && DateTime.UtcNow < listenUntil)
{
var receiveTask = udp.ReceiveAsync(ct).AsTask();
var completed = await Task.WhenAny(receiveTask, Task.Delay(ListenWindow, ct)).ConfigureAwait(false);
if (completed != receiveTask)
break; // no more replies expected
var result = await receiveTask.ConfigureAwait(false);
var replies = ParsePacket(result.Buffer);
if (replies.Count > 0)
collected.AddRange(replies);
}
devices = BuildDevices(collected);
if (devices.Count > 0)
_logger.LogInformation("Camera discovery: {Count} HomeKit accessory(ies) via mDNS multicast", devices.Count);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
// cancelled
}
catch (Exception ex)
{
_logger.LogWarning(ex, "mDNS/HomeKit multicast probe failed");
}
return devices;
}
// ─── DNS packet building ─────────────────────────────────────────
private static byte[] BuildPtrQuery(string serviceType)
{
using var ms = new MemoryStream();
Span<byte> scratch = stackalloc byte[8];
// Header: ID (random), flags = 0x0000 (QU), QDCOUNT=1.
BinaryPrimitives.WriteUInt16BigEndian(scratch, (ushort)Random.Shared.Next(0, 0xFFFF));
BinaryPrimitives.WriteUInt16BigEndian(scratch[2..], 0);
BinaryPrimitives.WriteUInt16BigEndian(scratch[4..], 1);
BinaryPrimitives.WriteUInt16BigEndian(scratch[6..], 0);
ms.Write(scratch);
WriteDnsName(ms, serviceType);
BinaryPrimitives.WriteUInt16BigEndian(scratch, 12); // QTYPE = PTR
BinaryPrimitives.WriteUInt16BigEndian(scratch[2..], 0x8001); // QCLASS = IN + unicast-response
ms.Write(scratch[..4]);
return ms.ToArray();
}
private static void WriteDnsName(MemoryStream ms, string name)
{
foreach (var label in name.TrimEnd('.').Split('.'))
{
if (label.Length == 0 || label.Length > 63)
continue;
ms.WriteByte((byte)label.Length);
ms.Write(Encoding.ASCII.GetBytes(label));
}
ms.WriteByte(0);
}
// ─── DNS packet parsing (with compression pointers) ──────────────
private sealed record MdnsReply(
string Instance, // PTR target instance name (lowercased)
ushort Type,
string? SrvTarget,
int? SrvPort,
IReadOnlyDictionary<string, string>? Txt,
string? Address);
private sealed record PacketReader(byte[] Data)
{
private int _pos;
public int Position
{
get => _pos;
set => _pos = value;
}
public int Remaining => Data.Length - _pos;
public ushort ReadUInt16()
{
var v = BinaryPrimitives.ReadUInt16BigEndian(Data.AsSpan(_pos, 2));
_pos += 2;
return v;
}
public uint ReadUInt32()
{
var v = BinaryPrimitives.ReadUInt32BigEndian(Data.AsSpan(_pos, 4));
_pos += 4;
return v;
}
public byte[] ReadBytes(int count)
{
var b = Data.AsSpan(_pos, count).ToArray();
_pos += count;
return b;
}
/// <summary>Read a (possibly compressed) DNS name. Returns the name and the
/// position AFTER the name in the original stream (compression pointers
/// never advance the stream position past the pointer itself).</summary>
public (string Name, int EndPos) ReadName(int startPos)
{
var labels = new List<string>();
var pos = startPos;
var jumped = false;
var endPos = startPos;
var guard = 0;
while (guard++ < 128)
{
if (pos >= Data.Length)
break;
var len = Data[pos];
if (len == 0)
{
pos++;
if (!jumped)
endPos = pos;
break;
}
if ((len & 0xC0) == 0xC0)
{
if (pos + 1 >= Data.Length)
break;
var pointer = ((len & 0x3F) << 8) | Data[pos + 1];
if (!jumped)
endPos = pos + 2;
pos = pointer;
jumped = true;
continue;
}
pos++;
if (pos + len > Data.Length)
break;
labels.Add(Encoding.ASCII.GetString(Data, pos, len));
pos += len;
}
return (string.Join(".", labels).ToLowerInvariant(), endPos);
}
}
private static List<MdnsReply> ParsePacket(byte[] data)
{
var replies = new List<MdnsReply>();
try
{
if (data.Length < 12)
return replies;
var r = new PacketReader(data);
r.Position = 4; // skip ID + flags
var qdCount = r.ReadUInt16();
var anCount = r.ReadUInt16();
var nsCount = r.ReadUInt16();
var arCount = r.ReadUInt16();
// Skip questions.
for (var q = 0; q < qdCount; q++)
{
var (_, endPos) = r.ReadName(r.Position);
r.Position = endPos + 4; // QTYPE + QCLASS
}
var total = anCount + nsCount + arCount;
for (var i = 0; i < total; i++)
{
if (r.Remaining < 10)
break;
var (name, endPos) = r.ReadName(r.Position);
r.Position = endPos;
var type = r.ReadUInt16();
var _class = r.ReadUInt16();
r.ReadUInt32(); // TTL
var rdLength = r.ReadUInt16();
if (r.Remaining < rdLength)
break;
var rdataStart = r.Position;
var isCacheFlush = (_class & 0x8000) != 0;
_ = isCacheFlush;
switch (type)
{
case 12: // PTR
var (ptrName, _) = r.ReadName(rdataStart);
replies.Add(new MdnsReply(ptrName, 12, null, null, null, null));
break;
case 33: // SRV
var srv = r.ReadBytes(rdLength);
if (srv.Length >= 6)
{
var port = BinaryPrimitives.ReadUInt16BigEndian(srv.AsSpan(4, 2));
var srvReader = new PacketReader(srv);
srvReader.Position = 6;
var (target, _) = srvReader.ReadName(6);
replies.Add(new MdnsReply(name, 33, target, port, null, null));
}
break;
case 16: // TXT
var txt = ParseTxt(r.ReadBytes(rdLength));
replies.Add(new MdnsReply(name, 16, null, null, txt, null));
break;
case 1: // A
var a = r.ReadBytes(rdLength);
if (a.Length == 4)
replies.Add(new MdnsReply(name, 1, null, null, null, new IPAddress(a).ToString()));
break;
default:
break;
}
// Always advance to the end of this record's rdata so the next
// record parses from the right offset.
r.Position = rdataStart + rdLength;
}
}
catch (Exception ex)
{
// Malformed packet — ignore (mDNS traffic is noisy).
_ = ex;
}
return replies;
}
private static Dictionary<string, string> ParseTxt(byte[] data)
{
var dict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
var offset = 0;
while (offset < data.Length)
{
var length = data[offset];
offset++;
if (length == 0 || offset + length > data.Length)
break;
var entry = Encoding.ASCII.GetString(data, offset, length);
var eq = entry.IndexOf('=');
if (eq > 0)
dict[entry[..eq]] = entry[(eq + 1)..];
else if (entry.Length > 0)
dict[entry] = "";
offset += length;
}
return dict;
}
// ─── Assembly ────────────────────────────────────────────────────
/// <summary>
/// Group raw replies by instance name and build HomeKit devices.
/// Keeps categories 17 (camera) and 18 (doorbell); sf=1 (already paired)
/// devices are still returned — they are real cameras, just paired.
/// </summary>
private static List<HomeKitDevice> BuildDevices(List<MdnsReply> replies)
{
// instance name → TXT / SRV / A records
var byInstance = new Dictionary<string, (Dictionary<string, string> Txt, string? SrvTarget, int? Port, List<string> Ips)>(StringComparer.OrdinalIgnoreCase);
foreach (var reply in replies)
{
if (reply.Type == 12) // PTR: instance = target; only the PTR name matters
{
if (!byInstance.ContainsKey(reply.Instance))
byInstance[reply.Instance] = (new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase), null, null, []);
continue;
}
var key = reply.Instance;
if (!byInstance.TryGetValue(key, out var existing))
{
existing = (new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase), null, null, []);
byInstance[key] = existing;
}
if (reply.Type == 16 && reply.Txt is not null)
{
foreach (var (k, v) in reply.Txt)
existing.Txt[k] = v;
}
else if (reply.Type == 33)
{
existing = existing with { SrvTarget = reply.SrvTarget, Port = reply.SrvPort };
byInstance[key] = existing;
}
else if (reply.Type == 1 && reply.Address is not null && !existing.Ips.Contains(reply.Address))
{
existing.Ips.Add(reply.Address);
}
}
var devices = new List<HomeKitDevice>();
var seenIps = new HashSet<string>(StringComparer.Ordinal);
// A records are named by the SRV target host (cam1.local), not by the
// instance name — build a host → IP map for the SRV target resolution.
var addressByHost = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var reply in replies)
{
if (reply.Type == 1 && reply.Address is not null)
addressByHost[reply.Instance] = reply.Address;
}
foreach (var (instance, info) in byInstance)
{
if (!int.TryParse(info.Txt.GetValueOrDefault("ci"), out var category))
continue;
if (category is not (17 or 18))
continue; // only cameras + doorbells
// IP: A record of the instance itself, then A record of the SRV
// target host, then any A record seen (best effort).
var ip = info.Ips.FirstOrDefault()
?? (info.SrvTarget is not null && addressByHost.TryGetValue(info.SrvTarget, out var srvIp) ? srvIp : null)
?? addressByHost.Values.FirstOrDefault()
?? "";
if (string.IsNullOrEmpty(ip) || !seenIps.Add(ip))
continue;
var name = instance.Split('.')[0]; // "Camera-ABCDEF._hap._tcp.local" → "Camera-ABCDEF"
var deviceId = info.Txt.GetValueOrDefault("id")
?? $"{ip}/{info.Txt.GetValueOrDefault("md", "unknown")}";
var model = info.Txt.GetValueOrDefault("md") ?? "HomeKit";
var sf = info.Txt.GetValueOrDefault("sf") ?? "0";
devices.Add(new HomeKitDevice(
ip,
name,
deviceId,
model,
category,
IsPaired: sf != "0",
Port: info.Port ?? MdnsPort));
}
return devices;
}
}
@@ -56,12 +56,17 @@ public sealed class NetworkCameraScanner
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;
private readonly HomeKitMdnsProbe _homeKitProbe;
private readonly string? _localIp;
private readonly string? _gatewayIp;
public NetworkCameraScanner(ILogger<NetworkCameraScanner> logger)
public NetworkCameraScanner(
ILogger<NetworkCameraScanner> logger,
HomeKitMdnsProbe? homeKitProbe = null)
{
_logger = logger;
_homeKitProbe = homeKitProbe ?? new HomeKitMdnsProbe(
Microsoft.Extensions.Logging.Abstractions.NullLogger<HomeKitMdnsProbe>.Instance);
var (localIp, gatewayIp) = GetLocalNetworkInfo();
_localIp = localIp;
_gatewayIp = gatewayIp;
@@ -162,6 +167,12 @@ public sealed class NetworkCameraScanner
if (!HasDefinitiveCameraEvidence(device) && !HasCameraPorts(device))
return null;
// 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;
// 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.
@@ -201,6 +212,50 @@ public sealed class NetworkCameraScanner
var devices = new List<AgentDiscoveredDevice>();
devices.AddRange(await DiscoverOnvifMulticastAsync(credentialPool, ct).ConfigureAwait(false));
devices.AddRange(await DiscoverDvripAsync(ct).ConfigureAwait(false));
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,
OpenPorts: [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));
}
}
catch (Exception ex)
{
_logger.LogWarning(ex, "HomeKit mDNS discovery failed");
}
return devices;
}