using System.Buffers.Binary; using System.Text; using Heimdall.Agent.Services; using Microsoft.Extensions.Logging.Abstractions; using Shouldly; 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"); /// Build a minimal mDNS response packet with PTR + SRV + TXT + A records. private static byte[] BuildMdnsPacket() { using var ms = new MemoryStream(); Span 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 { "ci=17", "id=AA:BB:CC:DD:EE:FF", "md=CamModel", "sf=0" }; var txtBytes = new List(); 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() .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)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() { var probe = new HomeKitMdnsProbe(NullLogger.Instance); using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); // In a container without a multicast route this returns [] — it must // never throw and must terminate within the window. var devices = await probe.DiscoverAsync(cts.Token); 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? txt = null, string? address = null) { return Activator.CreateInstance( MdnsReplyType, instance, type, srvTarget, srvPort, (System.Collections.Generic.IReadOnlyDictionary?)txt, address)!; } private static object MakeTypedList(IEnumerable 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 RunBuildDevices(List replies) => ((System.Collections.IEnumerable)BuildDevicesMethod.Invoke(null, [MakeTypedList(replies)])!) .Cast() .ToList(); [Fact] public void BuildDevices_KeepsCameraAndDoorbell_DedupesByIp() { var replies = new List { // Camera ci=17 MakeReply("cam1._hap._tcp.local", 16, txt: new Dictionary { ["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 { ["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 { ["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(); } [Fact] public void BuildDevices_DuplicateInstance_OneDevice() { var replies = new List { MakeReply("cam1._hap._tcp.local", 16, txt: new Dictionary { ["ci"] = "17", ["id"] = "AA:11", ["md"] = "CamOne", ["sf"] = "0" }), MakeReply("cam1._hap._tcp.local", 16, txt: new Dictionary { ["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); } }