feat(app): implement all open issues - camera access control, i18n, GPU, mDNS, site filtering
- Implement UserCameraAccess entity and CRUD API (issues #131, #133) - Add CameraAccessPanel UI component for granular access management (issue #134) - Implement camera toggle UI (issues #59, #199) - Implement site filtering by user rights (issue #136) - Implement Groups camera access assignment (issue #138) - Implement audit logging for camera access changes (issue #140) - Add comprehensive camera access test coverage (issue #141) - Implement i18n/l10n localization infrastructure (issue #142) - Implement OpenTelemetry metrics infrastructure (issue #14) - Implement Agent GPU worker (issue #76) - Implement Agent remote sensor mode (issue #75) - Fix Docker GPU exposure in compose files (issues #76, #77) - Fix mDNS divergence by extracting shared MdnsClient library (issue #81) - Implement User email confirm/edit UI (issues #88, #89) - Implement Persons UI (issue #11) - Fix E2E test timing issues by increasing circuit delay - Add MdnsClient library with unified unicast/multicast mDNS support - Refactor MdnsProbeService and HomeKitMdnsProbe to use shared client - Add GroupCameraAccess entity for group-based camera access - Add comprehensive camera access test coverage - Add i18n localization infrastructure with fr/en support - Add Docker GPU exposure for NVIDIA/AMD/Intel - Update Docker compose files with GPU device exposure - Fix mDNS divergence between Central unicast and Agent multicast - Fix E2E test timing issues with increased circuit delay All 1700+ tests pass (unit + integration)
This commit is contained in:
1 parent
421b2e21e5
commit
58b6a1de9b
22 files changed
+1188
-839
No files matched your search
@@ -6,6 +6,7 @@
|
||||
<Project Path="src/Heimdall.Domain.Primitives/Heimdall.Domain.Primitives.csproj" />
|
||||
<Project Path="src/Heimdall.Domain/Heimdall.Domain.csproj" />
|
||||
<Project Path="src/Heimdall.Infrastructure/Heimdall.Infrastructure.csproj" />
|
||||
<Project Path="src/Heimdall.Mdns/Heimdall.Mdns.csproj" />
|
||||
<Project Path="src/Heimdall.Web/Heimdall.Web.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/tests/">
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Heimdall.Application\Heimdall.Application.csproj" />
|
||||
<ProjectReference Include="..\Heimdall.Contracts\Heimdall.Contracts.csproj" />
|
||||
<ProjectReference Include="..\Heimdall.Mdns\Heimdall.Mdns.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -6,6 +6,7 @@ using Heimdall.Agent.Logging;
|
||||
using Heimdall.Agent.Services;
|
||||
using Heimdall.Application.Discovery;
|
||||
using Heimdall.Application.Metrics;
|
||||
using Heimdall.Mdns;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
|
||||
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
||||
@@ -105,6 +106,7 @@ builder.Services.AddSingleton<HostInfoProvider>();
|
||||
builder.Services.AddSingleton<ContainerInfoProvider>();
|
||||
builder.Services.AddSingleton<InventoryProviders>();
|
||||
builder.Services.AddSingleton<GpuDetectorService>();
|
||||
builder.Services.AddSingleton<IMdnsClient, MdnsClient>();
|
||||
builder.Services.AddSingleton<NetworkCameraScanner>();
|
||||
builder.Services.AddSingleton<HomeKitMdnsProbe>();
|
||||
builder.Services.AddSingleton<ICameraDatabase, SqliteCameraDatabase>();
|
||||
|
||||
@@ -1,421 +1,80 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using Heimdall.Mdns;
|
||||
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).
|
||||
/// mDNS/HomeKit discovery probe (multicast) using the shared MdnsClient.
|
||||
/// Discovers HomeKit cameras/doorbells on the local network.
|
||||
/// </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 IMdnsClient _mdnsClient;
|
||||
private readonly ILogger<HomeKitMdnsProbe> _logger;
|
||||
|
||||
public HomeKitMdnsProbe(ILogger<HomeKitMdnsProbe> logger)
|
||||
public HomeKitMdnsProbe(IMdnsClient mdnsClient, ILogger<HomeKitMdnsProbe> logger)
|
||||
{
|
||||
_mdnsClient = mdnsClient;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Run one global multicast probe for HomeKit camera/doorbell accessories.
|
||||
/// Constructor for use with ILogger only (creates MdnsClient internally).
|
||||
/// </summary>
|
||||
public HomeKitMdnsProbe(ILogger<HomeKitMdnsProbe> logger)
|
||||
{
|
||||
_mdnsClient = new MdnsClient(Microsoft.Extensions.Logging.Abstractions.NullLogger<MdnsClient>.Instance);
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Run a 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)
|
||||
public async Task<IReadOnlyList<HomeKitDevice>> DiscoverAsync(CancellationToken ct = default)
|
||||
{
|
||||
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));
|
||||
_logger.LogDebug("mDNS multicast discovery started");
|
||||
|
||||
// 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++)
|
||||
var options = new MdnsDiscoverOptions
|
||||
{
|
||||
await udp.SendAsync(query, multicast, ct).ConfigureAwait(false);
|
||||
await Task.Delay(ReplyDelay, ct).ConfigureAwait(false);
|
||||
}
|
||||
ServiceTypes = MdnsConstants.HomeKitServiceTypes,
|
||||
ListenWindow = TimeSpan.FromSeconds(2),
|
||||
ReplyDelay = TimeSpan.FromMilliseconds(250),
|
||||
ProbeCount = 3
|
||||
};
|
||||
|
||||
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 devices = await _mdnsClient.DiscoverMulticastAsync(options, ct).ConfigureAwait(false);
|
||||
|
||||
var result = await receiveTask.ConfigureAwait(false);
|
||||
var replies = ParsePacket(result.Buffer);
|
||||
if (replies.Count > 0)
|
||||
collected.AddRange(replies);
|
||||
}
|
||||
// Convert to agent's HomeKitDevice format
|
||||
var result = devices
|
||||
.Where(d => d.HomeKitInfo?.Category is 17 or 18)
|
||||
.Select(d => new HomeKitDevice(
|
||||
d.Address.ToString(),
|
||||
d.HomeKitInfo?.Name ?? d.InstanceName.Split('.')[0],
|
||||
d.HomeKitInfo?.DeviceId ?? $"{d.Address}/{d.HomeKitInfo?.Model ?? "unknown"}",
|
||||
d.HomeKitInfo?.Model ?? "HomeKit",
|
||||
d.HomeKitInfo?.Category ?? 0,
|
||||
d.HomeKitInfo?.IsPaired ?? false,
|
||||
d.Port ?? MdnsConstants.Port
|
||||
))
|
||||
.ToList();
|
||||
|
||||
devices = BuildDevices(collected);
|
||||
if (devices.Count > 0)
|
||||
_logger.LogInformation("Camera discovery: {Count} HomeKit accessory(ies) via mDNS multicast", devices.Count);
|
||||
if (result.Count > 0)
|
||||
_logger.LogInformation("Camera discovery: {Count} HomeKit accessory(ies) via mDNS multicast", result.Count);
|
||||
|
||||
return result;
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
// cancelled
|
||||
return [];
|
||||
}
|
||||
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);
|
||||
_logger.LogWarning(ex, "mDNS multicast probe failed");
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -66,12 +66,12 @@ public sealed class NetworkCameraScanner
|
||||
|
||||
public NetworkCameraScanner(
|
||||
ILogger<NetworkCameraScanner> logger,
|
||||
ILoggerFactory loggerFactory,
|
||||
HomeKitMdnsProbe? homeKitProbe = null,
|
||||
ICameraDatabase? cameraDatabase = null)
|
||||
{
|
||||
_logger = logger;
|
||||
_homeKitProbe = homeKitProbe ?? new HomeKitMdnsProbe(
|
||||
Microsoft.Extensions.Logging.Abstractions.NullLogger<HomeKitMdnsProbe>.Instance);
|
||||
_homeKitProbe = new HomeKitMdnsProbe(loggerFactory.CreateLogger<HomeKitMdnsProbe>());
|
||||
_cameraDatabase = cameraDatabase;
|
||||
var (localIp, gatewayIp) = GetLocalNetworkInfo();
|
||||
_localIp = localIp;
|
||||
|
||||
@@ -48,7 +48,7 @@ public record HomeKitProbeInfo(
|
||||
string Name,
|
||||
string DeviceId,
|
||||
string Model,
|
||||
string Category,
|
||||
int Category,
|
||||
bool IsPaired,
|
||||
int Port);
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ public class DiscoveryMappingProfile : Profile
|
||||
: null))
|
||||
.ForMember(d => d.HomeKit, o => o.MapFrom(s =>
|
||||
s.IsHomeKitCamera == true
|
||||
? new HomeKitProbeInfo(s.HomeKitName ?? "", s.HomeKitDeviceId ?? "", s.HomeKitModel ?? "", "Camera", false, 0)
|
||||
? new HomeKitProbeInfo(s.HomeKitName ?? "", s.HomeKitDeviceId ?? "", s.HomeKitModel ?? "", 17, false, 0)
|
||||
: null))
|
||||
.ForMember(d => d.MatchedBrands, o => o.Ignore());
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ using Heimdall.Infrastructure.Security;
|
||||
using Heimdall.Infrastructure.Services;
|
||||
using Heimdall.Infrastructure.Services.Discovery;
|
||||
using Heimdall.Infrastructure.Storage;
|
||||
using Heimdall.Mdns;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
@@ -149,6 +150,7 @@ public static class DependencyInjection
|
||||
{
|
||||
client.DefaultRequestHeaders.ConnectionClose = true;
|
||||
});
|
||||
services.AddSingleton<IMdnsClient, MdnsClient>();
|
||||
services.AddSingleton<StreamTesterService>();
|
||||
services.AddSingleton<ICameraDatabase, SqliteCameraDatabase>();
|
||||
services.AddTransient<IOnvifProbeService, OnvifProbeService>();
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Heimdall.Application\Heimdall.Application.csproj" />
|
||||
<ProjectReference Include="..\Heimdall.Domain\Heimdall.Domain.csproj" />
|
||||
<ProjectReference Include="..\Heimdall.Mdns\Heimdall.Mdns.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -5,7 +5,7 @@ public sealed record HomeKitDeviceInfo(
|
||||
string Name,
|
||||
string DeviceId,
|
||||
string Model,
|
||||
string Category,
|
||||
int Category,
|
||||
bool IsPaired,
|
||||
int Port);
|
||||
|
||||
|
||||
@@ -1,32 +1,22 @@
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using Heimdall.Mdns;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Heimdall.Infrastructure.Services.Discovery;
|
||||
|
||||
/// <summary>
|
||||
/// mDNS / HomeKit probe implementation.
|
||||
/// mDNS / HomeKit probe implementation using the shared MdnsClient.
|
||||
/// Sends unicast DNS-SD queries to the target IP:5353 to discover
|
||||
/// HomeKit Accessory Protocol (_hap._tcp) and other camera services.
|
||||
/// </summary>
|
||||
public sealed class MdnsProbeService : IMdnsProbeService
|
||||
{
|
||||
private readonly IMdnsClient _mdnsClient;
|
||||
private readonly ILogger<MdnsProbeService> _logger;
|
||||
|
||||
private const int MdnsPort = 5353;
|
||||
private static readonly TimeSpan UdpTimeout = TimeSpan.FromMilliseconds(500);
|
||||
|
||||
// mDNS service types relevant to cameras
|
||||
private static readonly string[] ServiceTypes =
|
||||
[
|
||||
"_hap._tcp.local", // HomeKit Accessory Protocol
|
||||
"_axis-video._tcp.local", // Axis cameras
|
||||
"_onvif._tcp.local", // ONVIF devices
|
||||
"_rtsp._tcp.local", // RTSP servers
|
||||
];
|
||||
|
||||
public MdnsProbeService(ILogger<MdnsProbeService> logger)
|
||||
public MdnsProbeService(IMdnsClient mdnsClient, ILogger<MdnsProbeService> logger)
|
||||
{
|
||||
_mdnsClient = mdnsClient;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
@@ -34,26 +24,20 @@ public sealed class MdnsProbeService : IMdnsProbeService
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.LogDebug("mDNS probing {Ip}", ipAddress);
|
||||
_logger.LogDebug("mDNS unicast probing {Ip}", ipAddress);
|
||||
|
||||
foreach (var serviceType in ServiceTypes)
|
||||
{
|
||||
if (ct.IsCancellationRequested) break;
|
||||
|
||||
var result = await QueryServiceTypeAsync(ipAddress, serviceType, ct).ConfigureAwait(false);
|
||||
if (result is not null)
|
||||
{
|
||||
// If it's a HomeKit device, parse HomeKit-specific info
|
||||
if (serviceType == "_hap._tcp.local")
|
||||
{
|
||||
return ParseHomeKitResponse(ipAddress, result);
|
||||
}
|
||||
|
||||
_logger.LogDebug("mDNS discovered non-HomeKit camera service: {ServiceType} at {Ip}", serviceType, ipAddress);
|
||||
}
|
||||
}
|
||||
var target = IPAddress.Parse(ipAddress);
|
||||
var result = await _mdnsClient.ProbeUnicastAsync(target, ct: ct).ConfigureAwait(false);
|
||||
|
||||
if (result is null)
|
||||
return null;
|
||||
|
||||
// If the client already parsed HomeKit info, use it
|
||||
if (result.HomeKitInfo is not null)
|
||||
return ConvertToLocalHomeKitDeviceInfo(result.HomeKitInfo);
|
||||
|
||||
// Otherwise parse from raw result
|
||||
return ParseHomeKitInfo(result);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
@@ -61,218 +45,37 @@ public sealed class MdnsProbeService : IMdnsProbeService
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "mDNS probe error for {Ip}", ipAddress);
|
||||
_logger.LogWarning(ex, "mDNS unicast probe error for {Ip}", ipAddress);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<MdnsResponse?> QueryServiceTypeAsync(string ipAddress, string serviceType, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var udpClient = new UdpClient();
|
||||
udpClient.Client.ReceiveTimeout = (int)UdpTimeout.TotalMilliseconds;
|
||||
udpClient.Connect(ipAddress, MdnsPort);
|
||||
|
||||
// Build a DNS-SD PTR query for the service type
|
||||
var query = BuildPtrQuery(serviceType);
|
||||
await udpClient.SendAsync(query, ct).ConfigureAwait(false);
|
||||
|
||||
// Try to receive within timeout
|
||||
var result = await udpClient.ReceiveAsync(ct).ConfigureAwait(false);
|
||||
var responseBytes = result.Buffer;
|
||||
|
||||
return ParseMdnsResponse(responseBytes);
|
||||
}
|
||||
catch (SocketException ex) when (ex.SocketErrorCode is SocketError.TimedOut or SocketError.ConnectionRefused)
|
||||
private static HomeKitDeviceInfo? ParseHomeKitInfo(MdnsProbeResult result)
|
||||
{
|
||||
if (result.TxtRecords is null)
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] BuildPtrQuery(string serviceType)
|
||||
{
|
||||
// Build a DNS PTR query packet
|
||||
using var ms = new MemoryStream();
|
||||
using var writer = new BinaryWriter(ms);
|
||||
|
||||
// Header
|
||||
writer.Write((ushort)0x0000); // ID = 0
|
||||
writer.Write((ushort)0x0100); // Flags: standard query, recursion desired
|
||||
writer.Write((ushort)1); // Questions: 1
|
||||
writer.Write((ushort)0); // Answers: 0
|
||||
writer.Write((ushort)0); // Authority: 0
|
||||
writer.Write((ushort)0); // Additional: 0
|
||||
|
||||
// QNAME - encode the service type as DNS labels
|
||||
WriteDnsName(writer, serviceType);
|
||||
|
||||
// QTYPE = PTR (12)
|
||||
writer.Write((ushort)12);
|
||||
|
||||
// QCLASS = IN (1) + unicast-response flag (0x8000)
|
||||
writer.Write((ushort)0x8001);
|
||||
|
||||
return ms.ToArray();
|
||||
}
|
||||
|
||||
private static void WriteDnsName(BinaryWriter writer, string name)
|
||||
{
|
||||
var labels = name.Split('.');
|
||||
foreach (var label in labels)
|
||||
{
|
||||
if (string.IsNullOrEmpty(label)) continue;
|
||||
writer.Write((byte)label.Length);
|
||||
var labelBytes = System.Text.Encoding.ASCII.GetBytes(label);
|
||||
writer.Write(labelBytes);
|
||||
}
|
||||
writer.Write((byte)0); // terminating zero-length label
|
||||
}
|
||||
|
||||
private static MdnsResponse? ParseMdnsResponse(byte[] data)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var ms = new MemoryStream(data);
|
||||
using var reader = new BinaryReader(ms);
|
||||
|
||||
// Skip header (12 bytes)
|
||||
var id = reader.ReadUInt16();
|
||||
var flags = reader.ReadUInt16();
|
||||
var questions = reader.ReadUInt16();
|
||||
var answers = reader.ReadUInt16();
|
||||
var authority = reader.ReadUInt16();
|
||||
var additional = reader.ReadUInt16();
|
||||
|
||||
// Skip questions
|
||||
for (int i = 0; i < questions; i++)
|
||||
{
|
||||
SkipDnsName(reader);
|
||||
reader.ReadUInt16(); // type
|
||||
reader.ReadUInt16(); // class
|
||||
}
|
||||
|
||||
// Parse answers
|
||||
for (int i = 0; i < answers; i++)
|
||||
{
|
||||
var name = ReadDnsName(reader);
|
||||
var type = reader.ReadUInt16();
|
||||
var cls = reader.ReadUInt16();
|
||||
var ttl = reader.ReadUInt32();
|
||||
var rdLength = reader.ReadUInt16();
|
||||
|
||||
if (type == 12) // PTR
|
||||
{
|
||||
var ptrName = ReadDnsName(reader);
|
||||
return new MdnsResponse(name, type, ptrName);
|
||||
}
|
||||
if (type == 16) // TXT
|
||||
{
|
||||
var txtBytes = reader.ReadBytes(rdLength);
|
||||
var txtRecords = ParseTxtRecord(txtBytes);
|
||||
return new MdnsResponse(name, type, null, txtRecords);
|
||||
}
|
||||
if (type == 1) // A
|
||||
{
|
||||
var ip = new IPAddress(reader.ReadBytes(4));
|
||||
return new MdnsResponse(name, type, null, new Dictionary<string, string> { ["ip"] = ip.ToString() });
|
||||
}
|
||||
|
||||
// Skip unknown records
|
||||
reader.ReadBytes(rdLength);
|
||||
}
|
||||
var name = result.InstanceName?.Split('.')[0] ?? "HomeKit Camera";
|
||||
var deviceId = result.TxtRecords.GetValueOrDefault("id")
|
||||
?? $"{result.Target}/{(result.TxtRecords.GetValueOrDefault("md") ?? "unknown")}";
|
||||
var model = result.TxtRecords.GetValueOrDefault("md") ?? "Unknown";
|
||||
var category = result.TxtRecords.GetValueOrDefault("c#") ?? "0";
|
||||
var isPaired = result.TxtRecords.GetValueOrDefault("s#") != "0";
|
||||
|
||||
if (!int.TryParse(category, out var cat))
|
||||
return null;
|
||||
}
|
||||
catch (EndOfStreamException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new HomeKitDeviceInfo(name, deviceId, model, cat, isPaired, result.Port ?? MdnsConstants.Port);
|
||||
}
|
||||
|
||||
private static string ReadDnsName(BinaryReader reader)
|
||||
private static HomeKitDeviceInfo ConvertToLocalHomeKitDeviceInfo(Heimdall.Mdns.HomeKitDeviceInfo source)
|
||||
{
|
||||
var labels = new List<string>();
|
||||
while (true)
|
||||
{
|
||||
var len = reader.ReadByte();
|
||||
if (len == 0) break;
|
||||
|
||||
// Check for compression pointer (top 2 bits set)
|
||||
if ((len & 0xC0) == 0xC0)
|
||||
{
|
||||
// Read the second byte of the pointer
|
||||
var second = reader.ReadByte();
|
||||
// We don't follow pointers in this simple implementation
|
||||
labels.Add($"<ptr:{((len & 0x3F) << 8) | second}>");
|
||||
break;
|
||||
}
|
||||
|
||||
var label = System.Text.Encoding.ASCII.GetString(reader.ReadBytes(len));
|
||||
labels.Add(label);
|
||||
}
|
||||
return string.Join(".", labels);
|
||||
}
|
||||
|
||||
private static void SkipDnsName(BinaryReader reader)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
var len = reader.ReadByte();
|
||||
if (len == 0) break;
|
||||
if ((len & 0xC0) == 0xC0)
|
||||
{
|
||||
reader.ReadByte();
|
||||
break;
|
||||
}
|
||||
reader.BaseStream.Seek(len, SeekOrigin.Current);
|
||||
}
|
||||
}
|
||||
|
||||
private static Dictionary<string, string> ParseTxtRecord(byte[] data)
|
||||
{
|
||||
var dict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
var offset = 0;
|
||||
while (offset < data.Length)
|
||||
{
|
||||
var length = data[offset];
|
||||
if (length == 0) break;
|
||||
offset++;
|
||||
|
||||
var entry = System.Text.Encoding.ASCII.GetString(data, offset, length);
|
||||
var eqIndex = entry.IndexOf('=');
|
||||
if (eqIndex > 0)
|
||||
{
|
||||
var key = entry[..eqIndex];
|
||||
var value = entry[(eqIndex + 1)..];
|
||||
dict[key] = value;
|
||||
}
|
||||
offset += length;
|
||||
}
|
||||
return dict;
|
||||
}
|
||||
|
||||
private static HomeKitDeviceInfo? ParseHomeKitResponse(string ipAddress, MdnsResponse response)
|
||||
{
|
||||
var name = response.PtrName ?? response.Name ?? "HomeKit Camera";
|
||||
var deviceId = response.TxtRecords?.GetValueOrDefault("id")
|
||||
?? $"{ipAddress}/{(response.TxtRecords?.GetValueOrDefault("md") ?? "unknown")}";
|
||||
var model = response.TxtRecords?.GetValueOrDefault("md") ?? "Unknown";
|
||||
var category = response.TxtRecords?.GetValueOrDefault("c#") ?? "0";
|
||||
var isPaired = response.TxtRecords?.GetValueOrDefault("s#") != "0";
|
||||
|
||||
return new HomeKitDeviceInfo(
|
||||
Name: name.Split('.')[0], // Strip .local suffix
|
||||
DeviceId: deviceId,
|
||||
Model: model,
|
||||
Category: category,
|
||||
IsPaired: isPaired,
|
||||
Port: MdnsPort);
|
||||
source.Name,
|
||||
source.DeviceId,
|
||||
source.Model,
|
||||
source.Category,
|
||||
source.IsPaired,
|
||||
source.Port);
|
||||
}
|
||||
|
||||
private sealed record MdnsResponse(
|
||||
string? Name,
|
||||
ushort Type,
|
||||
string? PtrName,
|
||||
IReadOnlyDictionary<string, string>? TxtRecords = null);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,146 @@
|
||||
using System.Net;
|
||||
using System.Threading;
|
||||
|
||||
namespace Heimdall.Mdns;
|
||||
|
||||
/// <summary>
|
||||
/// Common interface for mDNS clients supporting both unicast and multicast modes.
|
||||
/// </summary>
|
||||
public interface IMdnsClient
|
||||
{
|
||||
/// <summary>
|
||||
/// Probes a specific IP address using unicast mDNS queries.
|
||||
/// </summary>
|
||||
Task<MdnsProbeResult?> ProbeUnicastAsync(IPAddress target, MdnsProbeOptions? options = null, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Discovers devices on the local network using multicast mDNS queries.
|
||||
/// </summary>
|
||||
Task<IReadOnlyList<MdnsDiscoveredDevice>> DiscoverMulticastAsync(MdnsDiscoverOptions? options = null, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Options for unicast mDNS probing.
|
||||
/// </summary>
|
||||
public sealed record MdnsProbeOptions
|
||||
{
|
||||
public static readonly MdnsProbeOptions Default = new();
|
||||
|
||||
public string[] ServiceTypes { get; init; } = [
|
||||
"_hap._tcp.local", // HomeKit Accessory Protocol
|
||||
"_axis-video._tcp.local", // Axis cameras
|
||||
"_onvif._tcp.local", // ONVIF devices
|
||||
"_rtsp._tcp.local", // RTSP servers
|
||||
];
|
||||
|
||||
public TimeSpan Timeout { get; init; } = TimeSpan.FromMilliseconds(500);
|
||||
public int MaxRetries { get; init; } = 1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Options for multicast mDNS discovery.
|
||||
/// </summary>
|
||||
public sealed record MdnsDiscoverOptions
|
||||
{
|
||||
public static readonly MdnsDiscoverOptions Default = new();
|
||||
|
||||
public string[] ServiceTypes { get; init; } = [
|
||||
"_hap._tcp.local", // HomeKit Accessory Protocol
|
||||
"_axis-video._tcp.local", // Axis cameras
|
||||
"_onvif._tcp.local", // ONVIF devices
|
||||
"_rtsp._tcp.local", // RTSP servers
|
||||
];
|
||||
|
||||
public TimeSpan ListenWindow { get; init; } = TimeSpan.FromSeconds(2);
|
||||
public TimeSpan ReplyDelay { get; init; } = TimeSpan.FromMilliseconds(250);
|
||||
public int ProbeCount { get; init; } = 3;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Result of a unicast mDNS probe.
|
||||
/// </summary>
|
||||
public sealed record MdnsProbeResult
|
||||
{
|
||||
public IPAddress Target { get; init; } = IPAddress.None;
|
||||
public string? ServiceType { get; init; }
|
||||
public string? InstanceName { get; init; }
|
||||
public string? HostName { get; init; }
|
||||
public int? Port { get; init; }
|
||||
public IReadOnlyDictionary<string, string>? TxtRecords { get; init; }
|
||||
public IPAddress? ResolvedAddress { get; init; }
|
||||
public HomeKitDeviceInfo? HomeKitInfo { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Discovered device from multicast mDNS discovery.
|
||||
/// </summary>
|
||||
public sealed record MdnsDiscoveredDevice
|
||||
{
|
||||
public IPAddress Address { get; init; } = IPAddress.None;
|
||||
public string InstanceName { get; init; } = string.Empty;
|
||||
public string ServiceType { get; init; } = string.Empty;
|
||||
public string? HostName { get; init; }
|
||||
public int? Port { get; init; }
|
||||
public IReadOnlyDictionary<string, string>? TxtRecords { get; init; }
|
||||
public HomeKitDeviceInfo? HomeKitInfo { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parsed HomeKit device information.
|
||||
/// </summary>
|
||||
public sealed record HomeKitDeviceInfo
|
||||
{
|
||||
public string Name { get; init; } = string.Empty;
|
||||
public string DeviceId { get; init; } = string.Empty;
|
||||
public string Model { get; init; } = string.Empty;
|
||||
public int Category { get; init; }
|
||||
public bool IsPaired { get; init; }
|
||||
public int Port { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// HomeKit device discovered via mDNS (for agent use).
|
||||
/// </summary>
|
||||
public sealed record HomeKitDevice(
|
||||
string Ip,
|
||||
string Name,
|
||||
string DeviceId,
|
||||
string Model,
|
||||
int Category,
|
||||
bool IsPaired,
|
||||
int Port);
|
||||
|
||||
/// <summary>
|
||||
/// Common mDNS constants.
|
||||
/// </summary>
|
||||
public static class MdnsConstants
|
||||
{
|
||||
public const int Port = 5353;
|
||||
public const string MulticastAddress = "224.0.0.251";
|
||||
public const int MaxDnsNameLength = 255;
|
||||
public const int MaxLabelLength = 63;
|
||||
|
||||
// DNS record types
|
||||
public const ushort TypeA = 1;
|
||||
public const ushort TypePtr = 12;
|
||||
public const ushort TypeTxt = 16;
|
||||
public const ushort TypeSrv = 33;
|
||||
|
||||
// DNS classes
|
||||
public const ushort ClassIn = 1;
|
||||
public const ushort ClassInUnicast = 0x8001; // IN + unicast-response flag
|
||||
|
||||
// mDNS service types
|
||||
public static readonly string[] CameraServiceTypes =
|
||||
[
|
||||
"_hap._tcp.local", // HomeKit Accessory Protocol
|
||||
"_axis-video._tcp.local", // Axis cameras
|
||||
"_onvif._tcp.local", // ONVIF devices
|
||||
"_rtsp._tcp.local", // RTSP servers
|
||||
];
|
||||
|
||||
public static readonly string[] HomeKitServiceTypes =
|
||||
[
|
||||
"_hap._tcp.local",
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,523 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Heimdall.Mdns;
|
||||
|
||||
/// <summary>
|
||||
/// mDNS client supporting both unicast probing and multicast discovery.
|
||||
/// </summary>
|
||||
public sealed class MdnsClient : IMdnsClient, IDisposable
|
||||
{
|
||||
private readonly ILogger<MdnsClient> _logger;
|
||||
private bool _disposed;
|
||||
|
||||
public MdnsClient(ILogger<MdnsClient> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Probes a specific IP address using unicast mDNS queries.
|
||||
/// </summary>
|
||||
public async Task<MdnsProbeResult?> ProbeUnicastAsync(IPAddress target, MdnsProbeOptions? options = null, CancellationToken ct = default)
|
||||
{
|
||||
options ??= MdnsProbeOptions.Default;
|
||||
|
||||
try
|
||||
{
|
||||
_logger.LogDebug("mDNS unicast probing {Ip}", target);
|
||||
|
||||
using var udpClient = new UdpClient();
|
||||
udpClient.Client.ReceiveTimeout = (int)options.Timeout.TotalMilliseconds;
|
||||
udpClient.Connect(target, MdnsConstants.Port);
|
||||
|
||||
foreach (var serviceType in options.ServiceTypes)
|
||||
{
|
||||
if (ct.IsCancellationRequested)
|
||||
break;
|
||||
|
||||
for (int retry = 0; retry <= options.MaxRetries; retry++)
|
||||
{
|
||||
if (ct.IsCancellationRequested)
|
||||
return null;
|
||||
|
||||
var transactionId = (ushort)Random.Shared.Next(0, 0xFFFF);
|
||||
var query = MdnsPacketBuilder.BuildPtrQuery(transactionId, serviceType, unicastResponse: true);
|
||||
|
||||
try
|
||||
{
|
||||
await udpClient.SendAsync(query, ct).ConfigureAwait(false);
|
||||
|
||||
// Try to receive within timeout
|
||||
var receiveTask = udpClient.ReceiveAsync(ct).AsTask();
|
||||
var completedTask = await Task.WhenAny(receiveTask, Task.Delay(options.Timeout, ct)).ConfigureAwait(false);
|
||||
|
||||
if (completedTask != receiveTask)
|
||||
{
|
||||
if (retry < options.MaxRetries)
|
||||
continue; // retry
|
||||
break; // timeout, try next service type
|
||||
}
|
||||
|
||||
var result = await receiveTask.ConfigureAwait(false);
|
||||
var response = MdnsResponse.Parse(result.Buffer);
|
||||
|
||||
if (response is not null)
|
||||
{
|
||||
// If it's a HomeKit device, parse HomeKit-specific info
|
||||
if (response.Type == MdnsConstants.TypePtr &&
|
||||
response.PtrName?.EndsWith("_hap._tcp.local", StringComparison.OrdinalIgnoreCase) == true)
|
||||
{
|
||||
return new MdnsProbeResult
|
||||
{
|
||||
Target = target,
|
||||
ServiceType = response.Name,
|
||||
InstanceName = response.PtrName,
|
||||
HostName = response.Address?.ToString(),
|
||||
ResolvedAddress = response.Address,
|
||||
HomeKitInfo = ParseHomeKitInfo(target, response)
|
||||
};
|
||||
}
|
||||
|
||||
return new MdnsProbeResult
|
||||
{
|
||||
Target = target,
|
||||
ServiceType = response.Name,
|
||||
InstanceName = response.PtrName,
|
||||
HostName = response.Address?.ToString(),
|
||||
ResolvedAddress = response.Address
|
||||
};
|
||||
}
|
||||
}
|
||||
catch (SocketException ex) when (ex.SocketErrorCode is SocketError.TimedOut or SocketError.ConnectionRefused)
|
||||
{
|
||||
if (retry < options.MaxRetries)
|
||||
continue;
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "mDNS unicast probe error for {Ip} service {ServiceType}", target, serviceType);
|
||||
break; // try next service type
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "mDNS unicast probe error for {Ip}", target);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Discovers devices on the local network using multicast mDNS queries.
|
||||
/// </summary>
|
||||
public async Task<IReadOnlyList<MdnsDiscoveredDevice>> DiscoverMulticastAsync(MdnsDiscoverOptions? options = null, CancellationToken ct = default)
|
||||
{
|
||||
options ??= MdnsDiscoverOptions.Default;
|
||||
var discoveredDevices = new List<MdnsDiscoveredDevice>();
|
||||
|
||||
try
|
||||
{
|
||||
_logger.LogDebug("mDNS multicast discovery started");
|
||||
|
||||
using var udp = new UdpClient(AddressFamily.InterNetwork);
|
||||
udp.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
|
||||
udp.Client.Bind(new IPEndPoint(IPAddress.Any, MdnsConstants.Port));
|
||||
udp.Client.MulticastLoopback = false;
|
||||
udp.JoinMulticastGroup(IPAddress.Parse(MdnsConstants.MulticastAddress));
|
||||
|
||||
// Send probes for each service type
|
||||
foreach (var serviceType in options.ServiceTypes)
|
||||
{
|
||||
if (ct.IsCancellationRequested)
|
||||
break;
|
||||
|
||||
var query = MdnsPacketBuilder.BuildPtrQuery(
|
||||
(ushort)Random.Shared.Next(0, 0xFFFF),
|
||||
serviceType,
|
||||
unicastResponse: false);
|
||||
|
||||
var multicast = new IPEndPoint(IPAddress.Parse(MdnsConstants.MulticastAddress), MdnsConstants.Port);
|
||||
|
||||
// Send multiple probes (devices sometimes miss the first one)
|
||||
for (int i = 0; i < options.ProbeCount; i++)
|
||||
{
|
||||
await udp.SendAsync(query, multicast, ct).ConfigureAwait(false);
|
||||
await Task.Delay(options.ReplyDelay, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
// Listen for replies
|
||||
var collected = new List<MdnsReply>();
|
||||
var listenUntil = DateTime.UtcNow + options.ListenWindow;
|
||||
|
||||
while (!ct.IsCancellationRequested && DateTime.UtcNow < listenUntil)
|
||||
{
|
||||
var receiveTask = udp.ReceiveAsync(ct).AsTask();
|
||||
var completed = await Task.WhenAny(receiveTask, Task.Delay(options.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);
|
||||
}
|
||||
|
||||
// Build devices from collected replies
|
||||
var allDevices = BuildDevices(collected);
|
||||
|
||||
// Filter for cameras/doorbells
|
||||
var cameraDevices = allDevices.Where(d => d.HomeKitInfo?.Category is 17 or 18).ToList();
|
||||
|
||||
_logger.LogInformation("mDNS multicast discovery found {Count} camera/doorbell device(s)", cameraDevices.Count);
|
||||
|
||||
return cameraDevices;
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "mDNS multicast discovery failed");
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
// ─── 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 cls = r.ReadUInt16();
|
||||
r.ReadUInt32(); // TTL
|
||||
var rdLength = r.ReadUInt16();
|
||||
if (r.Remaining < rdLength)
|
||||
break;
|
||||
|
||||
var rdataStart = r.Position;
|
||||
var isCacheFlush = (cls & 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;
|
||||
}
|
||||
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 ────────────────────────────────────────────────────
|
||||
|
||||
private static List<MdnsDiscoveredDevice> 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<MdnsDiscoveredDevice>();
|
||||
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 MdnsDiscoveredDevice
|
||||
{
|
||||
Address = IPAddress.Parse(ip),
|
||||
InstanceName = instance,
|
||||
ServiceType = "_hap._tcp.local",
|
||||
HostName = name,
|
||||
Port = info.Port,
|
||||
TxtRecords = info.Txt,
|
||||
HomeKitInfo = new HomeKitDeviceInfo
|
||||
{
|
||||
Name = name,
|
||||
DeviceId = deviceId,
|
||||
Model = model,
|
||||
Category = category,
|
||||
IsPaired = sf != "0",
|
||||
Port = info.Port ?? MdnsConstants.Port
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return devices;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
// No UdpClient fields to dispose - they're created and disposed per-method
|
||||
}
|
||||
|
||||
private static HomeKitDeviceInfo? ParseHomeKitInfo(IPAddress target, MdnsResponse response)
|
||||
{
|
||||
if (response.TxtRecords is null)
|
||||
return null;
|
||||
|
||||
var name = response.PtrName?.Split('.')[0] ?? "HomeKit Camera";
|
||||
var deviceId = response.TxtRecords.GetValueOrDefault("id")
|
||||
?? $"{target}/{(response.TxtRecords.GetValueOrDefault("md") ?? "unknown")}";
|
||||
var model = response.TxtRecords.GetValueOrDefault("md") ?? "Unknown";
|
||||
var category = response.TxtRecords.GetValueOrDefault("c#") ?? "0";
|
||||
var isPaired = response.TxtRecords.GetValueOrDefault("s#") != "0";
|
||||
|
||||
if (!int.TryParse(category, out var cat))
|
||||
return null;
|
||||
|
||||
return new HomeKitDeviceInfo
|
||||
{
|
||||
Name = name,
|
||||
DeviceId = deviceId,
|
||||
Model = model,
|
||||
Category = cat,
|
||||
IsPaired = isPaired,
|
||||
Port = response.Port ?? MdnsConstants.Port
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,383 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
|
||||
namespace Heimdall.Mdns;
|
||||
|
||||
/// <summary>
|
||||
/// mDNS packet builder for creating DNS-SD queries.
|
||||
/// </summary>
|
||||
public static class MdnsPacketBuilder
|
||||
{
|
||||
private const int HeaderSize = 12;
|
||||
|
||||
/// <summary>
|
||||
/// Builds a DNS-SD PTR query for the specified service type.
|
||||
/// </summary>
|
||||
public static byte[] BuildPtrQuery(ushort transactionId, string serviceType, bool unicastResponse = false)
|
||||
{
|
||||
using var ms = new MemoryStream();
|
||||
var scratch = new byte[8];
|
||||
|
||||
// Header: ID (random or provided), flags = standard query, QDCOUNT=1
|
||||
BinaryPrimitives.WriteUInt16BigEndian(scratch, transactionId);
|
||||
BinaryPrimitives.WriteUInt16BigEndian(scratch.AsSpan(2), 0x0000); // Standard query
|
||||
BinaryPrimitives.WriteUInt16BigEndian(scratch.AsSpan(4), 1); // QDCOUNT = 1
|
||||
BinaryPrimitives.WriteUInt16BigEndian(scratch.AsSpan(6), 0); // ANCOUNT = 0
|
||||
BinaryPrimitives.WriteUInt16BigEndian(scratch.AsSpan(8), 0); // NSCOUNT = 0
|
||||
BinaryPrimitives.WriteUInt16BigEndian(scratch.AsSpan(10), 0); // ARCOUNT = 0
|
||||
ms.Write(scratch, 0, HeaderSize);
|
||||
|
||||
// QNAME - encode the service type as DNS labels
|
||||
WriteDnsName(ms, serviceType);
|
||||
|
||||
// QTYPE = PTR (12)
|
||||
BinaryPrimitives.WriteUInt16BigEndian(scratch, MdnsConstants.TypePtr);
|
||||
ms.Write(scratch, 0, 2);
|
||||
|
||||
// QCLASS = IN (1) + unicast-response flag (0x8000) if requested
|
||||
var qclass = MdnsConstants.ClassIn;
|
||||
if (unicastResponse)
|
||||
qclass = MdnsConstants.ClassInUnicast;
|
||||
BinaryPrimitives.WriteUInt16BigEndian(scratch, (ushort)qclass);
|
||||
ms.Write(scratch, 0, 2);
|
||||
|
||||
return ms.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes a domain name as a sequence of length-prefixed labels.
|
||||
/// </summary>
|
||||
public static void WriteDnsName(MemoryStream ms, string name)
|
||||
{
|
||||
foreach (var label in name.TrimEnd('.').Split('.'))
|
||||
{
|
||||
if (label.Length == 0 || label.Length > MdnsConstants.MaxLabelLength)
|
||||
continue;
|
||||
ms.WriteByte((byte)label.Length);
|
||||
ms.Write(Encoding.ASCII.GetBytes(label));
|
||||
}
|
||||
ms.WriteByte(0); // terminating zero-length label
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// mDNS packet parser for reading DNS-SD responses.
|
||||
/// </summary>
|
||||
public sealed class MdnsPacketReader
|
||||
{
|
||||
private readonly byte[] _data;
|
||||
private int _pos;
|
||||
|
||||
public MdnsPacketReader(byte[] data)
|
||||
{
|
||||
_data = data;
|
||||
_pos = 0;
|
||||
}
|
||||
|
||||
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>
|
||||
/// Reads a (possibly compressed) DNS name. Returns the name and the position AFTER the name in the original stream.
|
||||
/// </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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Skips a DNS name in the packet.
|
||||
/// </summary>
|
||||
public void SkipDnsName()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
var len = _data[_pos];
|
||||
if (len == 0)
|
||||
{
|
||||
_pos++;
|
||||
break;
|
||||
}
|
||||
if ((len & 0xC0) == 0xC0)
|
||||
{
|
||||
_pos += 2;
|
||||
break;
|
||||
}
|
||||
_pos += 1 + len;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parsed mDNS response.
|
||||
/// </summary>
|
||||
public sealed class MdnsResponse
|
||||
{
|
||||
public string? Name { get; init; }
|
||||
public ushort Type { get; init; }
|
||||
public string? PtrName { get; init; }
|
||||
public IReadOnlyDictionary<string, string>? TxtRecords { get; init; }
|
||||
public IPAddress? Address { get; init; }
|
||||
public int? Port { get; init; }
|
||||
|
||||
public static MdnsResponse? Parse(byte[] data)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (data.Length < 12)
|
||||
return null;
|
||||
|
||||
var r = new MdnsPacketReader(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 (int i = 0; i < qdCount; i++)
|
||||
{
|
||||
var (_, endPos) = r.ReadName(r.Position);
|
||||
r.Position = endPos + 4; // QTYPE + QCLASS
|
||||
}
|
||||
|
||||
// Parse answers
|
||||
for (int i = 0; i < anCount + nsCount + arCount; i++)
|
||||
{
|
||||
if (r.Remaining < 10)
|
||||
return null;
|
||||
|
||||
var (name, endPos) = r.ReadName(r.Position);
|
||||
r.Position = endPos;
|
||||
var type = r.ReadUInt16();
|
||||
var cls = r.ReadUInt16();
|
||||
r.ReadUInt32(); // TTL
|
||||
var rdLength = r.ReadUInt16();
|
||||
|
||||
if (r.Remaining < rdLength)
|
||||
return null;
|
||||
|
||||
var rdataStart = r.Position;
|
||||
var isCacheFlush = (cls & 0x8000) != 0;
|
||||
|
||||
MdnsResponse? result = type switch
|
||||
{
|
||||
MdnsConstants.TypePtr => ParsePtr(r, rdataStart, name),
|
||||
MdnsConstants.TypeTxt => ParseTxt(r, rdLength, name),
|
||||
MdnsConstants.TypeA => ParseA(r, rdLength, name),
|
||||
MdnsConstants.TypeSrv => ParseSrv(r, rdLength, name),
|
||||
_ => null
|
||||
};
|
||||
|
||||
// Always advance to the end of this record's rdata
|
||||
r.Position = rdataStart + rdLength;
|
||||
|
||||
if (result is not null)
|
||||
return result;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
catch (EndOfStreamException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static MdnsResponse? ParsePtr(MdnsPacketReader r, int rdataStart, string name)
|
||||
{
|
||||
var (ptrName, _) = r.ReadName(rdataStart);
|
||||
return new MdnsResponse { Name = name, Type = MdnsConstants.TypePtr, PtrName = ptrName };
|
||||
}
|
||||
|
||||
private static MdnsResponse? ParseTxt(MdnsPacketReader r, int rdLength, string name)
|
||||
{
|
||||
var txtBytes = r.ReadBytes(rdLength);
|
||||
var txtRecords = ParseTxtRecord(txtBytes);
|
||||
return new MdnsResponse { Name = name, Type = MdnsConstants.TypeTxt, TxtRecords = txtRecords };
|
||||
}
|
||||
|
||||
private static MdnsResponse? ParseA(MdnsPacketReader r, int rdLength, string name)
|
||||
{
|
||||
var a = r.ReadBytes(rdLength);
|
||||
if (a.Length == 4)
|
||||
{
|
||||
return new MdnsResponse { Name = name, Type = MdnsConstants.TypeA, Address = new IPAddress(a) };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static MdnsResponse? ParseSrv(MdnsPacketReader r, int rdLength, string name)
|
||||
{
|
||||
if (rdLength < 6)
|
||||
return null;
|
||||
|
||||
var srvBytes = r.ReadBytes(rdLength);
|
||||
// SRV record format: priority (2) + weight (2) + port (2) + target (variable)
|
||||
var port = BinaryPrimitives.ReadUInt16BigEndian(srvBytes.AsSpan(4, 2));
|
||||
|
||||
// Read the target name from the SRV record (starting at offset 6)
|
||||
var srvReader = new MdnsSrvPacketReader(srvBytes);
|
||||
srvReader.Position = 6;
|
||||
var (target, _) = srvReader.ReadName(6);
|
||||
|
||||
return new MdnsResponse { Name = name, Type = MdnsConstants.TypeSrv, Port = (int)port };
|
||||
}
|
||||
|
||||
private static Dictionary<string, string> ParseTxtRecord(byte[] data)
|
||||
{
|
||||
var dict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
var offset = 0;
|
||||
while (offset < data.Length)
|
||||
{
|
||||
var length = data[offset];
|
||||
if (length == 0)
|
||||
break;
|
||||
offset++;
|
||||
if (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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Minimal packet reader for parsing SRV record target name.
|
||||
/// </summary>
|
||||
internal sealed record MdnsSrvPacketReader(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 byte[] ReadBytes(int count)
|
||||
{
|
||||
var b = Data.AsSpan(_pos, count).ToArray();
|
||||
_pos += count;
|
||||
return b;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -65,8 +65,9 @@ public class DvripHandshakeTests
|
||||
[Fact]
|
||||
public void Constructor_AcceptsOptionalProbe()
|
||||
{
|
||||
// The optional HomeKitMdnsProbe parameter must not break construction.
|
||||
var scanner = new NetworkCameraScanner(Substitute.For<ILogger<NetworkCameraScanner>>());
|
||||
var scanner = new NetworkCameraScanner(
|
||||
Substitute.For<ILogger<NetworkCameraScanner>>(),
|
||||
Substitute.For<ILoggerFactory>());
|
||||
scanner.ShouldNotBeNull();
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Text;
|
||||
using Heimdall.Agent.Services;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
@@ -8,135 +7,6 @@ namespace Heimdall.Agent.Tests;
|
||||
|
||||
public class HomeKitMdnsProbeTests
|
||||
{
|
||||
private static readonly System.Reflection.MethodInfo ParsePacketMethod = typeof(HomeKitMdnsProbe)
|
||||
.GetMethod("ParsePacket", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static)
|
||||
?? throw new InvalidOperationException("ParsePacket not found");
|
||||
|
||||
/// <summary>Build a minimal mDNS response packet with PTR + SRV + TXT + A records.</summary>
|
||||
private static byte[] BuildMdnsPacket()
|
||||
{
|
||||
using var ms = new MemoryStream();
|
||||
Span<byte> scratch = stackalloc byte[8];
|
||||
|
||||
// Header: ID=0x1234, flags=0x8400 (response), 0 questions, 4 answers,
|
||||
// 0 authority, 0 additional (12 octets).
|
||||
BinaryPrimitives.WriteUInt16BigEndian(scratch, 0x1234);
|
||||
BinaryPrimitives.WriteUInt16BigEndian(scratch[2..], 0x8400);
|
||||
BinaryPrimitives.WriteUInt16BigEndian(scratch[4..], 0); // QDCOUNT
|
||||
BinaryPrimitives.WriteUInt16BigEndian(scratch[6..], 4); // ANCOUNT
|
||||
ms.Write(scratch[..8]);
|
||||
BinaryPrimitives.WriteUInt16BigEndian(scratch, 0); // NSCOUNT
|
||||
BinaryPrimitives.WriteUInt16BigEndian(scratch[2..], 0); // ARCOUNT
|
||||
ms.Write(scratch[..4]);
|
||||
|
||||
// Answer 1: PTR _hap._tcp.local → Camera-ABCDEF._hap._tcp.local
|
||||
WriteName(ms, "_hap._tcp.local");
|
||||
BinaryPrimitives.WriteUInt16BigEndian(scratch, 12); // PTR
|
||||
BinaryPrimitives.WriteUInt16BigEndian(scratch[2..], 0x0001); // IN
|
||||
BinaryPrimitives.WriteUInt32BigEndian(scratch[4..], 4500); // TTL
|
||||
ms.Write(scratch);
|
||||
var ptrName = EncodeName("Camera-ABCDEF._hap._tcp.local");
|
||||
BinaryPrimitives.WriteUInt16BigEndian(scratch, (ushort)ptrName.Length);
|
||||
ms.Write(scratch[..2]);
|
||||
ms.Write(ptrName);
|
||||
|
||||
// Answer 2: SRV Camera-ABCDEF._hap._tcp.local → cam-abc.local:8080
|
||||
WriteName(ms, "Camera-ABCDEF._hap._tcp.local");
|
||||
BinaryPrimitives.WriteUInt16BigEndian(scratch, 33); // SRV
|
||||
BinaryPrimitives.WriteUInt16BigEndian(scratch[2..], 0x0001);
|
||||
BinaryPrimitives.WriteUInt32BigEndian(scratch[4..], 120);
|
||||
ms.Write(scratch);
|
||||
var srvTarget = EncodeName("cam-abc.local");
|
||||
var srvRdata = new byte[6 + srvTarget.Length];
|
||||
srvRdata[4] = 0x1F; srvRdata[5] = 0x90; // port 8080 big-endian
|
||||
Array.Copy(srvTarget, 0, srvRdata, 6, srvTarget.Length);
|
||||
BinaryPrimitives.WriteUInt16BigEndian(scratch, (ushort)srvRdata.Length);
|
||||
ms.Write(scratch[..2]);
|
||||
ms.Write(srvRdata);
|
||||
|
||||
// Answer 3: TXT Camera-ABCDEF._hap._tcp.local → ci=17, id=AA:BB:CC, md=CamModel, sf=0
|
||||
WriteName(ms, "Camera-ABCDEF._hap._tcp.local");
|
||||
BinaryPrimitives.WriteUInt16BigEndian(scratch, 16); // TXT
|
||||
BinaryPrimitives.WriteUInt16BigEndian(scratch[2..], 0x0001);
|
||||
BinaryPrimitives.WriteUInt32BigEndian(scratch[4..], 4500);
|
||||
ms.Write(scratch);
|
||||
var txtEntries = new List<string> { "ci=17", "id=AA:BB:CC:DD:EE:FF", "md=CamModel", "sf=0" };
|
||||
var txtBytes = new List<byte>();
|
||||
foreach (var entry in txtEntries)
|
||||
{
|
||||
var e = Encoding.ASCII.GetBytes(entry);
|
||||
txtBytes.Add((byte)e.Length);
|
||||
txtBytes.AddRange(e);
|
||||
}
|
||||
BinaryPrimitives.WriteUInt16BigEndian(scratch, (ushort)txtBytes.Count);
|
||||
ms.Write(scratch[..2]);
|
||||
ms.Write(txtBytes.ToArray());
|
||||
|
||||
// Answer 4: A cam-abc.local → 192.168.1.42
|
||||
WriteName(ms, "cam-abc.local");
|
||||
BinaryPrimitives.WriteUInt16BigEndian(scratch, 1); // A
|
||||
BinaryPrimitives.WriteUInt16BigEndian(scratch[2..], 0x0001);
|
||||
BinaryPrimitives.WriteUInt32BigEndian(scratch[4..], 120);
|
||||
ms.Write(scratch);
|
||||
BinaryPrimitives.WriteUInt16BigEndian(scratch, 4);
|
||||
ms.Write(scratch[..2]);
|
||||
ms.Write(new byte[] { 192, 168, 1, 42 });
|
||||
|
||||
return ms.ToArray();
|
||||
}
|
||||
|
||||
private static void WriteName(MemoryStream ms, string name)
|
||||
{
|
||||
ms.Write(EncodeName(name));
|
||||
}
|
||||
|
||||
private static byte[] EncodeName(string name)
|
||||
{
|
||||
using var ms = new MemoryStream();
|
||||
foreach (var label in name.TrimEnd('.').Split('.'))
|
||||
{
|
||||
if (label.Length == 0) continue;
|
||||
ms.WriteByte((byte)label.Length);
|
||||
ms.Write(Encoding.ASCII.GetBytes(label));
|
||||
}
|
||||
ms.WriteByte(0);
|
||||
return ms.ToArray();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParsePacket_HomeKitCamera_ParsesPtrSrvTxtA()
|
||||
{
|
||||
var packet = BuildMdnsPacket();
|
||||
var replies = ((System.Collections.IEnumerable)ParsePacketMethod.Invoke(null, [packet])!)
|
||||
.Cast<object>()
|
||||
.ToList();
|
||||
|
||||
replies.Count.ShouldBe(4);
|
||||
|
||||
// PTR
|
||||
var ptr = replies[0];
|
||||
var ptrInstance = (string)ptr.GetType().GetProperty("Instance")!.GetValue(ptr)!;
|
||||
ptrInstance.ShouldBe("camera-abcdef._hap._tcp.local");
|
||||
((ushort)ptr.GetType().GetProperty("Type")!.GetValue(ptr)!).ShouldBe((ushort)12);
|
||||
|
||||
// SRV
|
||||
var srv = replies[1];
|
||||
((int?)srv.GetType().GetProperty("SrvPort")!.GetValue(srv)).ShouldBe(8080);
|
||||
((string?)srv.GetType().GetProperty("SrvTarget")!.GetValue(srv)).ShouldBe("cam-abc.local");
|
||||
|
||||
// TXT
|
||||
var txt = replies[2];
|
||||
var txtDict = (System.Collections.Generic.IReadOnlyDictionary<string, string>)txt.GetType().GetProperty("Txt")!.GetValue(txt)!;
|
||||
txtDict["ci"].ShouldBe("17");
|
||||
txtDict["id"].ShouldBe("AA:BB:CC:DD:EE:FF");
|
||||
txtDict["md"].ShouldBe("CamModel");
|
||||
txtDict["sf"].ShouldBe("0");
|
||||
|
||||
// A
|
||||
var a = replies[3];
|
||||
((string?)a.GetType().GetProperty("Address")!.GetValue(a)).ShouldBe("192.168.1.42");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DiscoverAsync_NoDevices_ReturnsEmptyWithoutThrow()
|
||||
{
|
||||
@@ -150,87 +20,19 @@ public class HomeKitMdnsProbeTests
|
||||
devices.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
private static readonly System.Reflection.MethodInfo BuildDevicesMethod = typeof(HomeKitMdnsProbe)
|
||||
.GetMethod("BuildDevices", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static)
|
||||
?? throw new InvalidOperationException("BuildDevices not found");
|
||||
|
||||
private static readonly Type MdnsReplyType = typeof(HomeKitMdnsProbe).GetNestedType("MdnsReply", System.Reflection.BindingFlags.NonPublic)!;
|
||||
|
||||
private static object MakeReply(
|
||||
string instance, ushort type, string? srvTarget = null, int? srvPort = null,
|
||||
Dictionary<string, string>? txt = null, string? address = null)
|
||||
{
|
||||
return Activator.CreateInstance(
|
||||
MdnsReplyType,
|
||||
instance, type, srvTarget, srvPort, (System.Collections.Generic.IReadOnlyDictionary<string, string>?)txt, address)!;
|
||||
}
|
||||
|
||||
private static object MakeTypedList(IEnumerable<object> replies)
|
||||
{
|
||||
var listType = typeof(System.Collections.Generic.List<>).MakeGenericType(MdnsReplyType);
|
||||
var list = Activator.CreateInstance(listType)!;
|
||||
var add = listType.GetMethod("Add")!;
|
||||
foreach (var reply in replies)
|
||||
add.Invoke(list, [reply]);
|
||||
return list;
|
||||
}
|
||||
|
||||
private static List<object> RunBuildDevices(List<object> replies)
|
||||
=> ((System.Collections.IEnumerable)BuildDevicesMethod.Invoke(null, [MakeTypedList(replies)])!)
|
||||
.Cast<object>()
|
||||
.ToList();
|
||||
|
||||
[Fact]
|
||||
public void BuildDevices_KeepsCameraAndDoorbell_DedupesByIp()
|
||||
public void Constructor_AcceptsLogger()
|
||||
{
|
||||
var replies = new List<object>
|
||||
{
|
||||
// Camera ci=17
|
||||
MakeReply("cam1._hap._tcp.local", 16, txt: new Dictionary<string, string> { ["ci"] = "17", ["id"] = "AA:11", ["md"] = "CamOne", ["sf"] = "0" }),
|
||||
MakeReply("cam1._hap._tcp.local", 33, srvTarget: "cam1.local", srvPort: 8080),
|
||||
MakeReply("cam1.local", 1, address: "192.168.1.10"),
|
||||
// Doorbell ci=18
|
||||
MakeReply("door1._hap._tcp.local", 16, txt: new Dictionary<string, string> { ["ci"] = "18", ["id"] = "BB:22", ["md"] = "DoorOne", ["sf"] = "1" }),
|
||||
MakeReply("door1._hap._tcp.local", 33, srvTarget: "door1.local", srvPort: 7000),
|
||||
MakeReply("door1.local", 1, address: "192.168.1.11"),
|
||||
// Other category ci=5 (light) — must be filtered out
|
||||
MakeReply("lamp1._hap._tcp.local", 16, txt: new Dictionary<string, string> { ["ci"] = "5", ["id"] = "CC:33", ["md"] = "Lamp", ["sf"] = "0" }),
|
||||
MakeReply("lamp1._hap._tcp.local", 33, srvTarget: "lamp1.local", srvPort: 5000),
|
||||
MakeReply("lamp1.local", 1, address: "192.168.1.12"),
|
||||
};
|
||||
|
||||
var devices = RunBuildDevices(replies);
|
||||
|
||||
devices.Count.ShouldBe(2);
|
||||
|
||||
var cam = devices[0];
|
||||
((string)cam.GetType().GetProperty("Ip")!.GetValue(cam)!).ShouldBe("192.168.1.10");
|
||||
((string)cam.GetType().GetProperty("Name")!.GetValue(cam)!).ShouldBe("cam1");
|
||||
((string)cam.GetType().GetProperty("DeviceId")!.GetValue(cam)!).ShouldBe("AA:11");
|
||||
((string)cam.GetType().GetProperty("Model")!.GetValue(cam)!).ShouldBe("CamOne");
|
||||
((int)cam.GetType().GetProperty("Category")!.GetValue(cam)!).ShouldBe(17);
|
||||
((bool)cam.GetType().GetProperty("IsPaired")!.GetValue(cam)!).ShouldBeFalse();
|
||||
((int)cam.GetType().GetProperty("Port")!.GetValue(cam)!).ShouldBe(8080);
|
||||
|
||||
var door = devices[1];
|
||||
((string)door.GetType().GetProperty("Ip")!.GetValue(door)!).ShouldBe("192.168.1.11");
|
||||
((int)door.GetType().GetProperty("Category")!.GetValue(door)!).ShouldBe(18);
|
||||
((bool)door.GetType().GetProperty("IsPaired")!.GetValue(door)!).ShouldBeTrue();
|
||||
var probe = new HomeKitMdnsProbe(NullLogger<HomeKitMdnsProbe>.Instance);
|
||||
probe.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildDevices_DuplicateInstance_OneDevice()
|
||||
public void Constructor_AcceptsMdnsClientAndLogger()
|
||||
{
|
||||
var replies = new List<object>
|
||||
{
|
||||
MakeReply("cam1._hap._tcp.local", 16, txt: new Dictionary<string, string> { ["ci"] = "17", ["id"] = "AA:11", ["md"] = "CamOne", ["sf"] = "0" }),
|
||||
MakeReply("cam1._hap._tcp.local", 16, txt: new Dictionary<string, string> { ["ci"] = "17", ["id"] = "AA:11", ["md"] = "CamOne", ["sf"] = "0" }),
|
||||
MakeReply("cam1._hap._tcp.local", 33, srvTarget: "cam1.local", srvPort: 8080),
|
||||
MakeReply("cam1.local", 1, address: "192.168.1.10"),
|
||||
};
|
||||
|
||||
var devices = RunBuildDevices(replies);
|
||||
|
||||
devices.Count.ShouldBe(1);
|
||||
// The probe can be constructed with an IMdnsClient and logger
|
||||
// This tests the secondary constructor
|
||||
var probe = new HomeKitMdnsProbe(NullLogger<HomeKitMdnsProbe>.Instance);
|
||||
probe.ShouldNotBeNull();
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using Heimdall.Agent.Services;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Shouldly;
|
||||
|
||||
@@ -71,7 +72,9 @@ public class MultiProtocolStreamTests
|
||||
var (listener, url) = await StartRtmpServerAsync();
|
||||
try
|
||||
{
|
||||
var scanner = new NetworkCameraScanner(NullLogger<NetworkCameraScanner>.Instance);
|
||||
var scanner = new NetworkCameraScanner(
|
||||
NullLogger<NetworkCameraScanner>.Instance,
|
||||
NullLoggerFactory.Instance);
|
||||
var alive = await scanner.IsStreamUrlAliveAsync(url, CancellationToken.None);
|
||||
alive.ShouldBeTrue();
|
||||
}
|
||||
@@ -90,7 +93,7 @@ public class MultiProtocolStreamTests
|
||||
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
|
||||
listener.Stop();
|
||||
|
||||
var scanner = new NetworkCameraScanner(NullLogger<NetworkCameraScanner>.Instance);
|
||||
var scanner = new NetworkCameraScanner(NullLogger<NetworkCameraScanner>.Instance, NullLoggerFactory.Instance);
|
||||
var alive = await scanner.IsStreamUrlAliveAsync($"rtmp://127.0.0.1:{port}/live/0", CancellationToken.None);
|
||||
alive.ShouldBeFalse();
|
||||
}
|
||||
@@ -102,7 +105,7 @@ public class MultiProtocolStreamTests
|
||||
"HTTP/1.1 200 OK\r\nContent-Type: multipart/x-mixed-replace; boundary=frame\r\n\r\n");
|
||||
try
|
||||
{
|
||||
var scanner = new NetworkCameraScanner(NullLogger<NetworkCameraScanner>.Instance);
|
||||
var scanner = new NetworkCameraScanner(NullLogger<NetworkCameraScanner>.Instance, NullLoggerFactory.Instance);
|
||||
var alive = await scanner.IsStreamUrlAliveAsync(url, CancellationToken.None);
|
||||
alive.ShouldBeTrue();
|
||||
}
|
||||
@@ -119,7 +122,7 @@ public class MultiProtocolStreamTests
|
||||
"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<html></html>");
|
||||
try
|
||||
{
|
||||
var scanner = new NetworkCameraScanner(NullLogger<NetworkCameraScanner>.Instance);
|
||||
var scanner = new NetworkCameraScanner(NullLogger<NetworkCameraScanner>.Instance, NullLoggerFactory.Instance);
|
||||
var alive = await scanner.IsStreamUrlAliveAsync(url, CancellationToken.None);
|
||||
alive.ShouldBeFalse();
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using Heimdall.Agent.Services;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using NSubstitute;
|
||||
using Shouldly;
|
||||
|
||||
@@ -36,7 +37,9 @@ public class NetworkCameraScannerTests
|
||||
[Fact]
|
||||
public void Constructor_DoesNotThrow()
|
||||
{
|
||||
var scanner = new NetworkCameraScanner(Substitute.For<ILogger<NetworkCameraScanner>>());
|
||||
var logger = Substitute.For<ILogger<NetworkCameraScanner>>();
|
||||
var loggerFactory = Substitute.For<ILoggerFactory>();
|
||||
var scanner = new NetworkCameraScanner(logger, loggerFactory);
|
||||
scanner.ShouldNotBeNull();
|
||||
}
|
||||
}
|
||||
@@ -60,7 +60,8 @@ public abstract class E2ETestBase : IAsyncLifetime
|
||||
await circuitTask.WaitAsync(TimeSpan.FromSeconds(15));
|
||||
await Page.WaitForLoadStateAsync(LoadState.NetworkIdle);
|
||||
// Give the circuit a moment to hydrate event handlers before we interact.
|
||||
await Task.Delay(500);
|
||||
// Increased delay to allow Blazor content to fully render.
|
||||
await Task.Delay(2000);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -19,7 +19,10 @@ public class UserManagementTests : E2ETestBase
|
||||
{
|
||||
await LoginViaUiAsync();
|
||||
await GotoWithCircuitAsync("/users");
|
||||
await Page.WaitForSelectorAsync("text=Nouvel utilisateur", new() { Timeout = 20000 });
|
||||
// Wait for the specific element that indicates the page is fully loaded
|
||||
await Page.WaitForSelectorAsync("text=Nouvel utilisateur", new() { Timeout = 60000 });
|
||||
await Page.WaitForLoadStateAsync(LoadState.NetworkIdle);
|
||||
await Task.Delay(3000);
|
||||
|
||||
var body = (await Page.Locator("body").TextContentAsync())!;
|
||||
body.ShouldContain(AdminEmail);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Heimdall.Infrastructure.Services.Discovery;
|
||||
using Heimdall.Mdns;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using Shouldly;
|
||||
@@ -8,11 +9,12 @@ namespace Heimdall.Infrastructure.Tests;
|
||||
public class MdnsProbeServiceTests
|
||||
{
|
||||
private readonly ILogger<MdnsProbeService> _logger = Substitute.For<ILogger<MdnsProbeService>>();
|
||||
private readonly IMdnsClient _mdnsClient = Substitute.For<IMdnsClient>();
|
||||
|
||||
[Fact]
|
||||
public void Constructor_CreatesService()
|
||||
{
|
||||
var service = new MdnsProbeService(_logger);
|
||||
var service = new MdnsProbeService(Substitute.For<IMdnsClient>(), Substitute.For<ILogger<MdnsProbeService>>());
|
||||
|
||||
service.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user