From 034ba4614c88930a332270d6db534cba7cf286e1 Mon Sep 17 00:00:00 2001 From: Johann Dirry Date: Mon, 16 Nov 2026 20:44:25 +0100 Subject: [PATCH 01/80] Add mDNS and DNS-SD service discovery browser --- .../DocumentationIdentifier.cs | 3 +- .../DocumentationManager.cs | 4 + .../Resources/Strings.Designer.cs | 168 ++++++++- .../Resources/Strings.resx | 54 +++ .../ApplicationManager.cs | 5 +- .../NETworkManager.Models/ApplicationName.cs | 7 +- .../Export/ExportManager.MDNSRecordInfo.cs | 21 ++ .../Export/ExportManager.MDNSServiceInfo.cs | 25 ++ .../Network/MDNSBrowser.cs | 141 ++++++++ .../Network/MDNSMessage.cs | 211 +++++++++++ .../Network/MDNSRecordInfo.cs | 44 +++ .../Network/MDNSServiceCache.cs | 183 ++++++++++ .../Network/MDNSServiceInfo.cs | 51 +++ .../RunCommand/RunCommandTarget.cs | 3 + .../RunCommand/RunCommandTargetKind.cs | 5 +- .../GlobalStaticConfiguration.cs | 9 +- .../NETworkManager.Settings/SettingsInfo.cs | 36 +- .../SettingsManager.cs | 7 + .../ExportManagerMDNSServiceInfoTests.cs | 47 +++ .../Network/MDNSDiscoveryTests.cs | 319 +++++++++++++++++ .../RunCommand/RunCommandTargetTests.cs | 3 + .../MDNSServiceType.cs | 34 ++ .../MDNSServiceTypeValidator.cs | 14 + Source/NETworkManager/MainWindow.xaml.cs | 12 + Source/NETworkManager/RunCommandManager.cs | 6 +- .../ViewModels/MDNSDiscoveryViewModel.cs | 335 ++++++++++++++++++ .../Views/MDNSDiscoveryView.xaml | 228 ++++++++++++ .../Views/MDNSDiscoveryView.xaml.cs | 19 + Website/docs/application/mdns-discovery.md | 85 +++++ Website/docs/changelog/next-release.md | 4 + Website/docs/run-command.md | 4 +- 31 files changed, 2075 insertions(+), 12 deletions(-) create mode 100644 Source/NETworkManager.Models/Export/ExportManager.MDNSRecordInfo.cs create mode 100644 Source/NETworkManager.Models/Export/ExportManager.MDNSServiceInfo.cs create mode 100644 Source/NETworkManager.Models/Network/MDNSBrowser.cs create mode 100644 Source/NETworkManager.Models/Network/MDNSMessage.cs create mode 100644 Source/NETworkManager.Models/Network/MDNSRecordInfo.cs create mode 100644 Source/NETworkManager.Models/Network/MDNSServiceCache.cs create mode 100644 Source/NETworkManager.Models/Network/MDNSServiceInfo.cs create mode 100644 Source/NETworkManager.Tests/Export/ExportManagerMDNSServiceInfoTests.cs create mode 100644 Source/NETworkManager.Tests/Network/MDNSDiscoveryTests.cs create mode 100644 Source/NETworkManager.Utilities/MDNSServiceType.cs create mode 100644 Source/NETworkManager.Validators/MDNSServiceTypeValidator.cs create mode 100644 Source/NETworkManager/ViewModels/MDNSDiscoveryViewModel.cs create mode 100644 Source/NETworkManager/Views/MDNSDiscoveryView.xaml create mode 100644 Source/NETworkManager/Views/MDNSDiscoveryView.xaml.cs create mode 100644 Website/docs/application/mdns-discovery.md diff --git a/Source/NETworkManager.Documentation/DocumentationIdentifier.cs b/Source/NETworkManager.Documentation/DocumentationIdentifier.cs index 63b071e9a5..ec2c493e51 100644 --- a/Source/NETworkManager.Documentation/DocumentationIdentifier.cs +++ b/Source/NETworkManager.Documentation/DocumentationIdentifier.cs @@ -99,6 +99,7 @@ public enum DocumentationIdentifier /// Discovery Protocol documentation page. /// ApplicationDiscoveryProtocol, + ApplicationMDNSDiscovery, /// /// Wake on LAN documentation page. @@ -219,4 +220,4 @@ public enum DocumentationIdentifier /// Changelog base documentation page. /// ChangelogBase -} \ No newline at end of file +} diff --git a/Source/NETworkManager.Documentation/DocumentationManager.cs b/Source/NETworkManager.Documentation/DocumentationManager.cs index 5cf844de12..b3f2e39df9 100644 --- a/Source/NETworkManager.Documentation/DocumentationManager.cs +++ b/Source/NETworkManager.Documentation/DocumentationManager.cs @@ -75,6 +75,9 @@ public static class DocumentationManager new DocumentationInfo(DocumentationIdentifier.ApplicationDiscoveryProtocol, @"docs/application/discovery-protocol"), + new DocumentationInfo(DocumentationIdentifier.ApplicationMDNSDiscovery, + @"docs/application/mdns-discovery"), + new DocumentationInfo(DocumentationIdentifier.ApplicationWakeOnLan, @"docs/application/wake-on-lan"), @@ -222,6 +225,7 @@ public static DocumentationIdentifier GetIdentifierByApplicationName(Application ApplicationName.SNTPLookup => DocumentationIdentifier.ApplicationSntpLookup, ApplicationName.HostsFileEditor => DocumentationIdentifier.ApplicationHostsFileEditor, ApplicationName.DiscoveryProtocol => DocumentationIdentifier.ApplicationDiscoveryProtocol, + ApplicationName.MDNSDiscovery => DocumentationIdentifier.ApplicationMDNSDiscovery, ApplicationName.Firewall => DocumentationIdentifier.ApplicationFirewall, ApplicationName.WakeOnLAN => DocumentationIdentifier.ApplicationWakeOnLan, ApplicationName.RDAP => DocumentationIdentifier.ApplicationRdap, diff --git a/Source/NETworkManager.Localization/Resources/Strings.Designer.cs b/Source/NETworkManager.Localization/Resources/Strings.Designer.cs index 5d071b5767..d632a7a4ff 100644 --- a/Source/NETworkManager.Localization/Resources/Strings.Designer.cs +++ b/Source/NETworkManager.Localization/Resources/Strings.Designer.cs @@ -1212,6 +1212,15 @@ public static string ApplicationName_Lookup { } } + /// + /// Looks up a localized string similar to mDNS / DNS-SD. + /// + public static string ApplicationName_MDNSDiscovery { + get { + return ResourceManager.GetString("ApplicationName_MDNSDiscovery", resourceCulture); + } + } + /// /// Looks up a localized string similar to Neighbor Table. /// @@ -8103,6 +8112,159 @@ public static string MACAddressOrVendor { } } + /// + /// Looks up a localized string similar to Browse. + /// + public static string MDNSDiscovery_Browse { + get { + return ResourceManager.GetString("MDNSDiscovery_Browse", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Discovering services on the selected network interface.... + /// + public static string MDNSDiscovery_Browsing { + get { + return ResourceManager.GetString("MDNSDiscovery_Browsing", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Discovery completed. The results show the last received service information.. + /// + public static string MDNSDiscovery_Completed { + get { + return ResourceManager.GetString("MDNSDiscovery_Completed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Discovery duration in seconds. Set to 0 to browse continuously until Stop is pressed. Discovery also stops when you switch to another tool.. + /// + public static string MDNSDiscovery_DurationHelp { + get { + return ResourceManager.GetString("MDNSDiscovery_DurationHelp", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No services found. Select a network interface and browse. Devices must advertise services on this local network; firewalls, VPNs and Wi-Fi client isolation can block discovery.. + /// + public static string MDNSDiscovery_Empty { + get { + return ResourceManager.GetString("MDNSDiscovery_Empty", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Service discovery failed. Check the network interface and whether UDP port 5353 is available and allowed by the firewall.. + /// + public static string MDNSDiscovery_Failed { + get { + return ResourceManager.GetString("MDNSDiscovery_Failed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Enter * or a service type such as _ipp._tcp, _http._tcp.local. or _ssh._tcp.. + /// + public static string MDNSDiscovery_InvalidServiceType { + get { + return ResourceManager.GetString("MDNSDiscovery_InvalidServiceType", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No active network interface with multicast support was found.. + /// + public static string MDNSDiscovery_NoInterface { + get { + return ResourceManager.GetString("MDNSDiscovery_NoInterface", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No DNS records received. Start browsing on the selected interface.. + /// + public static string MDNSDiscovery_NoRecords { + get { + return ResourceManager.GetString("MDNSDiscovery_NoRecords", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to SRV priority. + /// + public static string MDNSDiscovery_Priority { + get { + return ResourceManager.GetString("MDNSDiscovery_Priority", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Records. + /// + public static string MDNSDiscovery_Records { + get { + return ResourceManager.GetString("MDNSDiscovery_Records", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Service type. + /// + public static string MDNSDiscovery_ServiceType { + get { + return ResourceManager.GetString("MDNSDiscovery_ServiceType", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Enter * to discover all advertised service types (also probes common printer, scanner, web and media service types), or select or enter a type such as _ipp._tcp. Discovery is limited to the local. domain.. + /// + public static string MDNSDiscovery_ServiceTypeHelp { + get { + return ResourceManager.GetString("MDNSDiscovery_ServiceTypeHelp", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Services. + /// + public static string MDNSDiscovery_Services { + get { + return ResourceManager.GetString("MDNSDiscovery_Services", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Discovery stopped. The results show the last received service information.. + /// + public static string MDNSDiscovery_Stopped { + get { + return ResourceManager.GetString("MDNSDiscovery_Stopped", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to TXT records. + /// + public static string MDNSDiscovery_TXTRecords { + get { + return ResourceManager.GetString("MDNSDiscovery_TXTRecords", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to SRV weight. + /// + public static string MDNSDiscovery_Weight { + get { + return ResourceManager.GetString("MDNSDiscovery_Weight", resourceCulture); + } + } + /// /// Looks up a localized string similar to Magenta. /// @@ -8111,7 +8273,7 @@ public static string Magenta { return ResourceManager.GetString("Magenta", resourceCulture); } } - + /// /// Looks up a localized string similar to Magic packet successfully sent!. /// @@ -8120,7 +8282,7 @@ public static string MagicPacketSentMessage { return ResourceManager.GetString("MagicPacketSentMessage", resourceCulture); } } - + /// /// Looks up a localized string similar to Management. /// @@ -8129,7 +8291,7 @@ public static string Management { return ResourceManager.GetString("Management", resourceCulture); } } - + /// /// Looks up a localized string similar to Map. /// diff --git a/Source/NETworkManager.Localization/Resources/Strings.resx b/Source/NETworkManager.Localization/Resources/Strings.resx index ce63409d40..10a797d698 100644 --- a/Source/NETworkManager.Localization/Resources/Strings.resx +++ b/Source/NETworkManager.Localization/Resources/Strings.resx @@ -5567,4 +5567,58 @@ Do you want to start the scan? ISC License + + mDNS / DNS-SD + + + Browse + + + Discovering services on the selected network interface... + + + Discovery completed. The results show the last received service information. + + + Discovery duration in seconds. Set to 0 to browse continuously until Stop is pressed. Discovery also stops when you switch to another tool. + + + No services found. Select a network interface and browse. Devices must advertise services on this local network; firewalls, VPNs and Wi-Fi client isolation can block discovery. + + + Service discovery failed. Check the network interface and whether UDP port 5353 is available and allowed by the firewall. + + + Enter * or a service type such as _ipp._tcp, _http._tcp.local. or _ssh._tcp. + + + No active network interface with multicast support was found. + + + SRV priority + + + Service type + + + Enter * to discover all advertised service types (also probes common printer, scanner, web and media service types), or select or enter a type such as _ipp._tcp. Discovery is limited to the local. domain. + + + Discovery stopped. The results show the last received service information. + + + TXT records + + + SRV weight + + + No DNS records received. Start browsing on the selected interface. + + + Records + + + Services + \ No newline at end of file diff --git a/Source/NETworkManager.Models/ApplicationManager.cs b/Source/NETworkManager.Models/ApplicationManager.cs index bbf05016f8..818992eb00 100644 --- a/Source/NETworkManager.Models/ApplicationManager.cs +++ b/Source/NETworkManager.Models/ApplicationManager.cs @@ -89,6 +89,9 @@ public static Canvas GetIcon(ApplicationName name) case ApplicationName.DNSLookup: canvas.Children.Add(new LucideIcon { Kind = LucideIconKind.Globe }); break; + case ApplicationName.MDNSDiscovery: + canvas.Children.Add(new LucideIcon { Kind = LucideIconKind.Radar }); + break; case ApplicationName.RemoteDesktop: canvas.Children.Add(new LucideIcon { Kind = LucideIconKind.Monitor }); break; @@ -161,4 +164,4 @@ public static Canvas GetIcon(ApplicationName name) return canvas; } -} \ No newline at end of file +} diff --git a/Source/NETworkManager.Models/ApplicationName.cs b/Source/NETworkManager.Models/ApplicationName.cs index fb2f263f28..7346dde6cd 100644 --- a/Source/NETworkManager.Models/ApplicationName.cs +++ b/Source/NETworkManager.Models/ApplicationName.cs @@ -162,5 +162,8 @@ public enum ApplicationName /// with "ARPTable" can still be deserialized; migrated in SettingsManager.Upgrade(). /// [System.Obsolete("Use NeighborTable instead.")] - ARPTable -} \ No newline at end of file + ARPTable, + + /// Multicast DNS service discovery application. + MDNSDiscovery +} diff --git a/Source/NETworkManager.Models/Export/ExportManager.MDNSRecordInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.MDNSRecordInfo.cs new file mode 100644 index 0000000000..ba556a7c68 --- /dev/null +++ b/Source/NETworkManager.Models/Export/ExportManager.MDNSRecordInfo.cs @@ -0,0 +1,21 @@ +using System.Collections.Generic; +using NETworkManager.Models.Network; + +namespace NETworkManager.Models.Export; + +public static partial class ExportManager +{ + private static readonly ExportField[] MDNSRecordInfoExportFields = + [ + new(nameof(MDNSRecordInfo.Name), x => x.Name, true), + new(nameof(MDNSRecordInfo.Type), x => x.Type), + new(nameof(MDNSRecordInfo.Class), x => x.Class), + new(nameof(MDNSRecordInfo.TTL), x => x.TTL), + new(nameof(MDNSRecordInfo.Value), x => x.Value, true), + new(nameof(MDNSRecordInfo.CacheFlush), x => x.CacheFlush), + new(nameof(MDNSRecordInfo.NetworkInterface), x => x.NetworkInterface, true) + ]; + + public static void Export(string filePath, ExportFileType fileType, IReadOnlyList collection) => + Export(filePath, fileType, collection, MDNSRecordInfoExportFields, ApplicationName.MDNSDiscovery); +} diff --git a/Source/NETworkManager.Models/Export/ExportManager.MDNSServiceInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.MDNSServiceInfo.cs new file mode 100644 index 0000000000..9b71ae6fa7 --- /dev/null +++ b/Source/NETworkManager.Models/Export/ExportManager.MDNSServiceInfo.cs @@ -0,0 +1,25 @@ +using System.Collections.Generic; +using NETworkManager.Models.Network; + +namespace NETworkManager.Models.Export; + +public static partial class ExportManager +{ + private static readonly ExportField[] MDNSServiceInfoExportFields = + [ + new(nameof(MDNSServiceInfo.Name), x => x.Name, true), + new(nameof(MDNSServiceInfo.FullName), x => x.FullName, true), + new(nameof(MDNSServiceInfo.ServiceType), x => x.ServiceType), + new(nameof(MDNSServiceInfo.NetworkInterface), x => x.NetworkInterface, true), + new(nameof(MDNSServiceInfo.Hostname), x => x.Hostname, true), + new(nameof(MDNSServiceInfo.Port), x => x.Port), + new(nameof(MDNSServiceInfo.Priority), x => x.Priority), + new(nameof(MDNSServiceInfo.Weight), x => x.Weight), + new(nameof(MDNSServiceInfo.Addresses), x => x.Addresses), + new(nameof(MDNSServiceInfo.TXTRecords), x => x.TXTRecords, true), + new(nameof(MDNSServiceInfo.TTL), x => x.TTL) + ]; + + public static void Export(string filePath, ExportFileType fileType, IReadOnlyList collection) => + Export(filePath, fileType, collection, MDNSServiceInfoExportFields, ApplicationName.MDNSDiscovery); +} diff --git a/Source/NETworkManager.Models/Network/MDNSBrowser.cs b/Source/NETworkManager.Models/Network/MDNSBrowser.cs new file mode 100644 index 0000000000..2f42445990 --- /dev/null +++ b/Source/NETworkManager.Models/Network/MDNSBrowser.cs @@ -0,0 +1,141 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.NetworkInformation; +using System.Net.Sockets; +using System.Threading; +using System.Threading.Channels; +using System.Threading.Tasks; + +namespace NETworkManager.Models.Network; + +/// A selectable link. Discovery is kept on one interface, so equal .local names on separate links never mix. +public sealed record MDNSInterfaceInfo(string Id, string Name, IPAddress IPv4Address, int IPv4Index, int IPv6Index) +{ + public override string ToString() => Name; +} + +/// Local-link multicast DNS service discovery over IPv4 and IPv6. No responder or service registration. +public static class MDNSBrowser +{ + public static IReadOnlyList GetInterfaces() => System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces() + .Where(x => x.OperationalStatus == OperationalStatus.Up && x.SupportsMulticast && + x.NetworkInterfaceType != NetworkInterfaceType.Loopback) + .Select(x => + { + var properties = x.GetIPProperties(); + var ipv4 = properties.UnicastAddresses.FirstOrDefault(a => a.Address.AddressFamily == AddressFamily.InterNetwork)?.Address; + var ipv6 = properties.UnicastAddresses.Any(a => a.Address.AddressFamily == AddressFamily.InterNetworkV6); + return new MDNSInterfaceInfo(x.Id, x.Name, ipv4, ipv4 == null ? 0 : properties.GetIPv4Properties().Index, + ipv6 ? properties.GetIPv6Properties().Index : 0); + }).Where(x => x.IPv4Address != null || x.IPv6Index != 0).OrderBy(x => x.Name).ToArray(); + + /// Browses until cancellation; reports detached snapshots from a worker thread every 250 ms. + public static async Task BrowseAsync(MDNSInterfaceInfo networkInterface, string serviceType, + Action update, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(networkInterface); + var cache = new MDNSServiceCache(serviceType, networkInterface.Name); + var sockets = new List<(Socket Socket, IPEndPoint Destination, int Index)>(); + using var lifetime = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + var receivers = new List(); + try + { + if (networkInterface.IPv4Address != null) + sockets.Add(CreateSocket(networkInterface, false)); + if (networkInterface.IPv6Index != 0) + sockets.Add(CreateSocket(networkInterface, true)); + if (sockets.Count == 0) + throw new NetworkInformationException(); + + var packets = Channel.CreateBounded(new BoundedChannelOptions(512) + { + SingleReader = true, + FullMode = BoundedChannelFullMode.DropOldest + }); + receivers.AddRange(sockets.Select(x => ReceiveAsync(x.Socket, x.Index, packets.Writer, lifetime.Token))); + using var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(250)); + do + { + cancellationToken.ThrowIfCancellationRequested(); + foreach (var receiver in receivers.Where(x => x.IsCompleted)) + await receiver.ConfigureAwait(false); // Surface interface/socket failures, never silently show an empty scan. + var now = DateTimeOffset.UtcNow; + // Bound work per tick, even if the link is very busy. + for (var i = 0; i < 512 && packets.Reader.TryRead(out var message); i++) + cache.ProcessResponse(message, now, networkInterface.IPv6Index); + foreach (var question in cache.GetQuestions(now)) + { + var data = MDNSMessage.CreateQuery(question.Name, question.Type); + foreach (var socket in sockets) + await socket.Socket.SendToAsync(data, SocketFlags.None, socket.Destination, cancellationToken) + .ConfigureAwait(false); + } + update(new MDNSDiscoverySnapshot(cache.GetServices(now), cache.GetRecords(now))); + } while (await timer.WaitForNextTickAsync(cancellationToken).ConfigureAwait(false)); + } + finally + { + await lifetime.CancelAsync().ConfigureAwait(false); + foreach (var socket in sockets) + socket.Socket.Dispose(); + try { await Task.WhenAll(receivers).ConfigureAwait(false); } + catch (OperationCanceledException) { } + catch (SocketException) when (lifetime.IsCancellationRequested) { } + catch (ObjectDisposedException) when (lifetime.IsCancellationRequested) { } + } + } + + private static (Socket, IPEndPoint, int) CreateSocket(MDNSInterfaceInfo link, bool ipv6) + { + var socket = new Socket(ipv6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork, + SocketType.Dgram, ProtocolType.Udp); + try + { + socket.ExclusiveAddressUse = false; + socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); + if (ipv6) + { + socket.DualMode = false; + socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.PacketInformation, true); + socket.Bind(new IPEndPoint(IPAddress.IPv6Any, 5353)); + var group = IPAddress.Parse("ff02::fb"); + socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.AddMembership, + new IPv6MulticastOption(group, link.IPv6Index)); + socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.MulticastInterface, link.IPv6Index); + socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.MulticastTimeToLive, 255); + return (socket, new IPEndPoint(new IPAddress(group.GetAddressBytes(), link.IPv6Index), 5353), link.IPv6Index); + } + else + { + socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true); + socket.Bind(new IPEndPoint(IPAddress.Any, 5353)); + var group = IPAddress.Parse("224.0.0.251"); + socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, + new MulticastOption(group, link.IPv4Address)); + socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, link.IPv4Address.GetAddressBytes()); + socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 255); + return (socket, new IPEndPoint(group, 5353), link.IPv4Index); + } + } + catch + { + socket.Dispose(); + throw; + } + } + + private static async Task ReceiveAsync(Socket socket, int index, ChannelWriter writer, CancellationToken token) + { + var buffer = new byte[65535]; + EndPoint any = new IPEndPoint(socket.AddressFamily == AddressFamily.InterNetworkV6 ? IPAddress.IPv6Any : IPAddress.Any, 0); + while (true) + { + var result = await socket.ReceiveMessageFromAsync(buffer.AsMemory(), SocketFlags.None, any, token).ConfigureAwait(false); + if (result.RemoteEndPoint is IPEndPoint { Port: 5353 } && result.PacketInformation.Interface == index && + (result.SocketFlags & SocketFlags.Truncated) == 0) + writer.TryWrite(buffer[..result.ReceivedBytes]); + } + } +} diff --git a/Source/NETworkManager.Models/Network/MDNSMessage.cs b/Source/NETworkManager.Models/Network/MDNSMessage.cs new file mode 100644 index 0000000000..660f6efa83 --- /dev/null +++ b/Source/NETworkManager.Models/Network/MDNSMessage.cs @@ -0,0 +1,211 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Security.Cryptography; +using System.Text; + +namespace NETworkManager.Models.Network; + +/// A DNS record understood by the service browser. Names use escaped DNS presentation format. +public sealed record MDNSRecord(string Name, ushort Type, uint TTL, bool CacheFlush, string Target = "", + ushort Port = 0, ushort Priority = 0, ushort Weight = 0, IPAddress Address = null, string[] Text = null, + byte[] RawData = null) +{ + // Keep row identities compact even when a TXT record contains thousands of strings. + public string Identity => $"{Target.ToLowerInvariant()}|{Port}|{Priority}|{Weight}|{Address}|" + + (Text == null ? string.Empty : Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(string.Join('\0', Text))))) + "|" + + (RawData == null ? string.Empty : Convert.ToHexString(SHA256.HashData(RawData))); +} + +/// Bounded DNS wire reader/writer. Decodes DNS-SD records and preserves other record types as opaque RDATA. +public static class MDNSMessage +{ + public const ushort A = 1, PTR = 12, TXT = 16, AAAA = 28, SRV = 33; + + /// Builds a multicast question (ID zero, class IN, multicast response). + public static byte[] CreateQuery(string name, ushort type) + { + var data = new List { 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 }; + var label = new StringBuilder(); + var escaped = false; + foreach (var character in name.TrimEnd('.') + ".") + { + if (escaped) + { + label.Append(character); + escaped = false; + } + else if (character == '\\') + escaped = true; + else if (character != '.') + label.Append(character); + else + { + var bytes = Encoding.UTF8.GetBytes(label.ToString()); + if (bytes.Length is < 1 or > 63) + throw new ArgumentException("Invalid DNS label.", nameof(name)); + data.Add((byte)bytes.Length); + data.AddRange(bytes); + label.Clear(); + } + } + + if (escaped || data.Count > 266) + throw new ArgumentException("Invalid DNS name.", nameof(name)); + data.AddRange([0, (byte)(type >> 8), (byte)type, 0, 1]); + return [.. data]; + } + + /// Rejects malformed/truncated packets atomically, including invalid compression and RDATA lengths. + public static IReadOnlyList ReadResponse(byte[] data, long ipv6ScopeId = 0) + { + try + { + var reader = new Reader(data); + reader.U16(); + var flags = reader.U16(); + if ((flags & 0x8000) == 0 || (flags & 0x7A0F) != 0) + return []; + var questions = reader.U16(); + var answers = reader.U16(); + var authority = reader.U16(); + var additional = reader.U16(); + if (questions > 256 || answers + authority + additional > 4096) + return []; + for (var i = 0; i < questions; i++) + { + reader.Name(); + reader.Skip(4); + } + + var records = new List(); + for (var i = 0; i < answers + authority + additional; i++) + { + var name = reader.Name(); + var type = reader.U16(); + var recordClass = reader.U16(); + var ttl = reader.U32(); + var length = reader.U16(); + var end = reader.Position + length; + reader.Require(length); + MDNSRecord record = null; + if ((recordClass & 0x7FFF) == 1) + { + var flush = (recordClass & 0x8000) != 0; + switch (type) + { + case PTR: + record = new MDNSRecord(name, type, ttl, flush, reader.Name(end)); + break; + case SRV: + var priority = reader.U16(); + var weight = reader.U16(); + var port = reader.U16(); + record = new MDNSRecord(name, type, ttl, flush, reader.Name(end), port, priority, weight); + break; + case TXT: + var text = new List(); + while (reader.Position < end) + { + var size = reader.Byte(); + if (reader.Position + size > end) + throw new InvalidDataException(); + text.Add(FormatText(reader.Bytes(size))); + } + record = new MDNSRecord(name, type, ttl, flush, Text: [.. text]); + break; + case A when length == 4: + case AAAA when length == 16: + var address = new IPAddress(reader.Bytes(length)); + if (address.IsIPv6LinkLocal) + address.ScopeId = ipv6ScopeId; + record = new MDNSRecord(name, type, ttl, flush, Address: address); + break; + default: + // RFC 3597: preserve unsupported RDATA without assuming its internal format. + record = new MDNSRecord(name, type, ttl, flush, RawData: reader.Bytes(length)); + break; + } + } + if (reader.Position > end || record != null && reader.Position != end) + throw new InvalidDataException(); + reader.Position = end; + if (record != null) + records.Add(record); + } + return records; + } + catch (InvalidDataException) + { + return []; + } + } + + private static string FormatText(byte[] bytes) + { + string text; + try { text = new UTF8Encoding(false, true).GetString(bytes); } + catch (DecoderFallbackException) { return string.Concat(bytes.Select(x => $"\\x{x:X2}")); } + return string.Concat(text.Select(x => char.IsControl(x) || x == '\\' ? $"\\u{(int)x:X4}" : x.ToString())); + } + + private sealed class Reader(byte[] data) + { + public int Position { get; set; } + public void Require(int count) + { + if (count < 0 || Position + count > data.Length) + throw new InvalidDataException(); + } + public byte Byte() { Require(1); return data[Position++]; } + public ushort U16() => (ushort)((Byte() << 8) | Byte()); + public uint U32() => ((uint)U16() << 16) | U16(); + public void Skip(int count) { Require(count); Position += count; } + public byte[] Bytes(int count) { Require(count); var value = data[Position..(Position + count)]; Position += count; return value; } + + public string Name(int? end = null) + { + var labels = new List(); + var position = Position; + var next = -1; + var jumps = 0; + var wireLength = 1; + while (true) + { + if (position >= data.Length || next < 0 && end.HasValue && position >= end.Value) + throw new InvalidDataException(); + var length = data[position++]; + if (length == 0) + break; + if ((length & 0xC0) == 0xC0) + { + if (position >= data.Length || next < 0 && end.HasValue && position >= end.Value || ++jumps > 32) + throw new InvalidDataException(); + var pointer = ((length & 0x3F) << 8) | data[position++]; + // DNS compression refers to a prior occurrence; reject forward/self references. + if (pointer >= position - 2) + throw new InvalidDataException(); + if (next < 0) + next = position; + position = pointer; + continue; + } + if (length > 63 || position + length > data.Length || + next < 0 && end.HasValue && position + length > end.Value || (wireLength += length + 1) > 255) + throw new InvalidDataException(); + string label; + try { label = new UTF8Encoding(false, true).GetString(data, position, length); } + catch (DecoderFallbackException) { throw new InvalidDataException(); } + if (label.Any(char.IsControl)) + throw new InvalidDataException(); + label = label.Replace("\\", "\\\\").Replace(".", "\\."); + labels.Add(label); + position += length; + } + Position = next < 0 ? position : next; + return string.Join('.', labels) + "."; + } + } +} diff --git a/Source/NETworkManager.Models/Network/MDNSRecordInfo.cs b/Source/NETworkManager.Models/Network/MDNSRecordInfo.cs new file mode 100644 index 0000000000..02578d024f --- /dev/null +++ b/Source/NETworkManager.Models/Network/MDNSRecordInfo.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using NETworkManager.Utilities; + +namespace NETworkManager.Models.Network; + +/// A cached DNS resource record or individual TXT entry for the Records view and export. +public sealed class MDNSRecordInfo : PropertyChangedBase +{ + public string Id { get; } + public string Name { get; } + public string Type { get; } + public string Class => "IN"; + public string Value { get; } + public string NetworkInterface { get; } + public bool CacheFlush { get; private set; } + public uint TTL + { + get; + private set { if (value == field) return; field = value; OnPropertyChanged(); } + } + + public MDNSRecordInfo(string id, string name, string type, string value, string networkInterface, bool cacheFlush, uint ttl) + { + Id = id; + Name = name; + Type = type; + Value = value; + NetworkInterface = networkInterface; + CacheFlush = cacheFlush; + TTL = ttl; + } + + public void UpdateFrom(MDNSRecordInfo value) + { + TTL = value.TTL; + if (CacheFlush == value.CacheFlush) return; + CacheFlush = value.CacheFlush; + OnPropertyChanged(nameof(CacheFlush)); + } +} + +/// Detached results delivered together, so the services and records views describe the same cache. +public sealed record MDNSDiscoverySnapshot(IReadOnlyList Services, IReadOnlyList Records); diff --git a/Source/NETworkManager.Models/Network/MDNSServiceCache.cs b/Source/NETworkManager.Models/Network/MDNSServiceCache.cs new file mode 100644 index 0000000000..0ad4fc647d --- /dev/null +++ b/Source/NETworkManager.Models/Network/MDNSServiceCache.cs @@ -0,0 +1,183 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using NETworkManager.Utilities; + +namespace NETworkManager.Models.Network; + +/// +/// Per-link DNS-SD cache. Keeps independently arriving PTR/SRV/TXT/address records until their TTL expires, +/// observes goodbye/cache-flush records, and schedules follow-up questions with exponential backoff. +/// The browser serializes access; no UI objects are shared with it. +/// +public sealed class MDNSServiceCache +{ + public static IReadOnlyList CommonServiceTypes { get; } = Array.AsReadOnly(new[] + { + "_ipp._tcp.local.", "_ipps._tcp.local.", "_printer._tcp.local.", "_pdl-datastream._tcp.local.", + "_scanner._tcp.local.", "_uscan._tcp.local.", "_http._tcp.local.", "_https._tcp.local.", + "_ssh._tcp.local.", "_smb._tcp.local.", "_airplay._tcp.local.", "_googlecast._tcp.local." + }); + + private sealed record Entry(MDNSRecord Record, DateTimeOffset Received, DateTimeOffset Expires); + private sealed record Question(DateTimeOffset Next, int Interval); + private readonly Dictionary _records = new(StringComparer.Ordinal); + private readonly Dictionary<(string Name, ushort Type), Question> _questions = new(); + private readonly string _serviceType; + private readonly string _networkInterface; + + public MDNSServiceCache(string serviceType, string networkInterface) + { + if (!MDNSServiceType.TryNormalize(serviceType, out _serviceType)) + throw new ArgumentException("Invalid service type.", nameof(serviceType)); + _networkInterface = networkInterface; + } + + private static string Key(MDNSRecord record) => $"{record.Name.ToLowerInvariant()}|{record.Type}|{record.Identity}"; + + public void ProcessResponse(byte[] message, DateTimeOffset now, long ipv6ScopeId = 0) + { + Expire(now); + // The Records view also keeps reverse names and other owners seen on the link. Service browsing and + // follow-up questions remain restricted to the requested local DNS-SD service types. + var records = MDNSMessage.ReadResponse(message, ipv6ScopeId); + + // A cache-flush RRset may span packets. Give older values one second's grace, and preserve values just + // received in the same second (RFC 6762 section 10.2); a goodbye is also held for one second. + foreach (var group in records.Where(x => x.CacheFlush && x.TTL > 0).GroupBy(x => (x.Name.ToLowerInvariant(), x.Type))) + { + var keys = group.Select(Key).ToHashSet(StringComparer.Ordinal); + foreach (var old in _records.Where(x => x.Value.Record.Name.Equals(group.Key.Item1, StringComparison.OrdinalIgnoreCase) && + x.Value.Record.Type == group.Key.Type && !keys.Contains(x.Key) && + now - x.Value.Received >= TimeSpan.FromSeconds(1)).ToArray()) + _records[old.Key] = old.Value with { Expires = Min(old.Value.Expires, now.AddSeconds(1)) }; + } + + foreach (var record in records) + { + var key = Key(record); + if (record.TTL == 0) + { + if (_records.TryGetValue(key, out var entry)) + _records[key] = entry with { Expires = Min(entry.Expires, now.AddSeconds(1)) }; + } + else if (_records.ContainsKey(key) || _records.Count < 4096) + _records[key] = new Entry(record, now, now.AddSeconds(record.TTL)); + } + } + + private static DateTimeOffset Min(DateTimeOffset first, DateTimeOffset second) => first < second ? first : second; + + private void Expire(DateTimeOffset now) + { + foreach (var key in _records.Where(x => x.Value.Expires <= now).Select(x => x.Key).ToArray()) + _records.Remove(key); + } + + private IEnumerable Instances => _records.Values.Where(x => x.Record.Type == MDNSMessage.PTR && + MDNSServiceType.TryNormalize(x.Record.Name, out var type) && type != "*" && + (_serviceType == "*" || type == _serviceType) && + x.Record.Target.EndsWith("." + type, StringComparison.OrdinalIgnoreCase) && + x.Record.Target.Length > type.Length + 1); + + /// Returns at most 256 due questions per tick; repeated unanswered queries back off to 60 seconds. + public IReadOnlyList<(string Name, ushort Type)> GetQuestions(DateTimeOffset now) + { + Expire(now); + var wanted = new Dictionary<(string Name, ushort Type), string>(); + void Add(string name, ushort type) => wanted.TryAdd((name.ToLowerInvariant(), type), name); + if (_serviceType == "*") + { + Add(MDNSServiceType.Enumeration, MDNSMessage.PTR); + foreach (var type in CommonServiceTypes) + Add(type, MDNSMessage.PTR); + foreach (var record in _records.Values.Where(x => x.Record.Type == MDNSMessage.PTR && + x.Record.Name.Equals(MDNSServiceType.Enumeration, StringComparison.OrdinalIgnoreCase))) + if (MDNSServiceType.TryNormalize(record.Record.Target, out var type) && type != "*") + Add(type, MDNSMessage.PTR); + } + else + Add(_serviceType, MDNSMessage.PTR); + + var instances = Instances.ToArray(); + var instanceNames = instances.Select(x => x.Record.Target).ToHashSet(StringComparer.OrdinalIgnoreCase); + foreach (var instance in instances) + { + Add(instance.Record.Target, MDNSMessage.SRV); + Add(instance.Record.Target, MDNSMessage.TXT); + } + foreach (var record in _records.Values.Where(x => x.Record.Type == MDNSMessage.SRV && instanceNames.Contains(x.Record.Name))) + { + if (!record.Record.Target.EndsWith(".local.", StringComparison.OrdinalIgnoreCase)) + continue; + Add(record.Record.Target, MDNSMessage.A); + Add(record.Record.Target, MDNSMessage.AAAA); + } + + foreach (var key in _questions.Keys.Where(x => !wanted.ContainsKey(x)).ToArray()) + _questions.Remove(key); + var lifetimes = _records.Values.ToLookup(x => (x.Record.Name.ToLowerInvariant(), x.Record.Type)); + var due = new List<(string Name, ushort Type)>(); + foreach (var key in wanted.Keys) + { + if (_questions.TryGetValue(key, out var question) && question.Next > now) + continue; + if (due.Count == 256) + break; + due.Add((wanted[key], key.Type)); + var interval = Math.Min(60, question == null ? 1 : question.Interval * 2); + // Refresh short-lived records before expiry, even after the question has backed off. + var lifetime = lifetimes[key] + .Select(x => (x.Expires - now).TotalSeconds * 0.8).DefaultIfEmpty(interval).Min(); + _questions[key] = new Question(now.AddSeconds(Math.Max(1, Math.Min(interval, lifetime))), interval); + } + return due; + } + + /// Creates detached snapshots, including instances whose SRV/address resolution is still pending. + public IReadOnlyList GetServices(DateTimeOffset now) + { + Expire(now); + var result = new List(); + var byName = _records.Values.ToLookup(x => x.Record.Name, StringComparer.OrdinalIgnoreCase); + foreach (var instance in Instances) + { + var fullName = instance.Record.Target; + var srv = byName[fullName].Where(x => x.Record.Type == MDNSMessage.SRV) + .OrderByDescending(x => x.Received).FirstOrDefault(); + var txt = byName[fullName].Where(x => x.Record.Type == MDNSMessage.TXT) + .OrderByDescending(x => x.Received).FirstOrDefault(); + var addresses = srv == null ? [] : byName[srv.Record.Target].Where(x => x.Record.Address != null) + .Select(x => x.Record.Address.ToString()).Distinct().Order().ToArray(); + var name = fullName[..^(instance.Record.Name.Length + 1)].Replace("\\.", ".").Replace("\\\\", "\\"); + result.Add(new MDNSServiceInfo(fullName, name, instance.Record.Name, _networkInterface, + srv?.Record.Target ?? string.Empty, srv?.Record.Port, srv?.Record.Priority, srv?.Record.Weight, + string.Join("; ", addresses), string.Join(Environment.NewLine, txt?.Record.Text ?? []), + (uint)Math.Max(0, Math.Ceiling((instance.Expires - now).TotalSeconds)))); + } + return result; + } + + /// One row per resource record, with each character string of a TXT record on its own row. + public IReadOnlyList GetRecords(DateTimeOffset now) + { + Expire(now); + return _records.SelectMany(pair => + { + var record = pair.Value.Record; + var type = Enum.IsDefined((DnsClient.QueryType)record.Type) + ? ((DnsClient.QueryType)record.Type).ToString() + : $"TYPE{record.Type}"; + var values = record.Type switch + { + MDNSMessage.PTR => new[] { record.Target }, + MDNSMessage.SRV => [$"{record.Priority} {record.Weight} {record.Port} {record.Target}"], + MDNSMessage.TXT => record.Text is { Length: > 0 } ? record.Text : [string.Empty], + _ => [record.Address?.ToString() ?? $"\\# {record.RawData?.Length ?? 0} {Convert.ToHexString(record.RawData ?? [])}".TrimEnd()] + }; + var ttl = (uint)Math.Max(0, Math.Ceiling((pair.Value.Expires - now).TotalSeconds)); + return values.Select((value, index) => new MDNSRecordInfo($"{pair.Key}|{index}", record.Name, type, value, + _networkInterface, record.CacheFlush, ttl)); + }).Take(4096).ToArray(); + } +} diff --git a/Source/NETworkManager.Models/Network/MDNSServiceInfo.cs b/Source/NETworkManager.Models/Network/MDNSServiceInfo.cs new file mode 100644 index 0000000000..47ff7f5c6a --- /dev/null +++ b/Source/NETworkManager.Models/Network/MDNSServiceInfo.cs @@ -0,0 +1,51 @@ +using System; +using NETworkManager.Utilities; + +namespace NETworkManager.Models.Network; + +/// A discovered DNS-SD instance. Updated on the UI thread from independent cache snapshots. +public sealed class MDNSServiceInfo : PropertyChangedBase +{ + public string FullName { get; init; } + public string Name { get; init; } + public string ServiceType { get; init; } + public string NetworkInterface { get; init; } + public string Hostname { get; private set; } + public ushort? Port { get; private set; } + public ushort? Priority { get; private set; } + public ushort? Weight { get; private set; } + public string Addresses { get; private set; } + public string TXTRecords { get; private set; } + public uint TTL { get; private set; } + + public MDNSServiceInfo(string fullName, string name, string serviceType, string networkInterface, + string hostname, ushort? port, ushort? priority, ushort? weight, string addresses, string txtRecords, uint ttl) + { + FullName = fullName; + Name = name; + ServiceType = serviceType; + NetworkInterface = networkInterface; + Hostname = hostname; + Port = port; + Priority = priority; + Weight = weight; + Addresses = addresses; + TXTRecords = txtRecords; + TTL = ttl; + } + + public void UpdateFrom(MDNSServiceInfo value) + { + if (Hostname == value.Hostname && Port == value.Port && Priority == value.Priority && Weight == value.Weight && + Addresses == value.Addresses && TXTRecords == value.TXTRecords && TTL == value.TTL) + return; + Hostname = value.Hostname; + Port = value.Port; + Priority = value.Priority; + Weight = value.Weight; + Addresses = value.Addresses; + TXTRecords = value.TXTRecords; + TTL = value.TTL; + OnPropertyChanged(string.Empty); + } +} diff --git a/Source/NETworkManager.Models/RunCommand/RunCommandTarget.cs b/Source/NETworkManager.Models/RunCommand/RunCommandTarget.cs index aefdbfe945..c3692f4264 100644 --- a/Source/NETworkManager.Models/RunCommand/RunCommandTarget.cs +++ b/Source/NETworkManager.Models/RunCommand/RunCommandTarget.cs @@ -36,6 +36,9 @@ public static RunCommandTargetKind GetKind(string target) if (string.IsNullOrEmpty(target) || target.Any(char.IsWhiteSpace)) return RunCommandTargetKind.None; + if (MDNSServiceType.TryNormalize(target, out _)) + return RunCommandTargetKind.ServiceType; + if (RegexHelper.HttpOrHttpsSchemeRegex().IsMatch(target)) return Uri.TryCreate(target, UriKind.Absolute, out _) ? RunCommandTargetKind.URL : RunCommandTargetKind.None; diff --git a/Source/NETworkManager.Models/RunCommand/RunCommandTargetKind.cs b/Source/NETworkManager.Models/RunCommand/RunCommandTargetKind.cs index f3feeee7b6..1bd66b91d9 100644 --- a/Source/NETworkManager.Models/RunCommand/RunCommandTargetKind.cs +++ b/Source/NETworkManager.Models/RunCommand/RunCommandTargetKind.cs @@ -59,5 +59,8 @@ public enum RunCommandTargetKind /// /// HTTP or HTTPS URL. /// - URL + URL, + + /// Local DNS-SD service type (e.g. _ipp._tcp) or * for all service types. + ServiceType } diff --git a/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs b/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs index c44628327f..b6ac33d458 100644 --- a/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs +++ b/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs @@ -389,6 +389,13 @@ public static class GlobalStaticConfiguration public static AutoRefreshTimeInfo Connections_AutoRefreshTime => AutoRefreshTime.GetDefaults.First(x => x.Value == 30 && x.TimeUnit == TimeUnit.Second); + // Application: mDNS / DNS-SD + public static string MDNSDiscovery_ServiceType => "*"; + public static int MDNSDiscovery_Duration => 10; + public static string MDNSDiscovery_InterfaceId => string.Empty; + public static ExportFileType MDNSDiscovery_ExportFileType => ExportFileType.Csv; + public static string MDNSDiscovery_ExportFilePath => string.Empty; + // Application: Listeners public static ExportFileType Listeners_ExportFileType => ExportFileType.Csv; @@ -402,4 +409,4 @@ public static class GlobalStaticConfiguration AutoRefreshTime.GetDefaults.First(x => x.Value == 30 && x.TimeUnit == TimeUnit.Second); #endregion -} \ No newline at end of file +} diff --git a/Source/NETworkManager.Settings/SettingsInfo.cs b/Source/NETworkManager.Settings/SettingsInfo.cs index 67966df2a8..c072baa7dc 100644 --- a/Source/NETworkManager.Settings/SettingsInfo.cs +++ b/Source/NETworkManager.Settings/SettingsInfo.cs @@ -35,6 +35,40 @@ namespace NETworkManager.Settings; /// in applications that require user customization and state management across sessions. public class SettingsInfo : INotifyPropertyChanged { + #region mDNS / DNS-SD + + public string MDNSDiscovery_ServiceType + { + get; + set { if (value == field) return; field = value; OnPropertyChanged(); } + } = GlobalStaticConfiguration.MDNSDiscovery_ServiceType; + + public int MDNSDiscovery_Duration + { + get; + set { if (value == field) return; field = value; OnPropertyChanged(); } + } = GlobalStaticConfiguration.MDNSDiscovery_Duration; + + public string MDNSDiscovery_InterfaceId + { + get; + set { if (value == field) return; field = value; OnPropertyChanged(); } + } = GlobalStaticConfiguration.MDNSDiscovery_InterfaceId; + + public ExportFileType MDNSDiscovery_ExportFileType + { + get; + set { if (value == field) return; field = value; OnPropertyChanged(); } + } = GlobalStaticConfiguration.MDNSDiscovery_ExportFileType; + + public string MDNSDiscovery_ExportFilePath + { + get; + set { if (value == field) return; field = value; OnPropertyChanged(); } + } = GlobalStaticConfiguration.MDNSDiscovery_ExportFilePath; + + #endregion + /// /// Occurs when a property value changes. /// @@ -4804,4 +4838,4 @@ private void UpdateCollectionChanged(INotifyCollectionChanged oldCollection, INo } #endregion -} \ No newline at end of file +} diff --git a/Source/NETworkManager.Settings/SettingsManager.cs b/Source/NETworkManager.Settings/SettingsManager.cs index 3a76a0af05..1eafbabfda 100644 --- a/Source/NETworkManager.Settings/SettingsManager.cs +++ b/Source/NETworkManager.Settings/SettingsManager.cs @@ -745,6 +745,13 @@ private static void UpgradeToLatest(Version version) { Log.Info($"Apply upgrade to {version}..."); + if (Current.General_ApplicationList.All(x => x.Name != ApplicationName.MDNSDiscovery)) + { + Log.Info($"Add new app {nameof(ApplicationName.MDNSDiscovery)}."); + Current.General_ApplicationList.Add(ApplicationManager.GetDefaultList() + .First(x => x.Name == ApplicationName.MDNSDiscovery)); + } + // Add RDAP application if (Current.General_ApplicationList.All(x => x.Name != ApplicationName.RDAP)) { diff --git a/Source/NETworkManager.Tests/Export/ExportManagerMDNSServiceInfoTests.cs b/Source/NETworkManager.Tests/Export/ExportManagerMDNSServiceInfoTests.cs new file mode 100644 index 0000000000..f13a7c2668 --- /dev/null +++ b/Source/NETworkManager.Tests/Export/ExportManagerMDNSServiceInfoTests.cs @@ -0,0 +1,47 @@ +using System; +using NETworkManager.Models.Export; +using NETworkManager.Models.Network; +using Xunit; +using static NETworkManager.Tests.Export.ExportTestHelper; + +namespace NETworkManager.Tests.Export; + +public class ExportManagerMDNSServiceInfoTests +{ + [Fact] + public void ExportsPrinterDetailsWithTypedPortAndMultilineTXT() + { + var service = new MDNSServiceInfo("Office Printer._ipp._tcp.local.", "Office, Printer", "_ipp._tcp.local.", + "Ethernet", "printer.local.", 631, 0, 0, "192.168.1.20; fe80::20%7", + "ty=Office \"Printer\"" + Environment.NewLine + "rp=ipp/print", 120); + var files = ExportAll((path, type) => ExportManager.Export(path, type, new[] { service })); + var json = Assert.Single(files.JsonItems); + Assert.Equal(631, (int)json["Port"]); + Assert.Equal(service.TXTRecords, (string)json["TXTRecords"]); + Assert.Equal(service.Name, Assert.Single(files.XmlItems).Element("Name")?.Value); + Assert.Contains("\"Office, Printer\"", files.Csv); + Assert.Contains("\"\"Printer\"\"", files.Csv); + } + + [Fact] + public void UnresolvedServiceHasNullPortInExport() + { + var service = new MDNSServiceInfo("Printer._ipp._tcp.local.", "Printer", "_ipp._tcp.local.", + "Ethernet", "", null, null, null, "", "", 120); + var files = ExportAll((path, type) => ExportManager.Export(path, type, new[] { service })); + Assert.Equal(Newtonsoft.Json.Linq.JTokenType.Null, Assert.Single(files.JsonItems)["Port"]?.Type); + } + + [Fact] + public void ExportsDNSRecordsWithTypedTTLAndSingleLineValue() + { + var record = new MDNSRecordInfo("id", "Printer._ipp._tcp.local.", "SRV", "0 0 631 printer.local.", "Ethernet", true, 119); + var files = ExportAll((path, type) => ExportManager.Export(path, type, new[] { record })); + var json = Assert.Single(files.JsonItems); + Assert.Equal(119, (int)json["TTL"]); + Assert.True((bool)json["CacheFlush"]); + Assert.Equal(record.Value, (string)json["Value"]); + Assert.Equal(record.Value, Assert.Single(files.XmlItems).Element("Value")?.Value); + Assert.Equal(7, files.CsvHeader.Count); + } +} diff --git a/Source/NETworkManager.Tests/Network/MDNSDiscoveryTests.cs b/Source/NETworkManager.Tests/Network/MDNSDiscoveryTests.cs new file mode 100644 index 0000000000..d45d389eef --- /dev/null +++ b/Source/NETworkManager.Tests/Network/MDNSDiscoveryTests.cs @@ -0,0 +1,319 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Text; +using NETworkManager.Models.Network; +using NETworkManager.Utilities; +using Xunit; + +namespace NETworkManager.Tests.Network; + +public class MDNSDiscoveryTests +{ + private const string Type = "_ipp._tcp.local."; + private const string Instance = "Office Printer._ipp._tcp.local."; + private const string Host = "printer.local."; + private static readonly DateTimeOffset Now = new(2026, 11, 16, 12, 0, 0, TimeSpan.Zero); + + private sealed record Record(string Name, ushort Type, byte[] Data, uint TTL = 120, bool Flush = false); + + private static byte[] Name(string name) => Labels(name.TrimEnd('.').Split('.')); + private static byte[] Labels(params string[] labels) => + [.. labels.SelectMany(x => new[] { (byte)Encoding.UTF8.GetByteCount(x) }.Concat(Encoding.UTF8.GetBytes(x))), 0]; + + private static byte[] Packet(params Record[] records) + { + var bytes = new List { 0, 0, 0x84, 0, 0, 0, (byte)(records.Length >> 8), (byte)records.Length, 0, 0, 0, 0 }; + foreach (var record in records) + { + bytes.AddRange(Name(record.Name)); + bytes.AddRange([(byte)(record.Type >> 8), (byte)record.Type, record.Flush ? (byte)0x80 : (byte)0, 1, + (byte)(record.TTL >> 24), (byte)(record.TTL >> 16), (byte)(record.TTL >> 8), (byte)record.TTL, + (byte)(record.Data.Length >> 8), (byte)record.Data.Length]); + bytes.AddRange(record.Data); + } + return [.. bytes]; + } + + private static Record Ptr(uint ttl = 120) => new(Type, 12, Name(Instance), ttl); + private static Record Srv() => new(Instance, 33, [0, 10, 0, 20, 2, 119, .. Name(Host)], Flush: true); + private static Record Address(string address = "192.168.1.20", bool flush = false) => + new(Host, (ushort)(address.Contains(':') ? 28 : 1), IPAddress.Parse(address).GetAddressBytes(), Flush: flush); + + [Theory] + [InlineData("*", "*")] + [InlineData(" _IPP._TCP ", Type)] + [InlineData("_ipp._tcp.local.", Type)] + [InlineData("_pdl-datastream._tcp", "_pdl-datastream._tcp.local.")] + [InlineData("_foo1._udp.local", "_foo1._udp.local.")] + public void NormalizesLocalServiceTypes(string input, string expected) + { + Assert.True(MDNSServiceType.TryNormalize(input, out var type)); + Assert.Equal(expected, type); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("_ipp._tcp.example.com")] + [InlineData("ipp._tcp")] + [InlineData("_ipp._sctp")] + [InlineData("_123._tcp")] + [InlineData("_-ipp._tcp")] + [InlineData("_ip--p._tcp")] + [InlineData("_1234567890123456._tcp")] + [InlineData("_http._tcp;_ipp._tcp")] + public void RejectsInvalidAndNonLocalServiceTypes(string input) => + Assert.False(MDNSServiceType.TryNormalize(input, out _)); + + [Fact] + public void BrowsingQueriesHaveZeroIdAndMulticastINClass() + { + var query = MDNSMessage.CreateQuery(Type, 12); + Assert.Equal(new byte[] { 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 }, query[..12]); + Assert.Equal(Name(Type), query[12..^4]); + Assert.Equal(new byte[] { 0, 12, 0, 1 }, query[^4..]); + Assert.Empty(MDNSMessage.ReadResponse(query)); + } + + [Fact] + public void ReadsCompressedPtrAndAdditionalRecords() + { + // The instance suffix points back to the PTR owner's service type at offset 12. + var packet = Packet(new Record(Type, 12, [14, .. Encoding.UTF8.GetBytes("Office Printer"), 0xC0, 12]), Srv(), Address()); + // Move the SRV and address from the answer section into the additional section. + packet[7] = 1; + packet[11] = 2; + var records = MDNSMessage.ReadResponse(packet); + Assert.Equal(3, records.Count); + Assert.Equal(Instance, records[0].Target); + Assert.Equal((ushort)631, records[1].Port); + Assert.Equal((ushort)10, records[1].Priority); + Assert.Equal((ushort)20, records[1].Weight); + Assert.True(records[1].CacheFlush); + Assert.Equal(IPAddress.Parse("192.168.1.20"), records[2].Address); + } + + [Fact] + public void InstanceLabelsWithDotsBackslashesAndUnicodeRoundTripIntoFollowupQuestion() + { + var instanceWire = Labels("Büro.Printer\\One", "_ipp", "_tcp", "local"); + var record = Assert.Single(MDNSMessage.ReadResponse(Packet(new Record(Type, 12, instanceWire)))); + var query = MDNSMessage.CreateQuery(record.Target, 33); + Assert.Equal(instanceWire, query[12..^4]); + } + + [Fact] + public void PreservesBinaryTXTAndEscapesControlCharacters() + { + var txt = new Record(Instance, 16, [3, 97, 0, 98, 2, 0xFF, 0xFE, 0]); + var record = Assert.Single(MDNSMessage.ReadResponse(Packet(txt))); + Assert.Equal(new[] { "a\\u0000b", "\\xFF\\xFE", "" }, record.Text); + } + + [Fact] + public void RejectsAllTruncatedPrefixesAndPointerLoops() + { + var packet = Packet(Ptr(), Srv(), Address()); + for (var length = 0; length < packet.Length; length++) + Assert.Empty(MDNSMessage.ReadResponse(packet[..length])); + packet = Packet(new Record(Type, 12, [0xC0, 12])); + // Owner name points to itself. + packet[12] = 0xC0; + packet[13] = 12; + Assert.Empty(MDNSMessage.ReadResponse(packet)); + Assert.Empty(MDNSMessage.ReadResponse(Packet(new Record(Type, 12, [0xFF, 0xFF])))); + Assert.Empty(MDNSMessage.ReadResponse(Packet(new Record(Instance, 16, [20, 1])))); + Assert.Empty(MDNSMessage.ReadResponse(Packet(new Record(Instance, 33, [0, 1])))); + } + + [Fact] + public void MergesOutOfOrderResponsesAndReturnsUnresolvedInstances() + { + var cache = new MDNSServiceCache(Type, "Ethernet"); + cache.ProcessResponse(Packet(Ptr()), Now); + var pending = Assert.Single(cache.GetServices(Now)); + Assert.Null(pending.Port); + Assert.Empty(pending.Hostname); + Assert.Contains((Instance, (ushort)33), cache.GetQuestions(Now)); + cache.ProcessResponse(Packet(Address("fe80::1234"), Address()), Now, 7); + cache.ProcessResponse(Packet(Srv()), Now); + var result = Assert.Single(cache.GetServices(Now)); + Assert.Equal("Office Printer", result.Name); + Assert.Equal(Host, result.Hostname); + Assert.Equal((ushort)631, result.Port); + Assert.Contains("192.168.1.20", result.Addresses); + Assert.Contains("fe80::1234%7", result.Addresses); + Assert.Equal("Ethernet", result.NetworkInterface); + Assert.Single(cache.GetServices(Now)); + } + + [Fact] + public void EnumeratesUnknownTypesAndSeedsPrinters() + { + var cache = new MDNSServiceCache("*", "Ethernet"); + var questions = cache.GetQuestions(Now); + Assert.Contains((MDNSServiceType.Enumeration, (ushort)12), questions); + Assert.Contains((Type, (ushort)12), questions); + cache.ProcessResponse(Packet(new Record(MDNSServiceType.Enumeration, 12, Name("_custom._udp.local."))), Now); + Assert.Contains(("_custom._udp.local.", (ushort)12), cache.GetQuestions(Now)); + Assert.Empty(cache.GetQuestions(Now)); + Assert.NotEmpty(cache.GetQuestions(Now.AddSeconds(1))); + } + + [Fact] + public void FiltersServicesByRequestedTypeAndHonorsTTL() + { + var cache = new MDNSServiceCache("_http._tcp", "Ethernet"); + cache.ProcessResponse(Packet(Ptr()), Now); + Assert.Empty(cache.GetServices(Now)); + cache = new MDNSServiceCache(Type, "Ethernet"); + cache.ProcessResponse(Packet(Ptr(2)), Now); + Assert.Single(cache.GetServices(Now)); + Assert.Empty(cache.GetServices(Now.AddSeconds(2))); + } + + [Fact] + public void GoodbyeRemovesServiceAfterOneSecondGrace() + { + var cache = new MDNSServiceCache(Type, "Ethernet"); + cache.ProcessResponse(Packet(Ptr(), Srv(), Address()), Now); + cache.ProcessResponse(Packet(Ptr(0)), Now.AddSeconds(1)); + Assert.Single(cache.GetServices(Now.AddSeconds(1.5))); + Assert.Empty(cache.GetServices(Now.AddSeconds(2))); + } + + [Fact] + public void CacheFlushReplacesOldAddressAndPreservesRRSetAcrossPackets() + { + var cache = new MDNSServiceCache(Type, "Ethernet"); + cache.ProcessResponse(Packet(Ptr(), Srv(), Address()), Now); + cache.ProcessResponse(Packet(Address("192.168.1.30", true)), Now.AddSeconds(2)); + cache.ProcessResponse(Packet(Address("192.168.1.31", true)), Now.AddSeconds(2.1)); + var result = Assert.Single(cache.GetServices(Now.AddSeconds(3.2))); + Assert.DoesNotContain("192.168.1.20", result.Addresses); + Assert.Contains("192.168.1.30", result.Addresses); + Assert.Contains("192.168.1.31", result.Addresses); + } + + [Fact] + public void RepeatedAnnouncementsDeduplicateAndRefreshTTL() + { + var cache = new MDNSServiceCache(Type, "Ethernet"); + cache.ProcessResponse(Packet(Ptr(2)), Now); + cache.ProcessResponse(Packet(Ptr(2)), Now.AddSeconds(1)); + Assert.Single(cache.GetServices(Now.AddSeconds(2.5))); + Assert.Empty(cache.GetServices(Now.AddSeconds(3))); + } + + [Fact] + public void RecordsViewHasOneLinePerResourceRecordWithTTLAndType() + { + var cache = new MDNSServiceCache(Type, "Ethernet"); + cache.ProcessResponse(Packet(Ptr(), Srv(), Address(), Address("fe80::1234"), + new Record(Instance, 16, [4, 107, 61, 97, 10])), Now, 7); + var records = cache.GetRecords(Now.AddSeconds(1)); + Assert.Equal(5, records.Count); + Assert.Equal(new[] { "A", "AAAA", "PTR", "SRV", "TXT" }, records.Select(x => x.Type).Order()); + Assert.All(records, x => + { + Assert.Equal("IN", x.Class); + Assert.Equal((uint)119, x.TTL); + Assert.DoesNotContain('\n', x.Value); + Assert.DoesNotContain('\r', x.Value); + }); + Assert.Equal("10 20 631 printer.local.", Assert.Single(records, x => x.Type == "SRV").Value); + Assert.Equal("k=a\\u000A", Assert.Single(records, x => x.Type == "TXT").Value); + } + + [Fact] + public void TXTValuesAreCaseSensitiveAndReplacedAfterCacheFlushGrace() + { + var cache = new MDNSServiceCache(Type, "Ethernet"); + cache.ProcessResponse(Packet(new Record(Instance, 16, [3, 107, 61, 97], Flush: true)), Now); + cache.ProcessResponse(Packet(new Record(Instance, 16, [3, 107, 61, 65], Flush: true)), Now.AddSeconds(2)); + Assert.Equal(2, cache.GetRecords(Now.AddSeconds(2)).Count); + Assert.Equal("k=A", Assert.Single(cache.GetRecords(Now.AddSeconds(3))).Value); + } + + [Fact] + public void FollowupQuestionsPreserveInstanceNameCaseAndIgnoreUnrelatedSRVRecords() + { + var cache = new MDNSServiceCache(Type, "Ethernet"); + cache.ProcessResponse(Packet(Ptr(), new Record("Unrelated._http._tcp.local.", 33, [0, 0, 0, 0, 0, 80, .. Name("other.local.")])), Now); + var questions = cache.GetQuestions(Now); + Assert.Contains((Instance, (ushort)33), questions); + Assert.DoesNotContain(questions, x => x.Name == "other.local."); + } + + [Fact] + public void EachTXTEntryHasItsOwnStableRowAndSharedRecordTTL() + { + var cache = new MDNSServiceCache(Type, "Ethernet"); + var txt = new Record(Instance, 16, [9, .. Encoding.UTF8.GetBytes("txtvers=1"), + 10, .. Encoding.UTF8.GetBytes("ty=Printer"), 12, .. Encoding.UTF8.GetBytes("rp=ipp/print")]); + cache.ProcessResponse(Packet(txt), Now); + var rows = cache.GetRecords(Now); + Assert.Equal(new[] { "txtvers=1", "ty=Printer", "rp=ipp/print" }, rows.Select(x => x.Value)); + Assert.Equal(3, rows.Select(x => x.Id).Distinct().Count()); + Assert.All(rows, x => { Assert.Equal("TXT", x.Type); Assert.Equal((uint)120, x.TTL); }); + cache.ProcessResponse(Packet(txt), Now.AddSeconds(1)); + Assert.Equal(rows.Select(x => x.Id), cache.GetRecords(Now.AddSeconds(2)).Select(x => x.Id)); + Assert.All(cache.GetRecords(Now.AddSeconds(2)), x => Assert.Equal((uint)119, x.TTL)); + } + + [Fact] + public void LargeTXTResponseHasBoundedRowsAndCompactUniqueIds() + { + var cache = new MDNSServiceCache(Type, "Ethernet"); + cache.ProcessResponse(Packet(new Record(Instance, 16, new byte[8000])), Now); + var rows = cache.GetRecords(Now); + Assert.Equal(4096, rows.Count); + Assert.Equal(rows.Count, rows.Select(x => x.Id).Distinct().Count()); + Assert.All(rows, x => Assert.True(x.Id.Length < 500)); + } + + [Fact] + public void UnknownRecordTypesArePreservedAndExpireLikeOtherRecords() + { + var cache = new MDNSServiceCache(Type, "Ethernet"); + var packet = Packet(new Record(Host, 65400, [0x00, 0xFF, 0x42, 0x80], TTL: 2)); + var parsed = Assert.Single(MDNSMessage.ReadResponse(packet)); + Assert.Equal(new byte[] { 0x00, 0xFF, 0x42, 0x80 }, parsed.RawData); + cache.ProcessResponse(packet, Now); + var row = Assert.Single(cache.GetRecords(Now)); + Assert.Equal("TYPE65400", row.Type); + Assert.Equal("\\# 4 00FF4280", row.Value); + Assert.Empty(cache.GetServices(Now)); + Assert.Empty(cache.GetRecords(Now.AddSeconds(2))); + } + + [Fact] + public void UnsupportedStandardRecordsAreVisibleAlongsideServiceRecords() + { + var cache = new MDNSServiceCache(Type, "Ethernet"); + cache.ProcessResponse(Packet(Ptr(), Srv(), Address(), new Record(Host, 47, [0, 0, 1, 0x40])), Now); + var records = cache.GetRecords(Now); + Assert.Equal(4, records.Count); + Assert.Contains(records, x => x.Type == "NSEC" && x.Value == "\\# 4 00000140"); + Assert.Single(cache.GetServices(Now)); + } + + [Fact] + public void UnknownZeroLengthRecordsRemainVisible() + { + var cache = new MDNSServiceCache(Type, "Ethernet"); + cache.ProcessResponse(Packet(new Record(Host, 65401, [])), Now); + Assert.Equal("\\# 0", Assert.Single(cache.GetRecords(Now)).Value); + } + + [Fact] + public void RecordsViewAlsoPreservesReverseOwnersWithoutStartingUnrelatedQueries() + { + var cache = new MDNSServiceCache(Type, "Ethernet"); + cache.ProcessResponse(Packet(new Record("20.1.168.192.in-addr.arpa.", 65400, [0x42])), Now); + Assert.Equal("20.1.168.192.in-addr.arpa.", Assert.Single(cache.GetRecords(Now)).Name); + Assert.Equal(new[] { (Type, (ushort)12) }, cache.GetQuestions(Now)); + } +} diff --git a/Source/NETworkManager.Tests/RunCommand/RunCommandTargetTests.cs b/Source/NETworkManager.Tests/RunCommand/RunCommandTargetTests.cs index 618eafbe75..e7794d16f0 100644 --- a/Source/NETworkManager.Tests/RunCommand/RunCommandTargetTests.cs +++ b/Source/NETworkManager.Tests/RunCommand/RunCommandTargetTests.cs @@ -34,6 +34,9 @@ public class RunCommandTargetTests [InlineData("80-90/tcp", RunCommandTargetKind.Ports)] [InlineData("AS13335", RunCommandTargetKind.ASN)] [InlineData("https://borntoberoot.net", RunCommandTargetKind.URL)] + [InlineData("_ipp._tcp", RunCommandTargetKind.ServiceType)] + [InlineData("_http._tcp.local.", RunCommandTargetKind.ServiceType)] + [InlineData("*", RunCommandTargetKind.ServiceType)] public void Kind(string target, RunCommandTargetKind kind) { Assert.Equal(kind, RunCommandTarget.GetKind(target)); diff --git a/Source/NETworkManager.Utilities/MDNSServiceType.cs b/Source/NETworkManager.Utilities/MDNSServiceType.cs new file mode 100644 index 0000000000..2fffdad1d3 --- /dev/null +++ b/Source/NETworkManager.Utilities/MDNSServiceType.cs @@ -0,0 +1,34 @@ +using System; +using System.Text.RegularExpressions; + +namespace NETworkManager.Utilities; + +/// Service types accepted by the multicast DNS-SD browser (local-link discovery only). +public static class MDNSServiceType +{ + public const string Enumeration = "_services._dns-sd._udp.local."; + + /// Normalizes a service type, or * for automatic service type enumeration. + public static bool TryNormalize(string input, out string serviceType) + { + serviceType = null; + var value = input?.Trim().TrimEnd('.').ToLowerInvariant(); + if (value == "*") + { + serviceType = value; + return true; + } + + if (value == null || value.Length > 90) + return false; + + // RFC 6335 service name: 1–15 letters/digits/hyphens, at least one letter, no consecutive hyphens. + if (!Regex.IsMatch(value, @"^_[a-z0-9](?:[a-z0-9-]{0,13}[a-z0-9])?\._(?:tcp|udp)(?:\.local)?$", + RegexOptions.CultureInvariant) || value.Split('.')[0].Contains("--") || + !Regex.IsMatch(value.Split('.')[0], "[a-z]", RegexOptions.CultureInvariant)) + return false; + + serviceType = value.EndsWith(".local", StringComparison.Ordinal) ? value + "." : value + ".local."; + return true; + } +} diff --git a/Source/NETworkManager.Validators/MDNSServiceTypeValidator.cs b/Source/NETworkManager.Validators/MDNSServiceTypeValidator.cs new file mode 100644 index 0000000000..da66be2885 --- /dev/null +++ b/Source/NETworkManager.Validators/MDNSServiceTypeValidator.cs @@ -0,0 +1,14 @@ +using System.Globalization; +using System.Windows.Controls; +using NETworkManager.Localization.Resources; +using NETworkManager.Utilities; + +namespace NETworkManager.Validators; + +public sealed class MDNSServiceTypeValidator : ValidationRule +{ + public override ValidationResult Validate(object value, CultureInfo cultureInfo) => + MDNSServiceType.TryNormalize(value as string, out _) + ? ValidationResult.ValidResult + : new ValidationResult(false, Strings.MDNSDiscovery_InvalidServiceType); +} diff --git a/Source/NETworkManager/MainWindow.xaml.cs b/Source/NETworkManager/MainWindow.xaml.cs index c19e372ffb..bcb8a28374 100644 --- a/Source/NETworkManager/MainWindow.xaml.cs +++ b/Source/NETworkManager/MainWindow.xaml.cs @@ -693,6 +693,7 @@ private void LoadApplicationList() private HostsFileEditorView _hostsFileEditorView; private FirewallView _firewallView; private DiscoveryProtocolView _discoveryProtocolView; + private MDNSDiscoveryView _mdnsDiscoveryView; private WakeOnLANView _wakeOnLanView; private SubnetCalculatorHostView _subnetCalculatorHostView; private BitCalculatorView _bitCalculatorView; @@ -857,6 +858,14 @@ private void OnApplicationViewVisible(ApplicationName name) ContentControlApplication.Content = _discoveryProtocolView; break; + case ApplicationName.MDNSDiscovery: + if (_mdnsDiscoveryView == null) + _mdnsDiscoveryView = new MDNSDiscoveryView(); + else + _mdnsDiscoveryView.OnViewVisible(); + + ContentControlApplication.Content = _mdnsDiscoveryView; + break; case ApplicationName.WakeOnLAN: if (_wakeOnLanView == null) _wakeOnLanView = new WakeOnLANView(); @@ -1001,6 +1010,9 @@ private void OnApplicationViewHide(ApplicationName name) case ApplicationName.DiscoveryProtocol: _discoveryProtocolView?.OnViewHide(); break; + case ApplicationName.MDNSDiscovery: + _mdnsDiscoveryView?.OnViewHide(); + break; case ApplicationName.WakeOnLAN: _wakeOnLanView?.OnViewHide(); break; diff --git a/Source/NETworkManager/RunCommandManager.cs b/Source/NETworkManager/RunCommandManager.cs index 65da272890..f51c5adf6d 100644 --- a/Source/NETworkManager/RunCommandManager.cs +++ b/Source/NETworkManager/RunCommandManager.cs @@ -77,7 +77,8 @@ public static class RunCommandManager [RunCommandTargetKind.OUI] = [ApplicationName.Lookup], [RunCommandTargetKind.Ports] = [ApplicationName.Lookup], [RunCommandTargetKind.ASN] = [ApplicationName.RDAP], - [RunCommandTargetKind.URL] = [ApplicationName.WebConsole] + [RunCommandTargetKind.URL] = [ApplicationName.WebConsole], + [RunCommandTargetKind.ServiceType] = [ApplicationName.MDNSDiscovery] }; /// @@ -313,6 +314,7 @@ ApplicationName.Traceroute or ApplicationName.PowerShell or ApplicationName.PuTT ApplicationName.WakeOnLAN => new MACAddressValidator(), ApplicationName.SubnetCalculator => new IPv4IPv6SubnetValidator(), ApplicationName.Lookup => new NotEndWithSemicolonValidator(), + ApplicationName.MDNSDiscovery => new MDNSServiceTypeValidator(), _ => null }; @@ -468,6 +470,8 @@ static RunCommandSyntaxPart Argument(string name) => ], RunCommandArgument.Ports), ApplicationName.PingMonitor => Create(name, ["ping"], [Target(Strings.Hosts)]), ApplicationName.Traceroute => Create(name, ["trace", "tracert"], [Target(Strings.Host)]), + ApplicationName.MDNSDiscovery => Create(name, ["mdns", "dnssd"], [Target(Strings.MDNSDiscovery_ServiceType)], + supportsProfile: false), ApplicationName.DNSLookup => Create(name, ["dns", "nslookup"], [Target(Strings.Hosts), Argument(Strings.DNSServer), type], RunCommandArgument.DNSServer, [.. DNSLookup.QueryTypes.Select(x => x.ToString().ToLowerInvariant()).Order()]), diff --git a/Source/NETworkManager/ViewModels/MDNSDiscoveryViewModel.cs b/Source/NETworkManager/ViewModels/MDNSDiscoveryViewModel.cs new file mode 100644 index 0000000000..1479dfc82a --- /dev/null +++ b/Source/NETworkManager/ViewModels/MDNSDiscoveryViewModel.cs @@ -0,0 +1,335 @@ +using log4net; +using MahApps.Metro.SimpleChildWindow; +using NETworkManager.Controls; +using NETworkManager.Localization.Resources; +using NETworkManager.Models.Export; +using NETworkManager.Models.Network; +using NETworkManager.Settings; +using NETworkManager.Utilities; +using NETworkManager.Utilities.WPF; +using NETworkManager.Views; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Globalization; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Data; +using System.Windows.Input; +using System.Windows.Threading; + +namespace NETworkManager.ViewModels; + +public sealed class MDNSDiscoveryViewModel : ViewModelBase +{ + private static readonly ILog Log = LogManager.GetLogger(typeof(MDNSDiscoveryViewModel)); + private readonly DispatcherTimer _flushTimer; + private readonly SearchDelay _searchDelay; + private readonly Dictionary _rows = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _recordRows = new(StringComparer.Ordinal); + private MDNSDiscoverySnapshot _pending; + private CancellationTokenSource _cancellation; + private Task _browseTask = Task.CompletedTask; + + public MDNSDiscoveryViewModel() + { + ServiceType = SettingsManager.Current.MDNSDiscovery_ServiceType; + if (!MDNSServiceType.TryNormalize(ServiceType, out _)) + ServiceType = GlobalStaticConfiguration.MDNSDiscovery_ServiceType; + Duration = Math.Clamp(SettingsManager.Current.MDNSDiscovery_Duration, 0, 3600); + _searchDelay = new SearchDelay(GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan, () => + { + ResultsView.Refresh(); + RecordsView.Refresh(); + }); + ResultsView = CollectionViewSource.GetDefaultView(Results); + ResultsView.SortDescriptions.Add(new SortDescription(nameof(MDNSServiceInfo.ServiceType), ListSortDirection.Ascending)); + ResultsView.SortDescriptions.Add(new SortDescription(nameof(MDNSServiceInfo.Name), ListSortDirection.Ascending)); + ResultsView.Filter = value => value is MDNSServiceInfo item && (string.IsNullOrWhiteSpace(Search) || + new[] { item.Name, item.ServiceType, item.Hostname, item.Addresses, item.Port?.ToString(), item.TXTRecords } + .Any(x => x?.Contains(Search, StringComparison.OrdinalIgnoreCase) == true)); + RecordsView = CollectionViewSource.GetDefaultView(Records); + RecordsView.SortDescriptions.Add(new SortDescription(nameof(MDNSRecordInfo.Name), ListSortDirection.Ascending)); + RecordsView.SortDescriptions.Add(new SortDescription(nameof(MDNSRecordInfo.Type), ListSortDirection.Ascending)); + RecordsView.Filter = value => value is MDNSRecordInfo item && (string.IsNullOrWhiteSpace(Search) || + new[] { item.Name, item.Type, item.Value }.Any(x => x.Contains(Search, StringComparison.OrdinalIgnoreCase))); + _flushTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(250) }; + _flushTimer.Tick += (_, _) => FlushResults(); + RefreshInterfaces(); + } + + public ObservableCollection Interfaces { get; } = new(); + public MDNSInterfaceInfo SelectedInterface + { + get; + set { if (value == field) return; field = value; OnPropertyChanged(); } + } + public IReadOnlyList ServiceTypes { get; } = ["*", .. MDNSServiceCache.CommonServiceTypes]; + public string ServiceType + { + get; + set { if (value == field) return; field = value; OnPropertyChanged(); } + } + public int Duration + { + get; + set { if (value == field) return; field = value; OnPropertyChanged(); } + } + public bool IsRunning + { + get; + private set + { + if (value == field) return; + field = value; + OnPropertyChanged(); + OnPropertyChanged(nameof(BrowseButtonText)); + CommandManager.InvalidateRequerySuggested(); + } + } + public bool IsCanceling + { + get; + private set { if (value == field) return; field = value; OnPropertyChanged(); } + } + public string BrowseButtonText => IsRunning ? Strings.Stop : Strings.MDNSDiscovery_Browse; + public string StatusMessage + { + get; + private set { if (value == field) return; field = value; OnPropertyChanged(); } + } + public StatusLevel StatusMessageLevel + { + get; + private set { if (value == field) return; field = value; OnPropertyChanged(); } + } + public string Search + { + get; + set { if (value == field) return; field = value; OnPropertyChanged(); _searchDelay?.Restart(); } + } + public ObservableCollection Results { get; } = new(); + public ICollectionView ResultsView { get; } + public ObservableCollection Records { get; } = new(); + public ICollectionView RecordsView { get; } + public IList SelectedRecords { get; set; } = new ArrayList(); + public int SelectedTabIndex + { + get; + set + { + if (value == field) return; + field = value; + OnPropertyChanged(); + OnPropertyChanged(nameof(DisplayedResultCount)); + CommandManager.InvalidateRequerySuggested(); + } + } + public int DisplayedResultCount => SelectedTabIndex == 0 ? Results.Count : Records.Count; + public MDNSServiceInfo SelectedResult + { + get; + set { if (value == field) return; field = value; OnPropertyChanged(); } + } + public IList SelectedResults { get; set; } = new ArrayList(); + + public ICommand ApplySearchCommand => _searchDelay.ApplyCommand; + public ICommand RefreshInterfacesCommand => new RelayCommand(_ => RefreshInterfaces(), _ => !IsRunning && !DialogHelper.IsAnyDialogOpen()); + public ICommand BrowseCommand => new RelayCommand(_ => + { + if (IsRunning) Stop(); + else _browseTask = BrowseAsync(); + }, parameter => !IsCanceling && !DialogHelper.IsAnyDialogOpen() && + (IsRunning || SelectedInterface != null && Duration is >= 0 and <= 3600 && MDNSServiceType.TryNormalize(ServiceType, out _))); + + private void RefreshInterfaces() + { + var id = SelectedInterface?.Id ?? SettingsManager.Current.MDNSDiscovery_InterfaceId; + try + { + var links = MDNSBrowser.GetInterfaces(); + Interfaces.Clear(); + foreach (var link in links) + Interfaces.Add(link); + SelectedInterface = Interfaces.FirstOrDefault(x => x.Id == id) ?? Interfaces.FirstOrDefault(); + if (SelectedInterface == null) + SetStatus(Strings.MDNSDiscovery_NoInterface, StatusLevel.Warning); + } + catch (Exception exception) + { + Log.Error("Cannot enumerate multicast interfaces.", exception); + SetStatus(Strings.MDNSDiscovery_Failed + Environment.NewLine + exception.Message, StatusLevel.Error); + } + } + + private async Task BrowseAsync() + { + if (IsRunning || SelectedInterface == null || !MDNSServiceType.TryNormalize(ServiceType, out var type)) + return; + _cancellation?.Dispose(); + using var timeout = new CancellationTokenSource(); + if (Duration > 0) + timeout.CancelAfter(TimeSpan.FromSeconds(Duration)); + _cancellation = new CancellationTokenSource(); + using var linked = CancellationTokenSource.CreateLinkedTokenSource(_cancellation.Token, timeout.Token); + var link = SelectedInterface; + SettingsManager.Current.MDNSDiscovery_ServiceType = ServiceType; + SettingsManager.Current.MDNSDiscovery_Duration = Duration; + SettingsManager.Current.MDNSDiscovery_InterfaceId = link.Id; + Results.Clear(); + Records.Clear(); + _rows.Clear(); + _recordRows.Clear(); + OnPropertyChanged(nameof(DisplayedResultCount)); + Interlocked.Exchange(ref _pending, null); + IsRunning = true; + IsCanceling = false; + SetStatus(Strings.MDNSDiscovery_Browsing, StatusLevel.None); + _flushTimer.Start(); + try + { + await Task.Run(() => MDNSBrowser.BrowseAsync(link, type, values => Interlocked.Exchange(ref _pending, values), linked.Token)); + } + catch (OperationCanceledException) when (linked.IsCancellationRequested) + { + SetStatus(_cancellation.IsCancellationRequested ? Strings.MDNSDiscovery_Stopped : Strings.MDNSDiscovery_Completed, StatusLevel.None); + } + catch (Exception exception) + { + Log.Error("mDNS service discovery failed.", exception); + SetStatus(Strings.MDNSDiscovery_Failed + Environment.NewLine + exception.Message, StatusLevel.Error); + } + finally + { + FlushResults(); + _flushTimer.Stop(); + IsCanceling = false; + IsRunning = false; + _cancellation.Dispose(); + _cancellation = null; + } + } + + private void FlushResults() + { + var values = Interlocked.Exchange(ref _pending, null); + if (values == null) return; + var names = values.Services.Select(x => x.FullName).ToHashSet(StringComparer.OrdinalIgnoreCase); + foreach (var name in _rows.Keys.Where(x => !names.Contains(x)).ToArray()) + { + Results.Remove(_rows[name]); + _rows.Remove(name); + } + foreach (var value in values.Services) + if (_rows.TryGetValue(value.FullName, out var row)) + row.UpdateFrom(value); + else + { + _rows.Add(value.FullName, value); + Results.Add(value); + } + var recordIds = values.Records.Select(x => x.Id).ToHashSet(StringComparer.Ordinal); + foreach (var id in _recordRows.Keys.Where(x => !recordIds.Contains(x)).ToArray()) + { + Records.Remove(_recordRows[id]); + _recordRows.Remove(id); + } + foreach (var value in values.Records) + if (_recordRows.TryGetValue(value.Id, out var row)) + row.UpdateFrom(value); + else + { + _recordRows.Add(value.Id, value); + Records.Add(value); + } + OnPropertyChanged(nameof(DisplayedResultCount)); + // A late TXT/address record can make an existing row match the current search. + if (!string.IsNullOrWhiteSpace(Search)) ResultsView.Refresh(); + } + + private void SetStatus(string text, StatusLevel level) + { + StatusMessageLevel = level; + StatusMessage = text; + } + + private void Stop() + { + if (!IsRunning) return; + IsCanceling = true; + _cancellation?.Cancel(); + } + + public void OnViewHide() => Stop(); + public void OnViewVisible() { if (!IsRunning) RefreshInterfaces(); } + + public async Task OpenAsync(ApplicationRequest request) + { + if (string.IsNullOrEmpty(request.Target)) return; + Stop(); + await _browseTask; + if (!MDNSServiceType.TryNormalize(request.Target, out _)) return; + ServiceType = request.Target; + if (request.Start) await (_browseTask = BrowseAsync()); + } + + public ICommand CopySelectionCommand => new RelayCommand(_ => ClipboardHelper.SetClipboard(SelectedTabIndex == 0 + ? string.Join(Environment.NewLine + Environment.NewLine, SelectedResults.Cast() + .Select(x => $"{x.FullName}\n{x.Hostname}\t{x.Port}\t{x.Addresses}\n{x.TXTRecords}")) + : string.Join(Environment.NewLine, SelectedRecords.Cast() + .Select(x => $"{x.Name}\t{x.Type}\t{x.Class}\t{x.TTL}\t{x.Value}"))), + _ => (SelectedTabIndex == 0 ? SelectedResults.Count : SelectedRecords.Count) > 0); + + public ICommand CopyPortCommand => new RelayCommand(_ => ClipboardHelper.SetClipboard(SelectedResult.Port.Value.ToString(CultureInfo.InvariantCulture)), + _ => SelectedResult?.Port.HasValue == true); + + public ICommand ExportCommand => new RelayCommand(_ => { _ = ExportAsync(); }, + _ => DisplayedResultCount > 0 && !DialogHelper.IsAnyDialogOpen()); + + private Task ExportAsync() + { + var exportRecords = SelectedTabIndex != 0; + var window = new ExportChildWindow { Title = Strings.Export }; + window.DataContext = new ExportViewModel(async instance => + { + window.IsOpen = false; + ConfigurationManager.Current.IsChildWindowOpen = false; + try + { + // Detach the rows before background export; incoming advertisements can still update the grid. + if (exportRecords) + { + var records = RecordsView.GetItemsInViewOrder(instance.ExportAll, SelectedRecords) + .Select(x => new MDNSRecordInfo(x.Id, x.Name, x.Type, x.Value, x.NetworkInterface, x.CacheFlush, x.TTL)).ToArray(); + await Task.Run(() => ExportManager.Export(instance.FilePath, instance.FileType, records)); + } + else + { + var values = ResultsView.GetItemsInViewOrder(instance.ExportAll, SelectedResults) + .Select(x => new MDNSServiceInfo(x.FullName, x.Name, x.ServiceType, x.NetworkInterface, x.Hostname, + x.Port, x.Priority, x.Weight, x.Addresses, x.TXTRecords, x.TTL)).ToArray(); + await Task.Run(() => ExportManager.Export(instance.FilePath, instance.FileType, values)); + } + SettingsManager.Current.MDNSDiscovery_ExportFilePath = instance.FilePath; + SettingsManager.Current.MDNSDiscovery_ExportFileType = instance.FileType; + } + catch (Exception exception) + { + Log.Error("Cannot export mDNS services.", exception); + await DialogHelper.ShowMessageAsync(Application.Current.MainWindow, Strings.Error, + Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine + exception.Message, ChildWindowIcon.Error); + } + }, _ => + { + window.IsOpen = false; + ConfigurationManager.Current.IsChildWindowOpen = false; + }, [ExportFileType.Csv, ExportFileType.Xml, ExportFileType.Json], true, + SettingsManager.Current.MDNSDiscovery_ExportFileType, SettingsManager.Current.MDNSDiscovery_ExportFilePath); + ConfigurationManager.Current.IsChildWindowOpen = true; + return Application.Current.MainWindow.ShowChildWindowAsync(window); + } +} diff --git a/Source/NETworkManager/Views/MDNSDiscoveryView.xaml b/Source/NETworkManager/Views/MDNSDiscoveryView.xaml new file mode 100644 index 0000000000..5fcf9dac4a --- /dev/null +++ b/Source/NETworkManager/Views/MDNSDiscoveryView.xaml @@ -0,0 +1,228 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + - ApplicationDiscoveryProtocol, + + /// + /// mDNS / DNS-SD documentation page. + /// ApplicationMDNSDiscovery, /// diff --git a/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs b/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs index b6ac33d458..852c1002a3 100644 --- a/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs +++ b/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs @@ -352,6 +352,13 @@ public static class GlobalStaticConfiguration public static int DiscoveryProtocol_Duration => 60; public static ExportFileType DiscoveryProtocol_ExportFileType => ExportFileType.Csv; + // Application: mDNS / DNS-SD + public static string MDNSDiscovery_ServiceType => "*"; + public static int MDNSDiscovery_Duration => 10; + public static string MDNSDiscovery_InterfaceId => string.Empty; + public static ExportFileType MDNSDiscovery_ExportFileType => ExportFileType.Csv; + public static string MDNSDiscovery_ExportFilePath => string.Empty; + // Application: Wake on LAN public static int WakeOnLAN_Port => 9; @@ -389,13 +396,6 @@ public static class GlobalStaticConfiguration public static AutoRefreshTimeInfo Connections_AutoRefreshTime => AutoRefreshTime.GetDefaults.First(x => x.Value == 30 && x.TimeUnit == TimeUnit.Second); - // Application: mDNS / DNS-SD - public static string MDNSDiscovery_ServiceType => "*"; - public static int MDNSDiscovery_Duration => 10; - public static string MDNSDiscovery_InterfaceId => string.Empty; - public static ExportFileType MDNSDiscovery_ExportFileType => ExportFileType.Csv; - public static string MDNSDiscovery_ExportFilePath => string.Empty; - // Application: Listeners public static ExportFileType Listeners_ExportFileType => ExportFileType.Csv; diff --git a/Source/NETworkManager.Settings/SettingsInfo.cs b/Source/NETworkManager.Settings/SettingsInfo.cs index c072baa7dc..82e4836701 100644 --- a/Source/NETworkManager.Settings/SettingsInfo.cs +++ b/Source/NETworkManager.Settings/SettingsInfo.cs @@ -35,40 +35,6 @@ namespace NETworkManager.Settings; /// in applications that require user customization and state management across sessions. public class SettingsInfo : INotifyPropertyChanged { - #region mDNS / DNS-SD - - public string MDNSDiscovery_ServiceType - { - get; - set { if (value == field) return; field = value; OnPropertyChanged(); } - } = GlobalStaticConfiguration.MDNSDiscovery_ServiceType; - - public int MDNSDiscovery_Duration - { - get; - set { if (value == field) return; field = value; OnPropertyChanged(); } - } = GlobalStaticConfiguration.MDNSDiscovery_Duration; - - public string MDNSDiscovery_InterfaceId - { - get; - set { if (value == field) return; field = value; OnPropertyChanged(); } - } = GlobalStaticConfiguration.MDNSDiscovery_InterfaceId; - - public ExportFileType MDNSDiscovery_ExportFileType - { - get; - set { if (value == field) return; field = value; OnPropertyChanged(); } - } = GlobalStaticConfiguration.MDNSDiscovery_ExportFileType; - - public string MDNSDiscovery_ExportFilePath - { - get; - set { if (value == field) return; field = value; OnPropertyChanged(); } - } = GlobalStaticConfiguration.MDNSDiscovery_ExportFilePath; - - #endregion - /// /// Occurs when a property value changes. /// @@ -4053,6 +4019,75 @@ public ExportFileType DiscoveryProtocol_ExportFileType #endregion + #region mDNS / DNS-SD + + public string MDNSDiscovery_ServiceType + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = GlobalStaticConfiguration.MDNSDiscovery_ServiceType; + + public int MDNSDiscovery_Duration + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = GlobalStaticConfiguration.MDNSDiscovery_Duration; + + public string MDNSDiscovery_InterfaceId + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = GlobalStaticConfiguration.MDNSDiscovery_InterfaceId; + + public ExportFileType MDNSDiscovery_ExportFileType + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = GlobalStaticConfiguration.MDNSDiscovery_ExportFileType; + + public string MDNSDiscovery_ExportFilePath + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = GlobalStaticConfiguration.MDNSDiscovery_ExportFilePath; + + #endregion + #region WakeOnLAN public int WakeOnLAN_Port From 0c7869a0059c0942b926fe8a36281c10de1822a9 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:01:25 +0100 Subject: [PATCH 14/80] Update GlobalAssemblyInfo.cs --- Source/GlobalAssemblyInfo.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Source/GlobalAssemblyInfo.cs b/Source/GlobalAssemblyInfo.cs index f3fd20736a..e7d9456b4c 100644 --- a/Source/GlobalAssemblyInfo.cs +++ b/Source/GlobalAssemblyInfo.cs @@ -6,5 +6,5 @@ [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] -[assembly: AssemblyVersion("2026.11.14.0")] -[assembly: AssemblyFileVersion("2026.11.14.0")] +[assembly: AssemblyVersion("2026.11.18.0")] +[assembly: AssemblyFileVersion("2026.11.18.0")] From 114a6d5a95705beb3363ab58d12f181c1f4ab1d2 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:14:59 +0100 Subject: [PATCH 15/80] Feature: mDNS / DNS-SD - One result instead of tabs (M13) The result had a tab control (Services / Records), used nowhere else below the input of a tool. The services are the result; the raw DNS records (also of other owners and unknown types) are shown instead with the checkbox Raw DNS records in the header, like the raw JSON of the RDAP. Export follows what is shown. Columns like the other grids: MinWidth instead of a fixed width, the last column (IP addresses / value) fills the remaining width with a MinWidth. TTL moved before the IP addresses. Co-Authored-By: Claude Opus 5.5 --- .../Resources/Strings.Designer.cs | 15 +- .../Resources/Strings.resx | 7 +- .../ViewModels/MDNSDiscoveryViewModel.cs | 10 +- .../Views/MDNSDiscoveryView.xaml | 275 ++++++++++-------- Website/docs/application/mdns-discovery.md | 12 +- Website/docs/changelog/next-release.md | 2 +- 6 files changed, 163 insertions(+), 158 deletions(-) diff --git a/Source/NETworkManager.Localization/Resources/Strings.Designer.cs b/Source/NETworkManager.Localization/Resources/Strings.Designer.cs index 59241c85cb..7575d97f1a 100644 --- a/Source/NETworkManager.Localization/Resources/Strings.Designer.cs +++ b/Source/NETworkManager.Localization/Resources/Strings.Designer.cs @@ -8329,20 +8329,11 @@ public static string MDNSDiscovery_Priority { } /// - /// Looks up a localized string similar to Records. + /// Looks up a localized string similar to Raw DNS records. /// - public static string MDNSDiscovery_Records { + public static string MDNSDiscovery_RawRecords { get { - return ResourceManager.GetString("MDNSDiscovery_Records", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Services. - /// - public static string MDNSDiscovery_Services { - get { - return ResourceManager.GetString("MDNSDiscovery_Services", resourceCulture); + return ResourceManager.GetString("MDNSDiscovery_RawRecords", resourceCulture); } } diff --git a/Source/NETworkManager.Localization/Resources/Strings.resx b/Source/NETworkManager.Localization/Resources/Strings.resx index b36bdfdbda..b4a12b100c 100644 --- a/Source/NETworkManager.Localization/Resources/Strings.resx +++ b/Source/NETworkManager.Localization/Resources/Strings.resx @@ -5612,10 +5612,7 @@ Do you want to start the scan? {0} records - - Records - - - Services + + Raw DNS records \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/MDNSDiscoveryViewModel.cs b/Source/NETworkManager/ViewModels/MDNSDiscoveryViewModel.cs index bf4f39da60..6992cc1607 100644 --- a/Source/NETworkManager/ViewModels/MDNSDiscoveryViewModel.cs +++ b/Source/NETworkManager/ViewModels/MDNSDiscoveryViewModel.cs @@ -371,10 +371,10 @@ public IList SelectedRecords } = new ArrayList(); /// - /// Gets or sets the selected tab of the results (0 = services, 1 = records), exported by - /// . + /// Gets or sets a value indicating whether the raw DNS records are shown instead of the services (like the raw + /// JSON of the RDAP). exports what is shown. /// - public int SelectedResultTabIndex + public bool ShowRecords { get; set @@ -566,7 +566,7 @@ private void CopySelectedRecordsAction(object parameter) } /// - /// Gets the command to export the services or the records (the selected tab). + /// Gets the command to export the services or the records (what is shown, see ). /// public ICommand ExportCommand => new RelayCommand(_ => ExportAction()); @@ -749,7 +749,7 @@ private Task Export() { var window = Application.Current.Windows.OfType().FirstOrDefault(x => x.IsActive); - var exportRecords = SelectedResultTabIndex == 1; + var exportRecords = ShowRecords; var childWindow = new ExportChildWindow(); diff --git a/Source/NETworkManager/Views/MDNSDiscoveryView.xaml b/Source/NETworkManager/Views/MDNSDiscoveryView.xaml index 8fa0a850bc..cd1fc427ce 100644 --- a/Source/NETworkManager/Views/MDNSDiscoveryView.xaml +++ b/Source/NETworkManager/Views/MDNSDiscoveryView.xaml @@ -17,6 +17,7 @@ + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Website/docs/application/mdns-discovery.md b/Website/docs/application/mdns-discovery.md index 19e3392969..9e86453200 100644 --- a/Website/docs/application/mdns-discovery.md +++ b/Website/docs/application/mdns-discovery.md @@ -32,9 +32,9 @@ Discovery stops when its duration expires or when **Stop** is pressed. It contin ## Results -The header shows the time of the last browse (**Last scan at**) and the search box; below it the number of services and records. The results are updated live while browsing. +The header shows the time of the last browse (**Last scan at**), **Raw DNS records** and the search box; below it the number of services and records. The results are updated live while browsing. -The **Services** tab shows one row per advertised service instance. One printer can advertise several services and therefore appear in several rows. +The result shows one row per advertised service instance. One printer can advertise several services and therefore appear in several rows. | Column / detail | Meaning | | --- | --- | @@ -42,8 +42,8 @@ The **Services** tab shows one row per advertised service instance. One printer | Service type | Advertised type, including protocol and `.local.` domain | | Hostname | SRV target, such as `printer.local.` | | Port | Advertised service port, such as `631` for IPP | -| IP addresses | Resolved IPv4 and IPv6 addresses; link-local IPv6 addresses include the interface scope | | TTL | Remaining lifetime in seconds of the service instance's PTR record while browsing | +| IP addresses | Resolved IPv4 and IPv6 addresses; link-local IPv6 addresses include the interface scope | | SRV priority / weight | Values used for service selection | | TXT records | Advertised metadata, one TXT string per line; printer records often include model, capabilities and queue path | @@ -53,9 +53,9 @@ The search box filters by name, type, hostname, port, addresses and TXT contents The context menu provides **Copy...** with the name, service type, hostname, port, IP addresses, TXT records or all details of the selected services (one per line, in the order shown). **Export...** writes the filtered results (in their current sort order) or selected services to CSV, XML or JSON. It includes the interface, full service name, SRV fields, addresses, TXT records and remaining PTR TTL. Control characters and binary TXT values are escaped for display and export. -### Records +### Raw DNS records -The **Records** tab shows the cached DNS records received on the selected interface, including records for services outside the selected type. Records occupy individual lines with **Name**, **Type**, **Class**, **TTL** and **Value** columns. Each character string within a TXT record is shown as a separate row, with the same owner name and TTL. Repeated announcements update the rows instead of adding duplicates. +With **Raw DNS records** checked, the result shows the cached DNS records received on the selected interface instead of the services, including records for services outside the selected type. Records occupy individual lines with **Name**, **Type**, **Class**, **TTL** and **Value** columns. Each character string within a TXT record is shown as a separate row, with the same owner name and TTL. Repeated announcements update the rows instead of adding duplicates. - **PTR:** the service type or instance the record points to. - **SRV:** priority, weight, port and target hostname, in that order. @@ -63,7 +63,7 @@ The **Records** tab shows the cached DNS records received on the selected interf - **A / AAAA:** the host address, with an interface scope for link-local IPv6 addresses. - **Other types:** recognized DNS types keep their standard name (for example `NSEC`); unknown or private types use `TYPE` (for example `TYPE65400`). Their raw data is preserved as `\# ` (RFC 3597), including zero-length values. They can be searched, copied and exported like the decoded records. -Search filters the records by name, type and value. **Copy...** copies the name, value or the whole record (name, type, class, TTL and value) of the selected records, one per line. **Export...** exports records when this tab is selected (filtered or selected, in view order), including the cache-flush flag and interface. The TTL counts down during discovery; after stopping, records remain as a snapshot until the next browse. +Search filters the records by name, type and value. **Copy...** copies the name, value or the whole record (name, type, class, TTL and value) of the selected records, one per line. **Export...** exports the records while they are shown (filtered or selected, in view order), including the cache-flush flag and interface. The TTL counts down during discovery; after stopping, records remain as a snapshot until the next browse. ## Run command diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index fa65aec513..0b0b5bbd09 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -23,7 +23,7 @@ Release date: **xx.xx.2026** **mDNS / DNS-SD** -- Added a dedicated browser for services advertised on the local network, including printers, scanners, web servers and media devices. Select an interface and service type (or discover all types), inspect hostnames, ports, IPv4 / IPv6 addresses and TXT records, filter, copy and export the results. A separate **Records** tab shows individual DNS records, with each TXT entry on its own row; other and unknown record types are preserved as raw data. Includes the `mdns` / `dnssd` run commands. [#3719](https://github.com/BornToBeRoot/NETworkManager/pull/3719) +- Added a dedicated browser for services advertised on the local network, including printers, scanners, web servers and media devices. Select an interface and service type (or discover all types), inspect hostnames, ports, IPv4 / IPv6 addresses and TXT records, filter, copy and export the results. **Raw DNS records** shows the individual DNS records instead, with each TXT entry on its own row; other and unknown record types are preserved as raw data. Includes the `mdns` / `dnssd` run commands. [#3719](https://github.com/BornToBeRoot/NETworkManager/pull/3719) ## Improvements From 735017c9b7c2d9d92394d27c4358087b7436ac79 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:18:06 +0100 Subject: [PATCH 16/80] Feature: mDNS / DNS-SD - Logging of a browse (M14) Start (interface, service type, IPv4 / IPv6) and a summary at the end: packets processed, without records (queries of other hosts, invalid), dropped (busy link) and records not cached (cache full), to diagnose "no services found" from the log. Warning once when the cache is full. MaxRecords instead of the repeated 4096. Co-Authored-By: Claude Opus 5.5 --- .../Network/MDNSBrowser.cs | 15 ++++++++++- .../Network/MDNSServiceCache.cs | 26 +++++++++++++++++-- 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/Source/NETworkManager.Models/Network/MDNSBrowser.cs b/Source/NETworkManager.Models/Network/MDNSBrowser.cs index 8b339f47b9..dacd13c751 100644 --- a/Source/NETworkManager.Models/Network/MDNSBrowser.cs +++ b/Source/NETworkManager.Models/Network/MDNSBrowser.cs @@ -52,6 +52,7 @@ public static async Task BrowseAsync(MDNSInterfaceInfo networkInterface, string var sockets = new List<(Socket Socket, IPEndPoint Destination, int Index)>(); using var lifetime = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); var receivers = new List(); + long droppedPackets = 0; try { // One address family may fail (e.g. joining the IPv6 group on some adapters), the other is still used @@ -75,11 +76,16 @@ public static async Task BrowseAsync(MDNSInterfaceInfo networkInterface, string if (sockets.Count == 0) throw socketError ?? (Exception)new NetworkInformationException(); + // A very busy link: the oldest packets are dropped (counted for the log) var packets = Channel.CreateBounded(new BoundedChannelOptions(512) { SingleReader = true, FullMode = BoundedChannelFullMode.DropOldest - }); + }, _ => Interlocked.Increment(ref droppedPackets)); + + Log.Info($"mDNS browse on \"{networkInterface.Name}\" for {serviceType} started " + + $"({string.Join(", ", sockets.Select(x => x.Socket.AddressFamily == AddressFamily.InterNetworkV6 ? "IPv6" : "IPv4"))})."); + receivers.AddRange(sockets.Select(x => ReceiveAsync(x.Socket, x.Index, packets.Writer, lifetime.Token))); using var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(250)); var lastVersion = -1L; @@ -128,6 +134,13 @@ await socket.Socket.SendToAsync(data, SocketFlags.None, socket.Destination, canc await lifetime.CancelAsync().ConfigureAwait(false); foreach (var socket in sockets) socket.Socket.Dispose(); + + // Diagnostics for "no services found" on a network: were packets received at all, dropped or not cached? + if (sockets.Count > 0) + Log.Info($"mDNS browse on \"{networkInterface.Name}\" ended: {cache.Packets} packets processed " + + $"({cache.PacketsWithoutRecords} without records, e.g. queries), " + + $"{Interlocked.Read(ref droppedPackets)} dropped (busy), " + + $"{cache.RecordsNotCached} records not cached (cache full)."); try { await Task.WhenAll(receivers).ConfigureAwait(false); } catch (OperationCanceledException) { } catch (SocketException) when (lifetime.IsCancellationRequested) { } diff --git a/Source/NETworkManager.Models/Network/MDNSServiceCache.cs b/Source/NETworkManager.Models/Network/MDNSServiceCache.cs index 5c19d1e986..c7c1286825 100644 --- a/Source/NETworkManager.Models/Network/MDNSServiceCache.cs +++ b/Source/NETworkManager.Models/Network/MDNSServiceCache.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using log4net; using NETworkManager.Utilities; namespace NETworkManager.Models.Network; @@ -12,6 +13,11 @@ namespace NETworkManager.Models.Network; /// public sealed class MDNSServiceCache { + private static readonly ILog Log = LogManager.GetLogger(typeof(MDNSServiceCache)); + + /// Maximum number of cached records (busy or hostile networks). + public const int MaxRecords = 4096; + public static IReadOnlyList CommonServiceTypes { get; } = Array.AsReadOnly(new[] { "_ipp._tcp.local.", "_ipps._tcp.local.", "_printer._tcp.local.", "_pdl-datastream._tcp.local.", @@ -42,6 +48,15 @@ public MDNSServiceCache(string serviceType, string networkInterface) /// public long Version { get; private set; } + /// Number of processed packets (diagnostics, see ). + public long Packets { get; private set; } + + /// Number of packets without records: queries of other hosts, other opcodes or invalid packets. + public long PacketsWithoutRecords { get; private set; } + + /// Number of new records that were not cached because the cache was full (). + public long RecordsNotCached { get; private set; } + private static string Key(MDNSRecord record) => $"{record.Name.ToLowerInvariant()}|{record.Type}|{record.Identity}"; private static (string Name, ushort Type) RRset(MDNSRecord record) => (record.Name.ToLowerInvariant(), record.Type); @@ -91,6 +106,11 @@ public void ProcessResponse(byte[] message, DateTimeOffset now, long ipv6ScopeId // follow-up questions remain restricted to the requested local DNS-SD service types. var records = MDNSMessage.ReadResponse(message, ipv6ScopeId); + Packets++; + + if (records.Count == 0) + PacketsWithoutRecords++; + // A cache-flush RRset may span packets. Give older values one second's grace, and preserve values just // received in the same second (RFC 6762 section 10.2); a goodbye is also held for one second. foreach (var group in records.Where(x => x.CacheFlush && x.TTL > 0).GroupBy(RRset)) @@ -117,8 +137,10 @@ public void ProcessResponse(byte[] message, DateTimeOffset now, long ipv6ScopeId if (_records.TryGetValue(key, out var entry)) _records[key] = entry with { Expires = Min(entry.Expires, now.AddSeconds(1)) }; } - else if (_records.ContainsKey(key) || _records.Count < 4096) + else if (_records.ContainsKey(key) || _records.Count < MaxRecords) Set(key, new Entry(record, now, now.AddSeconds(record.TTL))); + else if (RecordsNotCached++ == 0) + Log.Warn($"mDNS cache on \"{_networkInterface}\" is full ({MaxRecords} records), new records are ignored until others expire."); } } @@ -238,6 +260,6 @@ public IReadOnlyList GetRecords(DateTimeOffset now) var ttl = (uint)Math.Max(0, Math.Ceiling((pair.Value.Expires - now).TotalSeconds)); return values.Select((value, index) => new MDNSRecordInfo($"{pair.Key}|{index}", record.Name, type, value, _networkInterface, record.CacheFlush, ttl)); - }).Take(4096).ToArray(); + }).Take(MaxRecords).ToArray(); } } From 1e3932b375d9128f250b6f69297a37ac963f9fd1 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:18:06 +0100 Subject: [PATCH 17/80] Fix: mDNS / DNS-SD - Query of a name with an escaped dot at the end (M15) CreateQuery removed all trailing dots (TrimEnd), also an escaped one of the last label (a\.. = label "a."): that label was never written and the question asked for a different name. A name ending with a backslash was not rejected either. Only an unescaped final dot is handled now, an unterminated label throws. Found by the new tests (M16). Co-Authored-By: Claude Opus 5.5 --- .../Network/MDNSMessage.cs | 20 +++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/Source/NETworkManager.Models/Network/MDNSMessage.cs b/Source/NETworkManager.Models/Network/MDNSMessage.cs index e1cd630a02..41784e5e3d 100644 --- a/Source/NETworkManager.Models/Network/MDNSMessage.cs +++ b/Source/NETworkManager.Models/Network/MDNSMessage.cs @@ -30,7 +30,9 @@ public static byte[] CreateQuery(string name, ushort type) var data = new List { 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 }; var label = new StringBuilder(); var escaped = false; - foreach (var character in name.TrimEnd('.') + ".") + // Fully qualified: add the final dot if it is missing. Not TrimEnd: an escaped dot at the end of the last label + // (e.g. a\.. = label "a.") is part of the label. + foreach (var character in EndsWithUnescapedDot(name) ? name : name + ".") { if (escaped) { @@ -52,12 +54,26 @@ public static byte[] CreateQuery(string name, ushort type) } } - if (escaped || data.Count > 266) + // Open escape or a last label without a dot (e.g. name\ becomes name\. with an escaped dot) + if (escaped || label.Length > 0 || data.Count > 266) throw new ArgumentException("Invalid DNS name.", nameof(name)); data.AddRange([0, (byte)(type >> 8), (byte)type, 0, 1]); return [.. data]; } + private static bool EndsWithUnescapedDot(string name) + { + if (!name.EndsWith('.')) + return false; + + // An even number of backslashes before the dot escape each other, not the dot + var backslashes = 0; + for (var i = name.Length - 2; i >= 0 && name[i] == '\\'; i--) + backslashes++; + + return backslashes % 2 == 0; + } + /// Rejects malformed/truncated packets atomically, including invalid compression and RDATA lengths. public static IReadOnlyList ReadResponse(byte[] data, long ipv6ScopeId = 0) { From 2c5d93b9c8d7f346ba842f77e5fd54a34cb7250d Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:18:06 +0100 Subject: [PATCH 18/80] Test: mDNS / DNS-SD - Parser, cache, questions and rows (M16) - CreateQuery: empty / too long labels and names, open escapes, escaped final dot - ReadResponse: queries / other opcodes / errors ignored, other classes, wrong address length, scope of link-local IPv6 addresses - Cache: counters, full cache (new records ignored, cached ones refreshed), question backoff to 60 s, refresh before expiry, no address questions outside .local, stable record order, version on cache-flush change, unescaped service names - Rows: UpdateFrom raises only the changed properties Co-Authored-By: Claude Opus 5.5 --- .../Network/MDNSDiscoveryTests.cs | 204 ++++++++++++++++++ 1 file changed, 204 insertions(+) diff --git a/Source/NETworkManager.Tests/Network/MDNSDiscoveryTests.cs b/Source/NETworkManager.Tests/Network/MDNSDiscoveryTests.cs index 4e1f077df1..2ec99bd5ca 100644 --- a/Source/NETworkManager.Tests/Network/MDNSDiscoveryTests.cs +++ b/Source/NETworkManager.Tests/Network/MDNSDiscoveryTests.cs @@ -339,4 +339,208 @@ public void RecordsViewAlsoPreservesReverseOwnersWithoutStartingUnrelatedQueries Assert.Equal("20.1.168.192.in-addr.arpa.", Assert.Single(cache.GetRecords(Now)).Name); Assert.Equal(new[] { (Type, (ushort)12) }, cache.GetQuestions(Now)); } + + // Query building + + [Theory] + [InlineData("")] + [InlineData("a..local.")] + [InlineData("trailing\\")] + public void CreateQueryRejectsEmptyLabelsAndOpenEscapes(string name) => + Assert.Throws(() => MDNSMessage.CreateQuery(name, 12)); + + [Fact] + public void CreateQueryKeepsAnEscapedDotAtTheEndOfTheLastLabel() + { + Assert.Equal(Labels("a."), MDNSMessage.CreateQuery("a\\..", 12)[12..^4]); + Assert.Equal(Labels("a."), MDNSMessage.CreateQuery("a\\.", 12)[12..^4]); + Assert.Equal(Labels("a\\"), MDNSMessage.CreateQuery("a\\\\.", 12)[12..^4]); + Assert.Equal(Labels("local"), MDNSMessage.CreateQuery("local", 12)[12..^4]); + } + + [Fact] + public void CreateQueryRejectsLabelsLongerThan63Bytes() => + Assert.Throws(() => MDNSMessage.CreateQuery(new string('a', 64) + ".local.", 12)); + + [Fact] + public void CreateQueryRejectsNamesLongerThan255Bytes() => + Assert.Throws(() => + MDNSMessage.CreateQuery(string.Join('.', Enumerable.Repeat(new string('a', 63), 5)) + ".", 12)); + + // Response parsing + + [Fact] + public void IgnoresQueriesAndOtherOpcodesAndErrors() + { + var packet = Packet(Ptr()); + packet[2] = 0x00; // query (QR = 0) + Assert.Empty(MDNSMessage.ReadResponse(packet)); + packet = Packet(Ptr()); + packet[2] = 0x84 | 0x08; // opcode 1 + Assert.Empty(MDNSMessage.ReadResponse(packet)); + packet = Packet(Ptr()); + packet[3] = 0x03; // rcode 3 (NXDOMAIN) + Assert.Empty(MDNSMessage.ReadResponse(packet)); + } + + [Fact] + public void IgnoresRecordsOfOtherClassesButKeepsTheRestOfThePacket() + { + var packet = Packet(Address(), Ptr()); + // Class of the first record (A of printer.local.): CH (3) instead of IN + var classOffset = 12 + Name(Host).Length + 2; + packet[classOffset + 1] = 3; + var record = Assert.Single(MDNSMessage.ReadResponse(packet)); + Assert.Equal(MDNSMessage.PTR, record.Type); + } + + [Fact] + public void AddressRecordsWithAWrongLengthArePreservedAsRawData() + { + var record = Assert.Single(MDNSMessage.ReadResponse(Packet(new Record(Host, 1, [192, 168, 1])))); + Assert.Null(record.Address); + Assert.Equal(new byte[] { 192, 168, 1 }, record.RawData); + } + + [Fact] + public void LinkLocalIPv6AddressesGetTheScopeOfTheInterface() + { + var records = MDNSMessage.ReadResponse(Packet(Address("fe80::1"), Address("2001:db8::1")), 12); + Assert.Equal(12, records[0].Address.ScopeId); + Assert.Equal(0, records[1].Address.ScopeId); + } + + // Cache + + [Fact] + public void CountsPacketsAndPacketsWithoutRecords() + { + var cache = new MDNSServiceCache(Type, "Ethernet"); + cache.ProcessResponse(Packet(Ptr()), Now); + cache.ProcessResponse(MDNSMessage.CreateQuery(Type, 12), Now); // query of another host + cache.ProcessResponse([1, 2, 3], Now); // invalid + Assert.Equal(3, cache.Packets); + Assert.Equal(2, cache.PacketsWithoutRecords); + } + + [Fact] + public void FullCacheIgnoresNewRecordsButRefreshesCachedOnes() + { + var cache = new MDNSServiceCache(Type, "Ethernet"); + cache.ProcessResponse(Packet(Ptr(2)), Now); + + // Fill the cache with other records (A records of different hosts) + var hosts = Enumerable.Range(0, MDNSServiceCache.MaxRecords - 1) + .Select(i => new Record($"host{i}.local.", 1, [10, 0, (byte)(i >> 8), (byte)i])).ToArray(); + foreach (var chunk in hosts.Chunk(500)) + cache.ProcessResponse(Packet(chunk), Now); + + Assert.Equal(0, cache.RecordsNotCached); + cache.ProcessResponse(Packet(Address("192.168.1.99")), Now); + Assert.Equal(1, cache.RecordsNotCached); + Assert.DoesNotContain(cache.GetRecords(Now), x => x.Value == "192.168.1.99"); + + // The cached PTR (TTL 2) is still refreshed by a new announcement + cache.ProcessResponse(Packet(Ptr(2)), Now.AddSeconds(1.5)); + Assert.Single(cache.GetServices(Now.AddSeconds(3))); + } + + [Fact] + public void QuestionsBackOffExponentiallyToSixtySeconds() + { + var cache = new MDNSServiceCache(Type, "Ethernet"); + var times = new List(); + for (var second = 0.0; second <= 200; second += 0.25) + if (cache.GetQuestions(Now.AddSeconds(second)).Count > 0) + times.Add(second); + + // 0, 1, 3, 7, 15, 31, 63, then every 60 seconds + Assert.Equal(new[] { 0.0, 1, 3, 7, 15, 31, 63, 123, 183 }, times); + } + + [Fact] + public void QuestionsRefreshShortLivedRecordsBeforeTheyExpire() + { + var cache = new MDNSServiceCache(Type, "Ethernet"); + cache.GetQuestions(Now); + cache.ProcessResponse(Packet(Ptr(10)), Now); + cache.GetQuestions(Now.AddSeconds(1)); // asked again (backoff 2 s) + // Next question at 80 % of the remaining lifetime (9 s * 0.8), not after the backoff of the question + Assert.DoesNotContain((Type, (ushort)12), cache.GetQuestions(Now.AddSeconds(2))); + Assert.Contains((Type, (ushort)12), cache.GetQuestions(Now.AddSeconds(3))); + } + + [Fact] + public void NoAddressQuestionsForHostsOutsideTheLocalDomain() + { + var cache = new MDNSServiceCache(Type, "Ethernet"); + cache.ProcessResponse(Packet(Ptr(), new Record(Instance, 33, [0, 0, 0, 0, 0, 80, .. Name("printer.example.com.")])), Now); + var questions = cache.GetQuestions(Now); + Assert.DoesNotContain(questions, x => x.Name == "printer.example.com."); + } + + [Fact] + public void RecordsAreReturnedInAStableOrder() + { + var cache = new MDNSServiceCache(Type, "Ethernet"); + cache.ProcessResponse(Packet(Address("192.168.1.3"), Ptr(), Address("192.168.1.1"), Srv()), Now); + cache.ProcessResponse(Packet(Address("192.168.1.2")), Now); + var first = cache.GetRecords(Now).Select(x => x.Id).ToArray(); + cache.ProcessResponse(Packet(Address("192.168.1.2")), Now.AddSeconds(1)); // announced again + Assert.Equal(first, cache.GetRecords(Now.AddSeconds(1)).Select(x => x.Id)); + Assert.Equal(first.Order(StringComparer.Ordinal), first); + } + + [Fact] + public void VersionChangesWhenTheCacheFlushFlagChanges() + { + var cache = new MDNSServiceCache(Type, "Ethernet"); + cache.ProcessResponse(Packet(Address()), Now); + var version = cache.Version; + cache.ProcessResponse(Packet(Address(flush: true)), Now.AddSeconds(1)); + Assert.NotEqual(version, cache.Version); + Assert.True(Assert.Single(cache.GetRecords(Now.AddSeconds(1))).CacheFlush); + } + + [Fact] + public void ServiceNamesWithEscapedDotsAndBackslashesAreUnescaped() + { + var cache = new MDNSServiceCache(Type, "Ethernet"); + cache.ProcessResponse(Packet(new Record(Type, 12, Labels("Büro.Printer\\One", "_ipp", "_tcp", "local"))), Now); + Assert.Equal("Büro.Printer\\One", Assert.Single(cache.GetServices(Now)).Name); + } + + // Rows + + [Fact] + public void ServiceUpdateRaisesOnlyTheChangedProperties() + { + var row = new MDNSServiceInfo(Instance, "Office Printer", Type, "Ethernet", Host, 631, 0, 0, "192.168.1.20", "a=1", 120); + var changed = new List(); + row.PropertyChanged += (_, e) => changed.Add(e.PropertyName); + + row.UpdateFrom(new MDNSServiceInfo(Instance, "Office Printer", Type, "Ethernet", Host, 631, 0, 0, "192.168.1.20", "a=1", 119)); + Assert.Equal(new[] { nameof(MDNSServiceInfo.TTL) }, changed); + + changed.Clear(); + row.UpdateFrom(new MDNSServiceInfo(Instance, "Office Printer", Type, "Ethernet", Host, 631, 0, 0, "192.168.1.20; fe80::1%7", "a=1", 119)); + Assert.Equal(new[] { nameof(MDNSServiceInfo.Addresses) }, changed); + Assert.Equal("192.168.1.20; fe80::1%7", row.Addresses); + + changed.Clear(); + row.UpdateFrom(new MDNSServiceInfo(Instance, "Office Printer", Type, "Ethernet", Host, 631, 0, 0, "192.168.1.20; fe80::1%7", "a=1", 119)); + Assert.Empty(changed); + } + + [Fact] + public void RecordUpdateRaisesTTLAndCacheFlush() + { + var row = new MDNSRecordInfo("id", Host, "A", "192.168.1.20", "Ethernet", false, 120); + var changed = new List(); + row.PropertyChanged += (_, e) => changed.Add(e.PropertyName); + row.UpdateFrom(new MDNSRecordInfo("id", Host, "A", "192.168.1.20", "Ethernet", true, 119)); + Assert.Equal(new[] { nameof(MDNSRecordInfo.TTL), nameof(MDNSRecordInfo.CacheFlush) }, changed); + Assert.True(row.CacheFlush); + Assert.Equal((uint)119, row.TTL); + } } From 54d10a875b787f1dae3be457d02f86c51db4bfc3 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:19:42 +0100 Subject: [PATCH 19/80] Feature: mDNS / DNS-SD - Pause a browse until stopped while hidden (M17) A browse with a duration is a scan that ends by itself and continues in the background (M8). A browse until stopped never ends: it is paused while another tool is shown, like the auto refresh of other tools, and resumed when the view is shown again. The browser continues with the cache of the browse, so the rows are kept, records that expired during the pause are removed and the due questions are sent right away. Co-Authored-By: Claude Opus 5.5 --- .../Network/MDNSBrowser.cs | 12 ++- .../Network/MDNSDiscoveryTests.cs | 15 ++++ .../ViewModels/MDNSDiscoveryViewModel.cs | 73 +++++++++++++++++-- Website/docs/application/mdns-discovery.md | 2 +- 4 files changed, 91 insertions(+), 11 deletions(-) diff --git a/Source/NETworkManager.Models/Network/MDNSBrowser.cs b/Source/NETworkManager.Models/Network/MDNSBrowser.cs index dacd13c751..6c3f44885c 100644 --- a/Source/NETworkManager.Models/Network/MDNSBrowser.cs +++ b/Source/NETworkManager.Models/Network/MDNSBrowser.cs @@ -44,11 +44,19 @@ public static IReadOnlyList GetInterfaces() => System.Net.Net /// Browses until cancellation. Reports detached snapshots from a worker thread, at most every 250 ms (when the /// cache changed) and once per second (TTL countdown). /// + /// Interface to browse on. + /// Service type (e.g. _ipp._tcp) or *. + /// Receives the snapshots (worker thread). + /// Ends the browse. + /// + /// Cache of an earlier browse of the same interface and service type, to continue it (e.g. after a pause): the + /// cached records are kept (if not expired meanwhile) and the due questions are sent right away. + /// public static async Task BrowseAsync(MDNSInterfaceInfo networkInterface, string serviceType, - Action update, CancellationToken cancellationToken) + Action update, CancellationToken cancellationToken, MDNSServiceCache cache = null) { ArgumentNullException.ThrowIfNull(networkInterface); - var cache = new MDNSServiceCache(serviceType, networkInterface.Name); + cache ??= new MDNSServiceCache(serviceType, networkInterface.Name); var sockets = new List<(Socket Socket, IPEndPoint Destination, int Index)>(); using var lifetime = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); var receivers = new List(); diff --git a/Source/NETworkManager.Tests/Network/MDNSDiscoveryTests.cs b/Source/NETworkManager.Tests/Network/MDNSDiscoveryTests.cs index 2ec99bd5ca..ad748b8e61 100644 --- a/Source/NETworkManager.Tests/Network/MDNSDiscoveryTests.cs +++ b/Source/NETworkManager.Tests/Network/MDNSDiscoveryTests.cs @@ -479,6 +479,21 @@ public void NoAddressQuestionsForHostsOutsideTheLocalDomain() Assert.DoesNotContain(questions, x => x.Name == "printer.example.com."); } + [Fact] + public void ResumedCacheKeepsValidRecordsAndAsksDueQuestionsRightAway() + { + // Paused browse (view hidden) continued 5 minutes later with the same cache + var cache = new MDNSServiceCache(Type, "Ethernet"); + cache.GetQuestions(Now); + cache.ProcessResponse(Packet(Ptr(4500), Srv(), Address()), Now); // SRV / A: TTL 120 + cache.GetQuestions(Now.AddSeconds(1)); + + var resumed = Now.AddMinutes(5); + var service = Assert.Single(cache.GetServices(resumed)); + Assert.Empty(service.Hostname); // SRV expired during the pause + Assert.Contains((Instance, (ushort)33), cache.GetQuestions(resumed)); + } + [Fact] public void RecordsAreReturnedInAStableOrder() { diff --git a/Source/NETworkManager/ViewModels/MDNSDiscoveryViewModel.cs b/Source/NETworkManager/ViewModels/MDNSDiscoveryViewModel.cs index 6992cc1607..0bff5ed984 100644 --- a/Source/NETworkManager/ViewModels/MDNSDiscoveryViewModel.cs +++ b/Source/NETworkManager/ViewModels/MDNSDiscoveryViewModel.cs @@ -44,6 +44,13 @@ public sealed class MDNSDiscoveryViewModel : ViewModelBase private CancellationTokenSource _cancellationTokenSource; private Task _browseTask = Task.CompletedTask; + // A browse until stopped is paused while the view is hidden (like the auto refresh of other tools) and resumed + // with the same interface, service type and cache when it is shown again + private MDNSInterfaceInfo _browseInterface; + private string _browseServiceType; + private MDNSServiceCache _browseCache; + private bool _isPaused; + // The browser reports detached snapshots from a worker thread; the latest one is merged into the rows by the // flush timer (like the results buffer of the scanners), so the dispatcher isn't called per snapshot. private MDNSDiscoverySnapshot _pendingSnapshot; @@ -629,12 +636,15 @@ private async Task Browse() if (IsRunning || SelectedInterface == null || !MDNSServiceType.TryNormalize(ServiceType, out var serviceType)) return; - var networkInterface = SelectedInterface; - var duration = SelectedDuration; + _isPaused = false; + + _browseInterface = SelectedInterface; + _browseServiceType = serviceType; + _browseCache = new MDNSServiceCache(serviceType, _browseInterface.Name); SettingsManager.Current.MDNSDiscovery_ServiceType = ServiceType; - SettingsManager.Current.MDNSDiscovery_Duration = duration; - SettingsManager.Current.MDNSDiscovery_InterfaceId = networkInterface.Id; + SettingsManager.Current.MDNSDiscovery_Duration = SelectedDuration; + SettingsManager.Current.MDNSDiscovery_InterfaceId = _browseInterface.Id; IsStatusMessageDisplayed = false; StatusMessage = string.Empty; @@ -646,6 +656,20 @@ private async Task Browse() _recordRows.Clear(); Interlocked.Exchange(ref _pendingSnapshot, null); + await Run(SelectedDuration); + } + + /// + /// Runs the browse of / with + /// (new browse or resumed after a pause, the rows are kept). + /// + /// Duration in seconds, 0 = until stopped. + private async Task Run(int duration) + { + var networkInterface = _browseInterface; + var serviceType = _browseServiceType; + var cache = _browseCache; + _cancellationTokenSource?.Dispose(); _cancellationTokenSource = new CancellationTokenSource(); @@ -669,11 +693,11 @@ private async Task Browse() try { await Task.Run(() => MDNSBrowser.BrowseAsync(networkInterface, serviceType, - snapshot => Interlocked.Exchange(ref _pendingSnapshot, snapshot), linked.Token)); + snapshot => Interlocked.Exchange(ref _pendingSnapshot, snapshot), linked.Token, cache)); } catch (OperationCanceledException) when (linked.IsCancellationRequested) { - // Stopped before the duration expired (until stopped: the normal end) + // Stopped before the duration expired (until stopped / paused: the normal end) if (_cancellationTokenSource.IsCancellationRequested && duration > 0) SetStatusMessage(Strings.CanceledByUserMessage, StatusLevel.None); } @@ -730,19 +754,52 @@ public async Task OpenAsync(ApplicationRequest request) } /// - /// Called when the view is shown: reloads the interfaces (not while browsing). + /// Called when the view is shown: resumes a paused browse (see ), otherwise reloads + /// the interfaces (not while browsing). /// public void OnViewVisible() { + if (_isPaused) + { + _ = Resume(); + + return; + } + if (!IsRunning) LoadInterfaces(); } /// - /// Called when the view is hidden. The browse continues in the background, like the scanners. + /// Called when the view is hidden. A browse with a duration continues in the background like the scanners, a + /// browse until stopped is paused (like the auto refresh of other tools) and resumed when the view is shown. /// public void OnViewHide() { + if (!IsRunning || BrowseDuration != 0) + return; + + _isPaused = true; + + Stop(); + } + + /// + /// Resumes a paused browse with the same cache: the rows are kept, expired records are removed and the due + /// questions are sent right away. + /// + private async Task Resume() + { + // The pause may still be ending (shown again right away) + await _browseTask; + + // Not if a new browse was started meanwhile (e.g. run command) + if (!_isPaused || IsRunning) + return; + + _isPaused = false; + + await (_browseTask = Run(0)); } private Task Export() diff --git a/Website/docs/application/mdns-discovery.md b/Website/docs/application/mdns-discovery.md index 9e86453200..957b099168 100644 --- a/Website/docs/application/mdns-discovery.md +++ b/Website/docs/application/mdns-discovery.md @@ -28,7 +28,7 @@ Discovery uses IPv4 (`224.0.0.251`) and IPv6 (`ff02::fb`) multicast on UDP port With `*`, the tool queries `_services._dns-sd._udp.local.` and browses the returned types. It also probes common printer, scanner, web, file sharing and media types because some devices do not answer service type enumeration. A specific type can be entered even when it is not in the suggestions. -Discovery stops when its duration expires or when **Stop** is pressed. It continues in the background when you switch to another tool. The last results remain available for inspection and export. Starting again clears the previous results. The interface, service type and duration are remembered. +Discovery stops when its duration expires or when **Stop** is pressed. With a duration it continues in the background when you switch to another tool. With **Until stopped** it is paused while another tool is shown and continues when you return; the results are kept (records that expired meanwhile are removed). The last results remain available for inspection and export. Starting again clears the previous results. The interface, service type and duration are remembered. ## Results From 656ed159f91abcf740472ffb5d787ec2f31fd962 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:20:14 +0100 Subject: [PATCH 20/80] Update GlobalAssemblyInfo.cs --- Source/GlobalAssemblyInfo.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Source/GlobalAssemblyInfo.cs b/Source/GlobalAssemblyInfo.cs index e7d9456b4c..a035eabcd4 100644 --- a/Source/GlobalAssemblyInfo.cs +++ b/Source/GlobalAssemblyInfo.cs @@ -6,5 +6,5 @@ [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] -[assembly: AssemblyVersion("2026.11.18.0")] -[assembly: AssemblyFileVersion("2026.11.18.0")] +[assembly: AssemblyVersion("2026.11.19.0")] +[assembly: AssemblyFileVersion("2026.11.19.0")] From 1bd39e86a0d2a759cc33755e464137c7f9276d52 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:25:03 +0100 Subject: [PATCH 21/80] Feature: mDNS / DNS-SD - Reload animation of the interface refresh (M18) Like the other refresh buttons (e.g. WiFi adapters): the reload takes at least ApplicationUIRefreshInterval (in the background), the icon spins meanwhile and the reload / browse can't be started again. The initial load and the reload when the view is shown stay immediate (a run command can browse right after). A reload that finds an interface again removes the no-interface / failed message. Co-Authored-By: Claude Opus 5.5 --- .../ViewModels/MDNSDiscoveryViewModel.cs | 100 ++++++++++++++---- .../Views/MDNSDiscoveryView.xaml | 3 +- 2 files changed, 82 insertions(+), 21 deletions(-) diff --git a/Source/NETworkManager/ViewModels/MDNSDiscoveryViewModel.cs b/Source/NETworkManager/ViewModels/MDNSDiscoveryViewModel.cs index 0bff5ed984..a651754484 100644 --- a/Source/NETworkManager/ViewModels/MDNSDiscoveryViewModel.cs +++ b/Source/NETworkManager/ViewModels/MDNSDiscoveryViewModel.cs @@ -140,6 +140,22 @@ private set } } + /// + /// Gets a value indicating whether the interfaces are reloaded (refresh button, reload animation). + /// + public bool IsInterfacesLoading + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + /// /// Gets a value indicating whether a running browse is being stopped. /// @@ -486,7 +502,7 @@ private void LoadSettings() private bool Browse_CanExecute(object parameter) { - return !DialogHelper.IsAnyDialogOpen() && (IsRunning || SelectedInterface != null); + return !DialogHelper.IsAnyDialogOpen() && !IsInterfacesLoading && (IsRunning || SelectedInterface != null); } private void BrowseAction() @@ -500,11 +516,16 @@ private void BrowseAction() /// /// Gets the command to reload the network interfaces. /// - public ICommand RefreshInterfacesCommand => new RelayCommand(_ => LoadInterfaces(), RefreshInterfaces_CanExecute); + public ICommand RefreshInterfacesCommand => new RelayCommand(_ => RefreshInterfacesAction(), RefreshInterfaces_CanExecute); private bool RefreshInterfaces_CanExecute(object parameter) { - return !IsRunning && !DialogHelper.IsAnyDialogOpen(); + return !IsRunning && !IsInterfacesLoading && !DialogHelper.IsAnyDialogOpen(); + } + + private void RefreshInterfacesAction() + { + _ = RefreshInterfaces(); } /// @@ -587,36 +608,75 @@ private void ExportAction() #region Methods /// - /// Loads the network interfaces and selects the previous (or last used) one. + /// Loads the network interfaces right away (constructor, view shown: a run command may browse right after). /// private void LoadInterfaces() { - var id = SelectedInterface?.Id ?? SettingsManager.Current.MDNSDiscovery_InterfaceId; - try { - var interfaces = MDNSBrowser.GetInterfaces(); - - Interfaces.Clear(); + SetInterfaces(MDNSBrowser.GetInterfaces()); + } + catch (Exception ex) + { + LoadInterfacesFailed(ex); + } + } - foreach (var networkInterface in interfaces) - Interfaces.Add(networkInterface); + /// + /// Reloads the network interfaces with the refresh button: takes at least the refresh interval, so the reload + /// animation is visible and the reload can't be spammed (like the other refresh buttons). + /// + private async Task RefreshInterfaces() + { + IsInterfacesLoading = true; - SelectedInterface = Interfaces.FirstOrDefault(x => x.Id == id) ?? Interfaces.FirstOrDefault(); + try + { + var interfaces = await TaskHelper.WithMinimumDurationAsync(() => Task.Run(MDNSBrowser.GetInterfaces), + GlobalStaticConfiguration.ApplicationUIRefreshInterval); - if (SelectedInterface == null) - SetStatusMessage(Strings.MDNSDiscovery_NoInterface, StatusLevel.Warning); - else if (StatusMessage == Strings.MDNSDiscovery_NoInterface) - IsStatusMessageDisplayed = false; + SetInterfaces(interfaces); } catch (Exception ex) { - Log.Error("Cannot load the network interfaces with multicast support.", ex); - - SetStatusMessage(Strings.MDNSDiscovery_Failed + Environment.NewLine + ex.Message, StatusLevel.Error); + LoadInterfacesFailed(ex); + } + finally + { + IsInterfacesLoading = false; } } + /// + /// Shows the interfaces and selects the previous (or last used) one. + /// + private void SetInterfaces(IReadOnlyList interfaces) + { + var id = SelectedInterface?.Id ?? SettingsManager.Current.MDNSDiscovery_InterfaceId; + + Interfaces.Clear(); + + foreach (var networkInterface in interfaces) + Interfaces.Add(networkInterface); + + SelectedInterface = Interfaces.FirstOrDefault(x => x.Id == id) ?? Interfaces.FirstOrDefault(); + + Log.Debug($"Found {Interfaces.Count} network interfaces with multicast support, selected: \"{SelectedInterface?.Name}\"."); + + if (SelectedInterface == null) + SetStatusMessage(Strings.MDNSDiscovery_NoInterface, StatusLevel.Warning); + else if (StatusMessage is not null && + (StatusMessage == Strings.MDNSDiscovery_NoInterface || StatusMessage.StartsWith(Strings.MDNSDiscovery_Failed))) + IsStatusMessageDisplayed = false; + } + + private void LoadInterfacesFailed(Exception ex) + { + Log.Error("Cannot load the network interfaces with multicast support.", ex); + + SetStatusMessage(Strings.MDNSDiscovery_Failed + Environment.NewLine + ex.Message, StatusLevel.Error); + } + /// /// Shows a message below the input (replaces the previous one). /// @@ -766,7 +826,7 @@ public void OnViewVisible() return; } - if (!IsRunning) + if (!IsRunning && !IsInterfacesLoading) LoadInterfaces(); } diff --git a/Source/NETworkManager/Views/MDNSDiscoveryView.xaml b/Source/NETworkManager/Views/MDNSDiscoveryView.xaml index cd1fc427ce..fb7fe59c67 100644 --- a/Source/NETworkManager/Views/MDNSDiscoveryView.xaml +++ b/Source/NETworkManager/Views/MDNSDiscoveryView.xaml @@ -154,7 +154,8 @@ Style="{StaticResource CleanButton}" ToolTip="{x:Static localization:Strings.Refresh}" Margin="10,0,0,0"> - + From bcdab25389f029b8b2bde3b8e44df6286a037663 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:29:16 +0100 Subject: [PATCH 22/80] Feature: mDNS / DNS-SD - Browse several service types (M19) The cache and the browser took one service type (or *). They take a list now (e.g. the types of a service type profile, M20): a PTR question per type, services of all of them; * includes the others. Co-Authored-By: Claude Opus 5.5 --- .../Network/MDNSBrowser.cs | 8 ++-- .../Network/MDNSServiceCache.cs | 44 ++++++++++++++++--- .../Network/MDNSDiscoveryTests.cs | 25 +++++++++++ .../ViewModels/MDNSDiscoveryViewModel.cs | 12 ++--- 4 files changed, 72 insertions(+), 17 deletions(-) diff --git a/Source/NETworkManager.Models/Network/MDNSBrowser.cs b/Source/NETworkManager.Models/Network/MDNSBrowser.cs index 6c3f44885c..22bf413a05 100644 --- a/Source/NETworkManager.Models/Network/MDNSBrowser.cs +++ b/Source/NETworkManager.Models/Network/MDNSBrowser.cs @@ -45,18 +45,18 @@ public static IReadOnlyList GetInterfaces() => System.Net.Net /// cache changed) and once per second (TTL countdown). /// /// Interface to browse on. - /// Service type (e.g. _ipp._tcp) or *. + /// Service types (e.g. _ipp._tcp), * for all. /// Receives the snapshots (worker thread). /// Ends the browse. /// /// Cache of an earlier browse of the same interface and service type, to continue it (e.g. after a pause): the /// cached records are kept (if not expired meanwhile) and the due questions are sent right away. /// - public static async Task BrowseAsync(MDNSInterfaceInfo networkInterface, string serviceType, + public static async Task BrowseAsync(MDNSInterfaceInfo networkInterface, IReadOnlyCollection serviceTypes, Action update, CancellationToken cancellationToken, MDNSServiceCache cache = null) { ArgumentNullException.ThrowIfNull(networkInterface); - cache ??= new MDNSServiceCache(serviceType, networkInterface.Name); + cache ??= new MDNSServiceCache(serviceTypes, networkInterface.Name); var sockets = new List<(Socket Socket, IPEndPoint Destination, int Index)>(); using var lifetime = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); var receivers = new List(); @@ -91,7 +91,7 @@ public static async Task BrowseAsync(MDNSInterfaceInfo networkInterface, string FullMode = BoundedChannelFullMode.DropOldest }, _ => Interlocked.Increment(ref droppedPackets)); - Log.Info($"mDNS browse on \"{networkInterface.Name}\" for {serviceType} started " + + Log.Info($"mDNS browse on \"{networkInterface.Name}\" for {string.Join(", ", serviceTypes)} started " + $"({string.Join(", ", sockets.Select(x => x.Socket.AddressFamily == AddressFamily.InterNetworkV6 ? "IPv6" : "IPv4"))})."); receivers.AddRange(sockets.Select(x => ReceiveAsync(x.Socket, x.Index, packets.Writer, lifetime.Token))); diff --git a/Source/NETworkManager.Models/Network/MDNSServiceCache.cs b/Source/NETworkManager.Models/Network/MDNSServiceCache.cs index c7c1286825..651423e329 100644 --- a/Source/NETworkManager.Models/Network/MDNSServiceCache.cs +++ b/Source/NETworkManager.Models/Network/MDNSServiceCache.cs @@ -32,16 +32,45 @@ private sealed record Question(DateTimeOffset Next, int Interval); // Keys of the records per RRset (lowercase name, type), so a cache flush doesn't search the whole cache per packet private readonly Dictionary<(string Name, ushort Type), HashSet> _rrsets = new(); private readonly Dictionary<(string Name, ushort Type), Question> _questions = new(); - private readonly string _serviceType; + // Browsed service types (normalized), empty = all (*) + private readonly HashSet _serviceTypes = new(StringComparer.Ordinal); private readonly string _networkInterface; - public MDNSServiceCache(string serviceType, string networkInterface) + /// + /// Creates the cache of a browse of one service type (or * for all). + /// + public MDNSServiceCache(string serviceType, string networkInterface) : this([serviceType], networkInterface) + { + } + + /// + /// Creates the cache of a browse of several service types (e.g. of a service type profile). * browses + /// all advertised service types. + /// + public MDNSServiceCache(IEnumerable serviceTypes, string networkInterface) { - if (!MDNSServiceType.TryNormalize(serviceType, out _serviceType)) - throw new ArgumentException("Invalid service type.", nameof(serviceType)); + ArgumentNullException.ThrowIfNull(serviceTypes); + + foreach (var serviceType in serviceTypes) + { + if (!MDNSServiceType.TryNormalize(serviceType, out var normalized)) + throw new ArgumentException($"Invalid service type \"{serviceType}\".", nameof(serviceTypes)); + + _serviceTypes.Add(normalized); + } + + if (_serviceTypes.Count == 0) + throw new ArgumentException("No service type.", nameof(serviceTypes)); + + // * includes all others + if (_serviceTypes.Contains("*")) + _serviceTypes.Clear(); + _networkInterface = networkInterface; } + private bool BrowsesAll => _serviceTypes.Count == 0; + /// /// Incremented when a record is added, replaced by a different value or removed (not when a record is only /// announced again). The browser creates a new snapshot only if it changed (or for the TTL countdown). @@ -155,7 +184,7 @@ public void Expire(DateTimeOffset now) private IEnumerable Instances => _records.Values.Where(x => x.Record.Type == MDNSMessage.PTR && MDNSServiceType.TryNormalize(x.Record.Name, out var type) && type != "*" && - (_serviceType == "*" || type == _serviceType) && + (BrowsesAll || _serviceTypes.Contains(type)) && x.Record.Target.EndsWith("." + type, StringComparison.OrdinalIgnoreCase) && x.Record.Target.Length > type.Length + 1); @@ -165,7 +194,7 @@ public void Expire(DateTimeOffset now) Expire(now); var wanted = new Dictionary<(string Name, ushort Type), string>(); void Add(string name, ushort type) => wanted.TryAdd((name.ToLowerInvariant(), type), name); - if (_serviceType == "*") + if (BrowsesAll) { Add(MDNSServiceType.Enumeration, MDNSMessage.PTR); foreach (var type in CommonServiceTypes) @@ -176,7 +205,8 @@ public void Expire(DateTimeOffset now) Add(type, MDNSMessage.PTR); } else - Add(_serviceType, MDNSMessage.PTR); + foreach (var type in _serviceTypes) + Add(type, MDNSMessage.PTR); var instances = Instances.ToArray(); var instanceNames = instances.Select(x => x.Record.Target).ToHashSet(StringComparer.OrdinalIgnoreCase); diff --git a/Source/NETworkManager.Tests/Network/MDNSDiscoveryTests.cs b/Source/NETworkManager.Tests/Network/MDNSDiscoveryTests.cs index ad748b8e61..8eb1188aaa 100644 --- a/Source/NETworkManager.Tests/Network/MDNSDiscoveryTests.cs +++ b/Source/NETworkManager.Tests/Network/MDNSDiscoveryTests.cs @@ -185,6 +185,31 @@ public void EnumeratesUnknownTypesAndSeedsPrinters() Assert.NotEmpty(cache.GetQuestions(Now.AddSeconds(1))); } + [Fact] + public void BrowsesSeveralServiceTypes() + { + var cache = new MDNSServiceCache(["_ipp._tcp", "_http._tcp.local."], "Ethernet"); + Assert.Equal(new[] { ("_http._tcp.local.", (ushort)12), (Type, (ushort)12) }, + cache.GetQuestions(Now).Order()); + cache.ProcessResponse(Packet(Ptr(), new Record("_http._tcp.local.", 12, Name("Web._http._tcp.local.")), + new Record("_ssh._tcp.local.", 12, Name("Server._ssh._tcp.local."))), Now); + Assert.Equal(new[] { "_http._tcp.local.", Type }, cache.GetServices(Now).Select(x => x.ServiceType).Order()); + } + + [Fact] + public void AllServiceTypesIncludeTheOthers() + { + var cache = new MDNSServiceCache(["_ipp._tcp", "*"], "Ethernet"); + Assert.Contains((MDNSServiceType.Enumeration, (ushort)12), cache.GetQuestions(Now)); + } + + [Fact] + public void RejectsNoOrInvalidServiceTypes() + { + Assert.Throws(() => new MDNSServiceCache(Array.Empty(), "Ethernet")); + Assert.Throws(() => new MDNSServiceCache(["_ipp._tcp", "printers"], "Ethernet")); + } + [Fact] public void FiltersServicesByRequestedTypeAndHonorsTTL() { diff --git a/Source/NETworkManager/ViewModels/MDNSDiscoveryViewModel.cs b/Source/NETworkManager/ViewModels/MDNSDiscoveryViewModel.cs index a651754484..96c8b98bf8 100644 --- a/Source/NETworkManager/ViewModels/MDNSDiscoveryViewModel.cs +++ b/Source/NETworkManager/ViewModels/MDNSDiscoveryViewModel.cs @@ -47,7 +47,7 @@ public sealed class MDNSDiscoveryViewModel : ViewModelBase // A browse until stopped is paused while the view is hidden (like the auto refresh of other tools) and resumed // with the same interface, service type and cache when it is shown again private MDNSInterfaceInfo _browseInterface; - private string _browseServiceType; + private IReadOnlyList _browseServiceTypes; private MDNSServiceCache _browseCache; private bool _isPaused; @@ -699,8 +699,8 @@ private async Task Browse() _isPaused = false; _browseInterface = SelectedInterface; - _browseServiceType = serviceType; - _browseCache = new MDNSServiceCache(serviceType, _browseInterface.Name); + _browseServiceTypes = [serviceType]; + _browseCache = new MDNSServiceCache(_browseServiceTypes, _browseInterface.Name); SettingsManager.Current.MDNSDiscovery_ServiceType = ServiceType; SettingsManager.Current.MDNSDiscovery_Duration = SelectedDuration; @@ -720,14 +720,14 @@ private async Task Browse() } /// - /// Runs the browse of / with + /// Runs the browse of / with /// (new browse or resumed after a pause, the rows are kept). /// /// Duration in seconds, 0 = until stopped. private async Task Run(int duration) { var networkInterface = _browseInterface; - var serviceType = _browseServiceType; + var serviceTypes = _browseServiceTypes; var cache = _browseCache; _cancellationTokenSource?.Dispose(); @@ -752,7 +752,7 @@ private async Task Run(int duration) try { - await Task.Run(() => MDNSBrowser.BrowseAsync(networkInterface, serviceType, + await Task.Run(() => MDNSBrowser.BrowseAsync(networkInterface, serviceTypes, snapshot => Interlocked.Exchange(ref _pendingSnapshot, snapshot), linked.Token, cache)); } catch (OperationCanceledException) when (linked.IsCancellationRequested) From 3db85280026d7a423b02ce4dce6797b83b5762b1 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:33:53 +0100 Subject: [PATCH 23/80] Feature: mDNS / DNS-SD - Service type profiles (M20) Like the port profiles of the Port Scanner: named lists of service types (e.g. Printers = _ipp._tcp; _ipps._tcp; ...) in the new settings page mDNS / DNS-SD (add / edit / delete, F2, Del, double-click). The name can be entered in the service type input (M21), so it must be unique, without ";" and must not be * or a service type. Default profiles for new installations; missing ones are added on upgrade. Settings for the service type history (M21). Docs: settings section. Co-Authored-By: Claude Opus 5.5 --- .../DocumentationManager.cs | 1 + .../Resources/StaticStrings.Designer.cs | 40 ++- .../Resources/StaticStrings.resx | 6 + .../Resources/Strings.Designer.cs | 90 +++++++ .../Resources/Strings.resx | 30 +++ .../Network/MDNSServiceTypeProfile.cs | 135 +++++++++++ .../Network/MDNSServiceTypeProfileInfo.cs | 42 ++++ .../NETworkManager.Settings/SettingsInfo.cs | 32 +++ .../SettingsManager.cs | 8 + .../NETworkManager.Settings/SettingsName.cs | 1 + .../SettingsViewManager.cs | 2 + .../Network/MDNSServiceTypeProfileTests.cs | 89 +++++++ .../MDNSServiceTypeProfileNameValidator.cs | 20 ++ .../MDNSServiceTypesValidator.cs | 20 ++ Source/NETworkManager/MainWindow.xaml.cs | 1 + .../MDNSDiscoverySettingsViewModel.cs | 228 ++++++++++++++++++ .../MDNSServiceTypeProfileViewModel.cs | 120 +++++++++ .../ViewModels/SettingsViewModel.cs | 6 + .../Views/MDNSDiscoverySettingsView.xaml | 112 +++++++++ .../Views/MDNSDiscoverySettingsView.xaml.cs | 23 ++ .../MDNSServiceTypeProfileChildWindow.xaml | 100 ++++++++ .../MDNSServiceTypeProfileChildWindow.xaml.cs | 22 ++ Website/docs/application/mdns-discovery.md | 21 ++ 23 files changed, 1138 insertions(+), 11 deletions(-) create mode 100644 Source/NETworkManager.Models/Network/MDNSServiceTypeProfile.cs create mode 100644 Source/NETworkManager.Models/Network/MDNSServiceTypeProfileInfo.cs create mode 100644 Source/NETworkManager.Tests/Network/MDNSServiceTypeProfileTests.cs create mode 100644 Source/NETworkManager.Validators/MDNSServiceTypeProfileNameValidator.cs create mode 100644 Source/NETworkManager.Validators/MDNSServiceTypesValidator.cs create mode 100644 Source/NETworkManager/ViewModels/MDNSDiscoverySettingsViewModel.cs create mode 100644 Source/NETworkManager/ViewModels/MDNSServiceTypeProfileViewModel.cs create mode 100644 Source/NETworkManager/Views/MDNSDiscoverySettingsView.xaml create mode 100644 Source/NETworkManager/Views/MDNSDiscoverySettingsView.xaml.cs create mode 100644 Source/NETworkManager/Views/MDNSServiceTypeProfileChildWindow.xaml create mode 100644 Source/NETworkManager/Views/MDNSServiceTypeProfileChildWindow.xaml.cs diff --git a/Source/NETworkManager.Documentation/DocumentationManager.cs b/Source/NETworkManager.Documentation/DocumentationManager.cs index b3f2e39df9..e816644b2b 100644 --- a/Source/NETworkManager.Documentation/DocumentationManager.cs +++ b/Source/NETworkManager.Documentation/DocumentationManager.cs @@ -278,6 +278,7 @@ public static DocumentationIdentifier GetIdentifierBySettingsName(SettingsName n SettingsName.SNMP => GetIdentifierByApplicationName(ApplicationName.SNMP), SettingsName.SNTPLookup => GetIdentifierByApplicationName(ApplicationName.SNTPLookup), SettingsName.Firewall => GetIdentifierByApplicationName(ApplicationName.Firewall), + SettingsName.MDNSDiscovery => GetIdentifierByApplicationName(ApplicationName.MDNSDiscovery), SettingsName.WakeOnLAN => GetIdentifierByApplicationName(ApplicationName.WakeOnLAN), SettingsName.RDAP => GetIdentifierByApplicationName(ApplicationName.RDAP), SettingsName.BitCalculator => GetIdentifierByApplicationName(ApplicationName.BitCalculator), diff --git a/Source/NETworkManager.Localization/Resources/StaticStrings.Designer.cs b/Source/NETworkManager.Localization/Resources/StaticStrings.Designer.cs index 09fad6f34c..fb612d027d 100644 --- a/Source/NETworkManager.Localization/Resources/StaticStrings.Designer.cs +++ b/Source/NETworkManager.Localization/Resources/StaticStrings.Designer.cs @@ -78,6 +78,15 @@ public static string CSV { } } + /// + /// Looks up a localized string similar to C:\Data\profiles.csv. + /// + public static string CsvImportFileLocationDots { + get { + return ResourceManager.GetString("CsvImportFileLocationDots", resourceCulture); + } + } + /// /// Looks up a localized string similar to 636. /// @@ -133,7 +142,7 @@ public static string ExampleCredentialName { } /// - /// Looks up a localized string similar to https://$$HOSTNAME$$/. + /// Looks up a localized string similar to https://{{Hostname}}/. /// public static string ExampleCustomCommandVariableHostname { get { @@ -438,6 +447,24 @@ public static string ExampleMACAddressesOrVendor { } } + /// + /// Looks up a localized string similar to Printers. + /// + public static string ExampleMDNSServiceTypeProfileName { + get { + return ResourceManager.GetString("ExampleMDNSServiceTypeProfileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to _ipp._tcp; _ipps._tcp. + /// + public static string ExampleMDNSServiceTypes { + get { + return ResourceManager.GetString("ExampleMDNSServiceTypes", resourceCulture); + } + } + /// /// Looks up a localized string similar to S3cr3t_P4ssw0rd%. /// @@ -815,16 +842,7 @@ public static string PrivateKeyFileLocationDots { return ResourceManager.GetString("PrivateKeyFileLocationDots", resourceCulture); } } - - /// - /// Looks up a localized string similar to C:\Data\profiles.csv. - /// - public static string CsvImportFileLocationDots { - get { - return ResourceManager.GetString("CsvImportFileLocationDots", resourceCulture); - } - } - + /// /// Looks up a localized string similar to NETworkManager. /// diff --git a/Source/NETworkManager.Localization/Resources/StaticStrings.resx b/Source/NETworkManager.Localization/Resources/StaticStrings.resx index aa8d79b4a7..c0a1971f2d 100644 --- a/Source/NETworkManager.Localization/Resources/StaticStrings.resx +++ b/Source/NETworkManager.Localization/Resources/StaticStrings.resx @@ -381,4 +381,10 @@ a.iana-servers.net + + Printers + + + _ipp._tcp; _ipps._tcp + \ No newline at end of file diff --git a/Source/NETworkManager.Localization/Resources/Strings.Designer.cs b/Source/NETworkManager.Localization/Resources/Strings.Designer.cs index 7575d97f1a..d961ffc9a4 100644 --- a/Source/NETworkManager.Localization/Resources/Strings.Designer.cs +++ b/Source/NETworkManager.Localization/Resources/Strings.Designer.cs @@ -8265,6 +8265,15 @@ public static string MDNS { } } + /// + /// Looks up a localized string similar to Add service type profile. + /// + public static string MDNSDiscovery_AddServiceTypeProfile { + get { + return ResourceManager.GetString("MDNSDiscovery_AddServiceTypeProfile", resourceCulture); + } + } + /// /// Looks up a localized string similar to Browse. /// @@ -8274,6 +8283,51 @@ public static string MDNSDiscovery_Browse { } } + /// + /// Looks up a localized string similar to Delete service type profile. + /// + public static string MDNSDiscovery_DeleteServiceTypeProfile { + get { + return ResourceManager.GetString("MDNSDiscovery_DeleteServiceTypeProfile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The selected service type profile will be deleted permanently.. + /// + public static string MDNSDiscovery_DeleteServiceTypeProfileMessage { + get { + return ResourceManager.GetString("MDNSDiscovery_DeleteServiceTypeProfileMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Delete service type profiles. + /// + public static string MDNSDiscovery_DeleteServiceTypeProfiles { + get { + return ResourceManager.GetString("MDNSDiscovery_DeleteServiceTypeProfiles", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The selected service type profiles will be deleted permanently.. + /// + public static string MDNSDiscovery_DeleteServiceTypeProfilesMessage { + get { + return ResourceManager.GetString("MDNSDiscovery_DeleteServiceTypeProfilesMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Edit service type profile. + /// + public static string MDNSDiscovery_EditServiceTypeProfile { + get { + return ResourceManager.GetString("MDNSDiscovery_EditServiceTypeProfile", resourceCulture); + } + } + /// /// Looks up a localized string similar to No services found. Devices must advertise their services on the network of the selected interface; firewalls, VPNs and Wi-Fi client isolation can block discovery.. /// @@ -8283,6 +8337,15 @@ public static string MDNSDiscovery_Empty { } } + /// + /// Looks up a localized string similar to Enter service types such as _ipp._tcp, separated by ";".. + /// + public static string MDNSDiscovery_EnterValidServiceTypes { + get { + return ResourceManager.GetString("MDNSDiscovery_EnterValidServiceTypes", resourceCulture); + } + } + /// /// Looks up a localized string similar to Service discovery failed. Check the network interface and whether UDP port 5353 is available and allowed by the firewall.. /// @@ -8355,6 +8418,33 @@ public static string MDNSDiscovery_ServiceTypeHelp { } } + /// + /// Looks up a localized string similar to The name must not contain ";" and must not be "*" or a service type.. + /// + public static string MDNSDiscovery_ServiceTypeProfileNameInvalid { + get { + return ResourceManager.GetString("MDNSDiscovery_ServiceTypeProfileNameInvalid", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Service type profiles. + /// + public static string MDNSDiscovery_ServiceTypeProfiles { + get { + return ResourceManager.GetString("MDNSDiscovery_ServiceTypeProfiles", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Service types. + /// + public static string MDNSDiscovery_ServiceTypes { + get { + return ResourceManager.GetString("MDNSDiscovery_ServiceTypes", resourceCulture); + } + } + /// /// Looks up a localized string similar to TXT records. /// diff --git a/Source/NETworkManager.Localization/Resources/Strings.resx b/Source/NETworkManager.Localization/Resources/Strings.resx index b4a12b100c..42e3bac250 100644 --- a/Source/NETworkManager.Localization/Resources/Strings.resx +++ b/Source/NETworkManager.Localization/Resources/Strings.resx @@ -5615,4 +5615,34 @@ Do you want to start the scan? Raw DNS records + + Service type profiles + + + Add service type profile + + + Edit service type profile + + + Delete service type profile + + + Delete service type profiles + + + The selected service type profile will be deleted permanently. + + + The selected service type profiles will be deleted permanently. + + + Service types + + + The name must not contain ";" and must not be "*" or a service type. + + + Enter service types such as _ipp._tcp, separated by ";". + \ No newline at end of file diff --git a/Source/NETworkManager.Models/Network/MDNSServiceTypeProfile.cs b/Source/NETworkManager.Models/Network/MDNSServiceTypeProfile.cs new file mode 100644 index 0000000000..b47d33106d --- /dev/null +++ b/Source/NETworkManager.Models/Network/MDNSServiceTypeProfile.cs @@ -0,0 +1,135 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using NETworkManager.Utilities; + +namespace NETworkManager.Models.Network; + +/// +/// Service type profiles of the mDNS / DNS-SD tool and the service type input (e.g. "Printers; _http._tcp"), like +/// the port profiles of the Port Scanner (see ). +/// +public static class MDNSServiceTypeProfile +{ + /// + /// Separator of the entries of a service type input (e.g. "Printers; _http._tcp"). + /// + private const char EntrySeparator = NamedReferenceInput.EntrySeparator; + + /// + /// Finds a service type profile by its name (case-insensitive, leading / trailing spaces are ignored). + /// + /// Service type profiles. + /// Name of the service type profile. + /// Service type profile, or null if there is none with the name. + public static MDNSServiceTypeProfileInfo FindByName(IEnumerable profiles, string name) + { + return NamedReferenceInput.FindByName(profiles, name); + } + + /// + /// Checks if a name can be used for a service type profile: the name can be entered in the service type input, + /// so it must not contain the entry separator ";" and must not be "*" or a service type (e.g. "_ipp._tcp"). + /// + /// Name to check. + /// True if the name can be used. + public static bool IsValidName(string name) + { + return !string.IsNullOrWhiteSpace(name) && !name.Contains(EntrySeparator) && + !MDNSServiceType.TryNormalize(name, out _); + } + + /// + /// Parses the service types of a service type profile (e.g. "_ipp._tcp; _ipps._tcp"): service types separated + /// by ";", no "*" (all service types) and no names of other profiles. + /// + /// Service types of the profile. + /// Normalized service types (e.g. "_ipp._tcp.local."), null if the input is not valid. + /// True if every entry is a service type. + public static bool TryParseServiceTypes(string input, out IReadOnlyList serviceTypes) + { + serviceTypes = null; + + if (string.IsNullOrWhiteSpace(input)) + return false; + + List result = []; + + foreach (var entry in input.Split(EntrySeparator)) + { + if (!MDNSServiceType.TryNormalize(entry, out var serviceType) || serviceType == "*") + return false; + + if (!result.Contains(serviceType)) + result.Add(serviceType); + } + + serviceTypes = result; + + return true; + } + + /// + /// Resolves a service type input into the service types to browse. Every entry (separated by ";") is "*" (all + /// service types), a service type (e.g. "_http._tcp") or the name of a service type profile (e.g. "Printers"), + /// which is replaced by its service types - e.g. "Printers; _http._tcp" -> "_ipp._tcp.local.", ..., + /// "_http._tcp.local.". With "*" only "*" is returned (it includes the others). + /// + /// Service type input. + /// Service type profiles that can be used by their name. + /// Normalized service types without duplicates, null if the input is not valid. + /// True if every entry is "*", a service type or a service type profile. + public static bool TryResolve(string input, IEnumerable profiles, + out IReadOnlyList serviceTypes) + { + serviceTypes = null; + + if (string.IsNullOrWhiteSpace(input)) + return false; + + var profileList = profiles?.ToList() ?? []; + List result = []; + + foreach (var entry in input.Split(EntrySeparator)) + { + if (MDNSServiceType.TryNormalize(entry, out var serviceType)) + { + if (!result.Contains(serviceType)) + result.Add(serviceType); + + continue; + } + + var profile = FindByName(profileList, entry); + + // A profile edited in the settings file may contain invalid service types + if (profile == null || !TryParseServiceTypes(profile.ServiceTypes, out var profileServiceTypes)) + return false; + + foreach (var profileServiceType in profileServiceTypes.Where(x => !result.Contains(x))) + result.Add(profileServiceType); + } + + serviceTypes = result.Contains("*") ? ["*"] : result; + + return true; + } + + /// + /// Gets the default service type profiles (new installation, added on upgrade if missing). + /// + public static List GetDefaultList() + { + return + [ + new("Printers", "_ipp._tcp; _ipps._tcp; _printer._tcp; _pdl-datastream._tcp"), + new("Scanners", "_uscan._tcp; _uscans._tcp; _scanner._tcp"), + new("Web", "_http._tcp; _https._tcp"), + new("File sharing", "_smb._tcp; _afpovertcp._tcp; _nfs._tcp; _ftp._tcp; _webdav._tcp; _webdavs._tcp"), + new("Remote access", "_ssh._tcp; _sftp-ssh._tcp; _rfb._tcp; _rdp._tcp; _telnet._tcp"), + new("Media", "_airplay._tcp; _raop._tcp; _googlecast._tcp; _spotify-connect._tcp; _sonos._tcp"), + new("Smart home", "_hap._tcp; _hap._udp; _matter._tcp; _matterc._udp; _home-assistant._tcp; _hue._tcp"), + new("Apple devices", "_companion-link._tcp; _device-info._tcp; _airplay._tcp; _apple-mobdev2._tcp") + ]; + } +} diff --git a/Source/NETworkManager.Models/Network/MDNSServiceTypeProfileInfo.cs b/Source/NETworkManager.Models/Network/MDNSServiceTypeProfileInfo.cs new file mode 100644 index 0000000000..00ec3a19a1 --- /dev/null +++ b/Source/NETworkManager.Models/Network/MDNSServiceTypeProfileInfo.cs @@ -0,0 +1,42 @@ +using System; + +namespace NETworkManager.Models.Network; + +/// +/// Service type profile of the mDNS / DNS-SD tool: a name for several service types (e.g. "Printers" = +/// "_ipp._tcp; _ipps._tcp; ..."), which can be entered in the service type input (see +/// ). +/// +public class MDNSServiceTypeProfileInfo : INamedReference +{ + public MDNSServiceTypeProfileInfo() + { + } + + /// + /// Creates a new service type profile with a new . + /// + /// Name of the service type profile. + /// Service types, separated by ";". + public MDNSServiceTypeProfileInfo(string name, string serviceTypes) + { + Id = Guid.NewGuid(); + Name = name; + ServiceTypes = serviceTypes; + } + + /// + /// Internal ID of the service type profile, kept when it is edited. + /// + public Guid Id { get; set; } + + /// + /// Name of the service type profile, entered in the service type input. + /// + public string Name { get; set; } + + /// + /// Service types, separated by ";" (e.g. "_ipp._tcp; _ipps._tcp"). + /// + public string ServiceTypes { get; set; } +} diff --git a/Source/NETworkManager.Settings/SettingsInfo.cs b/Source/NETworkManager.Settings/SettingsInfo.cs index 82e4836701..39deb566b3 100644 --- a/Source/NETworkManager.Settings/SettingsInfo.cs +++ b/Source/NETworkManager.Settings/SettingsInfo.cs @@ -4034,6 +4034,34 @@ public string MDNSDiscovery_ServiceType } } = GlobalStaticConfiguration.MDNSDiscovery_ServiceType; + public ObservableCollection MDNSDiscovery_ServiceTypeHistory + { + get; + set + { + if (value == field) + return; + + UpdateCollectionChanged(field, value); + field = value; + OnPropertyChanged(); + } + } = []; + + public ObservableCollection MDNSDiscovery_ServiceTypeProfiles + { + get; + set + { + if (value == field) + return; + + UpdateCollectionChanged(field, value); + field = value; + OnPropertyChanged(); + } + } = []; + public int MDNSDiscovery_Duration { get; @@ -4817,6 +4845,10 @@ public SettingsInfo() // SNTP Lookup SNTPLookup_SNTPServers.CollectionChanged += CollectionChanged; + // mDNS / DNS-SD + MDNSDiscovery_ServiceTypeHistory.CollectionChanged += CollectionChanged; + MDNSDiscovery_ServiceTypeProfiles.CollectionChanged += CollectionChanged; + // Wake on LAN WakeOnLan_MACAddressHistory.CollectionChanged += CollectionChanged; WakeOnLan_BroadcastHistory.CollectionChanged += CollectionChanged; diff --git a/Source/NETworkManager.Settings/SettingsManager.cs b/Source/NETworkManager.Settings/SettingsManager.cs index 4e1933da95..41132870fa 100644 --- a/Source/NETworkManager.Settings/SettingsManager.cs +++ b/Source/NETworkManager.Settings/SettingsManager.cs @@ -940,6 +940,14 @@ private static void UpgradeToLatest(Version version) Current.General_ApplicationList.Count), defaultList.First(x => x.Name == ApplicationName.MDNSDiscovery)); } + + // mDNS / DNS-SD - Add the missing default service type profiles (like the port profiles of the Port Scanner) + foreach (var profile in MDNSServiceTypeProfile.GetDefaultList().Where(profile => + MDNSServiceTypeProfile.FindByName(Current.MDNSDiscovery_ServiceTypeProfiles, profile.Name) == null)) + { + Log.Info($"Add \"{profile.Name}\" to \"MDNSDiscovery_ServiceTypeProfiles\"..."); + Current.MDNSDiscovery_ServiceTypeProfiles.Add(profile); + } } #endregion } diff --git a/Source/NETworkManager.Settings/SettingsName.cs b/Source/NETworkManager.Settings/SettingsName.cs index 75fb9a3afd..d728ad79a4 100644 --- a/Source/NETworkManager.Settings/SettingsName.cs +++ b/Source/NETworkManager.Settings/SettingsName.cs @@ -29,6 +29,7 @@ public enum SettingsName SNMP, SNTPLookup, Firewall, + MDNSDiscovery, WakeOnLAN, RDAP, BitCalculator, diff --git a/Source/NETworkManager.Settings/SettingsViewManager.cs b/Source/NETworkManager.Settings/SettingsViewManager.cs index 03f7d87348..51460cdc88 100644 --- a/Source/NETworkManager.Settings/SettingsViewManager.cs +++ b/Source/NETworkManager.Settings/SettingsViewManager.cs @@ -78,6 +78,8 @@ public static class SettingsViewManager SettingsGroup.Application), new(SettingsName.Firewall, ApplicationManager.GetIcon(ApplicationName.Firewall), SettingsGroup.Application), + new(SettingsName.MDNSDiscovery, ApplicationManager.GetIcon(ApplicationName.MDNSDiscovery), + SettingsGroup.Application), new(SettingsName.WakeOnLAN, ApplicationManager.GetIcon(ApplicationName.WakeOnLAN), SettingsGroup.Application), new(SettingsName.RDAP, ApplicationManager.GetIcon(ApplicationName.RDAP), diff --git a/Source/NETworkManager.Tests/Network/MDNSServiceTypeProfileTests.cs b/Source/NETworkManager.Tests/Network/MDNSServiceTypeProfileTests.cs new file mode 100644 index 0000000000..f2ec7009d6 --- /dev/null +++ b/Source/NETworkManager.Tests/Network/MDNSServiceTypeProfileTests.cs @@ -0,0 +1,89 @@ +using System.Linq; +using NETworkManager.Models.Network; +using NETworkManager.Utilities; +using Xunit; + +namespace NETworkManager.Tests.Network; + +public class MDNSServiceTypeProfileTests +{ + private static readonly MDNSServiceTypeProfileInfo[] Profiles = + [ + new("Printers", "_ipp._tcp; _ipps._tcp"), + new("Web", "_http._tcp; _https._tcp"), + new("Broken", "_ipp._tcp; printers") + ]; + + [Theory] + [InlineData("Printers")] + [InlineData("My printers (office)")] + [InlineData("ipp")] + public void ValidNames(string name) => Assert.True(MDNSServiceTypeProfile.IsValidName(name)); + + [Theory] + [InlineData(null)] + [InlineData(" ")] + [InlineData("*")] + [InlineData("_ipp._tcp")] + [InlineData("A; B")] + public void InvalidNames(string name) => Assert.False(MDNSServiceTypeProfile.IsValidName(name)); + + [Fact] + public void ParsesTheServiceTypesOfAProfile() + { + Assert.True(MDNSServiceTypeProfile.TryParseServiceTypes(" _IPP._tcp; _ipps._tcp.local.;_ipp._tcp ", out var types)); + Assert.Equal(new[] { "_ipp._tcp.local.", "_ipps._tcp.local." }, types); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("*")] + [InlineData("_ipp._tcp; *")] + [InlineData("_ipp._tcp; Printers")] + [InlineData("_ipp._tcp;")] + public void RejectsInvalidServiceTypesOfAProfile(string input) => + Assert.False(MDNSServiceTypeProfile.TryParseServiceTypes(input, out _)); + + [Fact] + public void ResolvesProfilesAndServiceTypesWithoutDuplicates() + { + Assert.True(MDNSServiceTypeProfile.TryResolve("printers; _http._tcp; _ipp._tcp", Profiles, out var types)); + Assert.Equal(new[] { "_ipp._tcp.local.", "_ipps._tcp.local.", "_http._tcp.local." }, types); + } + + [Fact] + public void AllServiceTypesReplaceTheOthers() + { + Assert.True(MDNSServiceTypeProfile.TryResolve("Web; *", Profiles, out var types)); + Assert.Equal(new[] { "*" }, types); + } + + [Theory] + [InlineData("")] + [InlineData("Unknown")] + [InlineData("Printers; Unknown")] + [InlineData("Broken")] + [InlineData("_ipp._tcp;")] + public void RejectsUnknownProfilesAndInvalidEntries(string input) => + Assert.False(MDNSServiceTypeProfile.TryResolve(input, Profiles, out _)); + + [Fact] + public void DefaultProfilesAreValidAndUnique() + { + var profiles = MDNSServiceTypeProfile.GetDefaultList(); + + Assert.All(profiles, x => + { + Assert.True(MDNSServiceTypeProfile.IsValidName(x.Name), x.Name); + Assert.True(MDNSServiceTypeProfile.TryParseServiceTypes(x.ServiceTypes, out _), x.ServiceTypes); + }); + Assert.Equal(profiles.Count, profiles.Select(x => x.Name.ToLowerInvariant()).Distinct().Count()); + Assert.Equal(profiles.Count, profiles.Select(x => x.Id).Distinct().Count()); + } + + [Fact] + public void DefaultProfilesUseNoInvalidServiceNames() => + Assert.All(MDNSServiceTypeProfile.GetDefaultList().SelectMany(x => x.ServiceTypes.Split(';')), + x => Assert.True(MDNSServiceType.TryNormalize(x, out _), x)); +} diff --git a/Source/NETworkManager.Validators/MDNSServiceTypeProfileNameValidator.cs b/Source/NETworkManager.Validators/MDNSServiceTypeProfileNameValidator.cs new file mode 100644 index 0000000000..0266592355 --- /dev/null +++ b/Source/NETworkManager.Validators/MDNSServiceTypeProfileNameValidator.cs @@ -0,0 +1,20 @@ +using System.Globalization; +using System.Windows.Controls; +using NETworkManager.Localization.Resources; +using NETworkManager.Models.Network; + +namespace NETworkManager.Validators; + +/// +/// Validates the name of a service type profile of the mDNS / DNS-SD tool, see +/// (the name can be entered in the service type input). +/// +public class MDNSServiceTypeProfileNameValidator : ValidationRule +{ + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + return MDNSServiceTypeProfile.IsValidName(value as string) + ? ValidationResult.ValidResult + : new ValidationResult(false, Strings.MDNSDiscovery_ServiceTypeProfileNameInvalid); + } +} diff --git a/Source/NETworkManager.Validators/MDNSServiceTypesValidator.cs b/Source/NETworkManager.Validators/MDNSServiceTypesValidator.cs new file mode 100644 index 0000000000..1532c840c4 --- /dev/null +++ b/Source/NETworkManager.Validators/MDNSServiceTypesValidator.cs @@ -0,0 +1,20 @@ +using System.Globalization; +using System.Windows.Controls; +using NETworkManager.Localization.Resources; +using NETworkManager.Models.Network; + +namespace NETworkManager.Validators; + +/// +/// Validates the service types of a service type profile of the mDNS / DNS-SD tool: service types separated by +/// ";" (e.g. "_ipp._tcp; _ipps._tcp"), see . +/// +public class MDNSServiceTypesValidator : ValidationRule +{ + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + return MDNSServiceTypeProfile.TryParseServiceTypes(value as string, out _) + ? ValidationResult.ValidResult + : new ValidationResult(false, Strings.MDNSDiscovery_EnterValidServiceTypes); + } +} diff --git a/Source/NETworkManager/MainWindow.xaml.cs b/Source/NETworkManager/MainWindow.xaml.cs index bcb8a28374..ee65691ff6 100644 --- a/Source/NETworkManager/MainWindow.xaml.cs +++ b/Source/NETworkManager/MainWindow.xaml.cs @@ -499,6 +499,7 @@ await DialogHelper.ShowMessageAsync(Application.Current.MainWindow, Strings.Sett SettingsManager.Current.General_ApplicationList = [.. ApplicationManager.GetDefaultList()]; SettingsManager.Current.IPScanner_CustomCommands = [.. IPScannerCustomCommand.GetDefaultList()]; SettingsManager.Current.PortScanner_PortProfiles = [.. PortProfile.GetDefaultList()]; + SettingsManager.Current.MDNSDiscovery_ServiceTypeProfiles = [.. MDNSServiceTypeProfile.GetDefaultList()]; SettingsManager.Current.DNSLookup_DNSServers = [.. DNSServer.GetDefaultList()]; SettingsManager.Current.SNMP_OidProfiles = [.. SNMPOIDProfile.GetDefaultList()]; SettingsManager.Current.SNTPLookup_SNTPServers = [.. SNTPServer.GetDefaultList()]; diff --git a/Source/NETworkManager/ViewModels/MDNSDiscoverySettingsViewModel.cs b/Source/NETworkManager/ViewModels/MDNSDiscoverySettingsViewModel.cs new file mode 100644 index 0000000000..08a95948b9 --- /dev/null +++ b/Source/NETworkManager/ViewModels/MDNSDiscoverySettingsViewModel.cs @@ -0,0 +1,228 @@ +using MahApps.Metro.SimpleChildWindow; +using NETworkManager.Localization.Resources; +using NETworkManager.Models.Network; +using NETworkManager.Settings; +using NETworkManager.Utilities; +using NETworkManager.Views; +using System; +using System.Collections; +using System.ComponentModel; +using System.Linq; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Data; +using System.Windows.Input; + +namespace NETworkManager.ViewModels; + +/// +/// View model of the mDNS / DNS-SD settings: the service type profiles (like the port profiles of the Port +/// Scanner settings). +/// +public class MDNSDiscoverySettingsViewModel : ViewModelBase +{ + #region Variables + + /// + /// Gets the collection view of the service type profiles. + /// + public ICollectionView ServiceTypeProfiles { get; } + + /// + /// Gets or sets the selected service type profile. + /// + public MDNSServiceTypeProfileInfo SelectedServiceTypeProfile + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets or sets the selected service type profiles (several can be deleted at once). + /// + public IList SelectedServiceTypeProfiles + { + get; + set + { + if (Equals(value, field)) + return; + + field = value; + OnPropertyChanged(); + } + } = new ArrayList(); + + #endregion + + #region Constructor + + /// + /// Initializes a new instance of the class. + /// + public MDNSDiscoverySettingsViewModel() + { + // Own view (not the default view of the collection), sort and selection only apply to the settings + ServiceTypeProfiles = new CollectionViewSource + { Source = SettingsManager.Current.MDNSDiscovery_ServiceTypeProfiles }.View; + ServiceTypeProfiles.SortDescriptions.Add( + new SortDescription(nameof(MDNSServiceTypeProfileInfo.Name), ListSortDirection.Ascending)); + + SelectFirstServiceTypeProfile(); + } + + #endregion + + #region ICommand & Actions + + public ICommand AddServiceTypeProfileCommand => new RelayCommand(_ => AddServiceTypeProfileAction()); + + private void AddServiceTypeProfileAction() + { + _ = AddServiceTypeProfile(); + } + + public ICommand EditServiceTypeProfileCommand => + new RelayCommand(_ => EditServiceTypeProfileAction(), EditServiceTypeProfile_CanExecute); + + /// + /// Checks if exactly one service type profile is selected (e.g. F2 without a selection or with several). + /// + private bool EditServiceTypeProfile_CanExecute(object parameter) + { + return SelectedServiceTypeProfile != null && SelectedServiceTypeProfiles.Count == 1; + } + + private void EditServiceTypeProfileAction() + { + _ = EditServiceTypeProfile(); + } + + public ICommand DeleteServiceTypeProfileCommand => + new RelayCommand(_ => DeleteServiceTypeProfileAction(), DeleteServiceTypeProfile_CanExecute); + + /// + /// Checks if at least one service type profile is selected (e.g. Del without a selection). + /// + private bool DeleteServiceTypeProfile_CanExecute(object parameter) + { + return SelectedServiceTypeProfiles.Count > 0; + } + + private void DeleteServiceTypeProfileAction() + { + _ = DeleteServiceTypeProfile(); + } + + #endregion + + #region Methods + + private Task AddServiceTypeProfile() + { + var childWindow = new MDNSServiceTypeProfileChildWindow(); + + var childWindowViewModel = new MDNSServiceTypeProfileViewModel(instance => + { + childWindow.IsOpen = false; + ConfigurationManager.Current.IsChildWindowOpen = false; + + SettingsManager.Current.MDNSDiscovery_ServiceTypeProfiles.Add( + new MDNSServiceTypeProfileInfo(instance.Name.Trim(), instance.ServiceTypes.Trim())); + }, _ => + { + childWindow.IsOpen = false; + ConfigurationManager.Current.IsChildWindowOpen = false; + }); + + childWindow.Title = Strings.MDNSDiscovery_AddServiceTypeProfile; + + childWindow.DataContext = childWindowViewModel; + + ConfigurationManager.Current.IsChildWindowOpen = true; + + return Application.Current.MainWindow.ShowChildWindowAsync(childWindow); + } + + private Task EditServiceTypeProfile() + { + var childWindow = new MDNSServiceTypeProfileChildWindow(); + + var profile = SelectedServiceTypeProfile; + + var childWindowViewModel = new MDNSServiceTypeProfileViewModel(instance => + { + childWindow.IsOpen = false; + ConfigurationManager.Current.IsChildWindowOpen = false; + + // Same ID, kept when the profile is edited + var editedProfile = new MDNSServiceTypeProfileInfo(instance.Name.Trim(), instance.ServiceTypes.Trim()); + + if (profile.Id != Guid.Empty) + editedProfile.Id = profile.Id; + + SettingsManager.Current.MDNSDiscovery_ServiceTypeProfiles.Remove(profile); + SettingsManager.Current.MDNSDiscovery_ServiceTypeProfiles.Add(editedProfile); + }, _ => + { + childWindow.IsOpen = false; + ConfigurationManager.Current.IsChildWindowOpen = false; + }, profile); + + childWindow.Title = Strings.MDNSDiscovery_EditServiceTypeProfile; + + childWindow.DataContext = childWindowViewModel; + + ConfigurationManager.Current.IsChildWindowOpen = true; + + return Application.Current.MainWindow.ShowChildWindowAsync(childWindow); + } + + /// + /// Deletes the selected service type profiles (after a confirmation that lists them). + /// + private async Task DeleteServiceTypeProfile() + { + var profiles = SelectedServiceTypeProfiles.Cast().ToList(); + + var result = await DialogHelper.ShowConfirmationMessageAsync(Application.Current.MainWindow, + profiles.Count == 1 + ? Strings.MDNSDiscovery_DeleteServiceTypeProfile + : Strings.MDNSDiscovery_DeleteServiceTypeProfiles, + (profiles.Count == 1 + ? Strings.MDNSDiscovery_DeleteServiceTypeProfileMessage + : Strings.MDNSDiscovery_DeleteServiceTypeProfilesMessage) + + Environment.NewLine + Environment.NewLine + + DialogHelper.FormatItemList([.. profiles.Select(x => x.Name)]), + ChildWindowIcon.Info, + Strings.Delete); + + if (!result) + return; + + foreach (var profile in profiles) + SettingsManager.Current.MDNSDiscovery_ServiceTypeProfiles.Remove(profile); + + SelectFirstServiceTypeProfile(); + } + + /// + /// Selects the first service type profile (also in the list of selected profiles, which the grid applies). + /// + private void SelectFirstServiceTypeProfile() + { + SelectedServiceTypeProfile = ServiceTypeProfiles.Cast().FirstOrDefault(); + SelectedServiceTypeProfiles = SelectedServiceTypeProfile != null + ? new ArrayList { SelectedServiceTypeProfile } + : new ArrayList(); + } + + #endregion +} diff --git a/Source/NETworkManager/ViewModels/MDNSServiceTypeProfileViewModel.cs b/Source/NETworkManager/ViewModels/MDNSServiceTypeProfileViewModel.cs new file mode 100644 index 0000000000..200aacd000 --- /dev/null +++ b/Source/NETworkManager/ViewModels/MDNSServiceTypeProfileViewModel.cs @@ -0,0 +1,120 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Windows.Input; +using NETworkManager.Models.Network; +using NETworkManager.Settings; +using NETworkManager.Utilities; + +namespace NETworkManager.ViewModels; + +/// +/// View model of the dialog to add / edit a service type profile of the mDNS / DNS-SD tool. +/// +public class MDNSServiceTypeProfileViewModel : ViewModelBase +{ + private readonly MDNSServiceTypeProfileInfo _info; + private readonly bool _isLoading; + + /// + /// Initializes a new instance of the class. + /// + /// The action to execute when saving. + /// The action to execute when canceling. + /// The service type profile to edit, null to add one. + public MDNSServiceTypeProfileViewModel(Action saveCommand, + Action cancelHandler, MDNSServiceTypeProfileInfo info = null) + { + _isLoading = true; + + SaveCommand = new RelayCommand(_ => saveCommand(this)); + CancelCommand = new RelayCommand(_ => cancelHandler(this)); + + _info = info ?? new MDNSServiceTypeProfileInfo(); + + // Names of the other profiles - a name is used in the service type input, it must be unique + UsedNames = [.. SettingsManager.Current.MDNSDiscovery_ServiceTypeProfiles + .Where(x => !ReferenceEquals(x, info)).Select(x => x.Name)]; + + Name = _info.Name; + ServiceTypes = _info.ServiceTypes; + + _isLoading = false; + } + + /// + /// Gets the names of the other service type profiles (the name must be unique). + /// + public List UsedNames { get; } + + /// + /// Gets the command to save the profile. + /// + public ICommand SaveCommand { get; } + + /// + /// Gets the command to cancel the operation. + /// + public ICommand CancelCommand { get; } + + /// + /// Gets or sets the name of the profile. + /// + public string Name + { + get; + set + { + if (field == value) + return; + + field = value; + + if (!_isLoading) + Validate(); + + OnPropertyChanged(); + } + } + + /// + /// Gets or sets the service types of the profile, separated by ";". + /// + public string ServiceTypes + { + get; + set + { + if (field == value) + return; + + field = value; + + if (!_isLoading) + Validate(); + + OnPropertyChanged(); + } + } + + /// + /// Gets a value indicating whether the profile has changed (save is enabled). + /// + public bool InfoChanged + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + private void Validate() + { + InfoChanged = _info.Name != Name || _info.ServiceTypes != ServiceTypes; + } +} diff --git a/Source/NETworkManager/ViewModels/SettingsViewModel.cs b/Source/NETworkManager/ViewModels/SettingsViewModel.cs index ef7bf08b10..43aaa07a31 100644 --- a/Source/NETworkManager/ViewModels/SettingsViewModel.cs +++ b/Source/NETworkManager/ViewModels/SettingsViewModel.cs @@ -135,6 +135,7 @@ public SettingsViewInfo SelectedSettingsView private SNMPSettingsView _snmpSettingsView; private SNTPLookupSettingsView _sntpLookupSettingsView; private FirewallSettingsView _firewallSettingsView; + private MDNSDiscoverySettingsView _mdnsDiscoverySettingsView; private WakeOnLANSettingsView _wakeOnLANSettingsView; private RDAPSettingsView _rdapSettingsView; private BitCalculatorSettingsView _bitCalculatorSettingsView; @@ -344,6 +345,11 @@ private void ChangeSettingsContent(SettingsViewInfo settingsViewInfo) SettingsContent = _firewallSettingsView; break; + case SettingsName.MDNSDiscovery: + _mdnsDiscoverySettingsView ??= new MDNSDiscoverySettingsView(); + + SettingsContent = _mdnsDiscoverySettingsView; + break; case SettingsName.WakeOnLAN: _wakeOnLANSettingsView ??= new WakeOnLANSettingsView(); diff --git a/Source/NETworkManager/Views/MDNSDiscoverySettingsView.xaml b/Source/NETworkManager/Views/MDNSDiscoverySettingsView.xaml new file mode 100644 index 0000000000..7062b19e6e --- /dev/null +++ b/Source/NETworkManager/Views/MDNSDiscoverySettingsView.xaml @@ -0,0 +1,112 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/NETworkManager/Views/MDNSDiscoverySettingsView.xaml.cs b/Source/NETworkManager/Views/MDNSDiscoverySettingsView.xaml.cs new file mode 100644 index 0000000000..ee154796b6 --- /dev/null +++ b/Source/NETworkManager/Views/MDNSDiscoverySettingsView.xaml.cs @@ -0,0 +1,23 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using NETworkManager.ViewModels; + +namespace NETworkManager.Views; + +public partial class MDNSDiscoverySettingsView +{ + private readonly MDNSDiscoverySettingsViewModel _viewModel = new(); + + public MDNSDiscoverySettingsView() + { + InitializeComponent(); + DataContext = _viewModel; + } + + private void DataGridRow_MouseDoubleClick(object sender, MouseButtonEventArgs e) + { + if (_viewModel.EditServiceTypeProfileCommand.CanExecute(null)) + _viewModel.EditServiceTypeProfileCommand.Execute(null); + } +} \ No newline at end of file diff --git a/Source/NETworkManager/Views/MDNSServiceTypeProfileChildWindow.xaml b/Source/NETworkManager/Views/MDNSServiceTypeProfileChildWindow.xaml new file mode 100644 index 0000000000..1a4386f675 --- /dev/null +++ b/Source/NETworkManager/Views/MDNSServiceTypeProfileChildWindow.xaml @@ -0,0 +1,100 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -411,25 +442,99 @@ - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/NETworkManager/Views/MDNSDiscoveryView.xaml.cs b/Source/NETworkManager/Views/MDNSDiscoveryView.xaml.cs index 086bfc1ad8..1635eaf0b1 100644 --- a/Source/NETworkManager/Views/MDNSDiscoveryView.xaml.cs +++ b/Source/NETworkManager/Views/MDNSDiscoveryView.xaml.cs @@ -1,4 +1,6 @@ using System.Windows; +using System.Windows.Controls; +using System.Windows.Media; using NETworkManager.ViewModels; namespace NETworkManager.Views; @@ -16,4 +18,21 @@ public MDNSDiscoveryView() public void OnViewVisible() => _viewModel.OnViewVisible(); public void OnViewHide() => _viewModel.OnViewHide(); public void Open(ApplicationRequest request) => _ = _viewModel.OpenAsync(request); + + /// + /// Expands / collapses the details of the row of the button (like the IP Scanner). + /// + private void ExpandRowDetails_OnClick(object sender, RoutedEventArgs e) + { + for (var visual = sender as Visual; visual != null; visual = VisualTreeHelper.GetParent(visual) as Visual) + { + if (visual is not DataGridRow row) + continue; + + row.DetailsVisibility = + row.DetailsVisibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible; + + break; + } + } } diff --git a/Website/docs/application/mdns-discovery.md b/Website/docs/application/mdns-discovery.md index a35f5191fa..fdfc094c54 100644 --- a/Website/docs/application/mdns-discovery.md +++ b/Website/docs/application/mdns-discovery.md @@ -47,7 +47,7 @@ The result shows one row per advertised service instance. One printer can advert | SRV priority / weight | Values used for service selection | | TXT records | Advertised metadata, one TXT string per line; printer records often include model, capabilities and queue path | -Select a row to expand its full name, SRV priority/weight and TXT records. Empty hostname, port or address fields mean those records have not been resolved (or have expired). Details can arrive in separate responses and update while browsing. Goodbye messages and expired advertisements remove services while discovery is running. After discovery stops, TTL and other values remain at their last observed values. +Expand a row with the arrow in the first column (like the IP Scanner) to see the details of the service (full name, hostname, IP addresses, port, SRV priority / weight, TTL) and its TXT records, one per line. Empty hostname, port or address fields mean those records have not been resolved (or have expired). Details can arrive in separate responses and update while browsing. Goodbye messages and expired advertisements remove services while discovery is running. After discovery stops, TTL and other values remain at their last observed values. The search box filters by name, type, hostname, port, addresses and TXT contents. `Enter` in the search box applies the filter without starting discovery. Standard grid sorting and multi-selection are supported. From 332ca4277469bde82f87fa02f36d6b7dbbe45227 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:47:04 +0100 Subject: [PATCH 26/80] Feature: mDNS / DNS-SD - * as fixed entry of the service type list (M23) Since the list only shows the history and the profiles (M21), * (all service types) was only visible as default text. It is the first entry of the profiles group now, with a description, like the Windows DNS server of the DNS Lookup - not a stored profile, so it can't be edited or deleted. * is not added to the history (already in the list). Co-Authored-By: Claude Opus 5.5 --- .../Resources/Strings.Designer.cs | 9 +++++++++ .../NETworkManager.Localization/Resources/Strings.resx | 3 +++ Source/NETworkManager/InputSuggestions.cs | 8 +++++--- .../NETworkManager/ViewModels/MDNSDiscoveryViewModel.cs | 5 +++-- Website/docs/application/mdns-discovery.md | 2 +- 5 files changed, 21 insertions(+), 6 deletions(-) diff --git a/Source/NETworkManager.Localization/Resources/Strings.Designer.cs b/Source/NETworkManager.Localization/Resources/Strings.Designer.cs index 227070ef0d..9c1deb1564 100644 --- a/Source/NETworkManager.Localization/Resources/Strings.Designer.cs +++ b/Source/NETworkManager.Localization/Resources/Strings.Designer.cs @@ -8274,6 +8274,15 @@ public static string MDNSDiscovery_AddServiceTypeProfile { } } + /// + /// Looks up a localized string similar to All advertised service types. + /// + public static string MDNSDiscovery_AllServiceTypes { + get { + return ResourceManager.GetString("MDNSDiscovery_AllServiceTypes", resourceCulture); + } + } + /// /// Looks up a localized string similar to Browse. /// diff --git a/Source/NETworkManager.Localization/Resources/Strings.resx b/Source/NETworkManager.Localization/Resources/Strings.resx index cc9b240ebd..213ab91f4e 100644 --- a/Source/NETworkManager.Localization/Resources/Strings.resx +++ b/Source/NETworkManager.Localization/Resources/Strings.resx @@ -5645,4 +5645,7 @@ Do you want to start the scan? Enter service types such as _ipp._tcp, separated by ";". + + All advertised service types + \ No newline at end of file diff --git a/Source/NETworkManager/InputSuggestions.cs b/Source/NETworkManager/InputSuggestions.cs index a09e60926e..ed84dbe4e9 100644 --- a/Source/NETworkManager/InputSuggestions.cs +++ b/Source/NETworkManager/InputSuggestions.cs @@ -82,15 +82,17 @@ public static InputSuggestions ForPortScannerPorts() } /// - /// Creates the list for the service types of the mDNS / DNS-SD tool: the service type profiles (sorted by name, - /// with their service types) and the service type history. + /// Creates the list for the service types of the mDNS / DNS-SD tool: * (all service types, always first like the + /// Windows DNS server of DNS Lookup, not a stored profile), the service type profiles (sorted by name, with their + /// service types) and the service type history. /// public static InputSuggestions ForMDNSDiscoveryServiceTypes() { return new InputSuggestions(SettingsManager.Current.MDNSDiscovery_ServiceTypeProfiles, () => SettingsManager.Current.MDNSDiscovery_ServiceTypeProfiles .OrderBy(x => x.Name, StringComparer.OrdinalIgnoreCase) - .Select(x => (x.Name, x.ServiceTypes)), + .Select(x => (x.Name, x.ServiceTypes)) + .Prepend(("*", Strings.MDNSDiscovery_AllServiceTypes)), Strings.MDNSDiscovery_ServiceTypeProfiles, SettingsManager.Current.MDNSDiscovery_ServiceTypeHistory); } diff --git a/Source/NETworkManager/ViewModels/MDNSDiscoveryViewModel.cs b/Source/NETworkManager/ViewModels/MDNSDiscoveryViewModel.cs index ec81c37f0a..8bcab97ae7 100644 --- a/Source/NETworkManager/ViewModels/MDNSDiscoveryViewModel.cs +++ b/Source/NETworkManager/ViewModels/MDNSDiscoveryViewModel.cs @@ -724,8 +724,9 @@ private async Task Browse() _browseServiceTypes = serviceTypes; _browseCache = new MDNSServiceCache(_browseServiceTypes, _browseInterface.Name); - // A single profile name is already in the list, only other inputs are added to the history - if (MDNSServiceTypeProfile.FindByName(SettingsManager.Current.MDNSDiscovery_ServiceTypeProfiles, ServiceType) == null) + // * and a single profile name are already in the list, only other inputs are added to the history + if (ServiceType.Trim() != "*" && + MDNSServiceTypeProfile.FindByName(SettingsManager.Current.MDNSDiscovery_ServiceTypeProfiles, ServiceType) == null) ListHelper.Modify(SettingsManager.Current.MDNSDiscovery_ServiceTypeHistory, ServiceType.Trim(), SettingsManager.Current.General_HistoryListEntries); diff --git a/Website/docs/application/mdns-discovery.md b/Website/docs/application/mdns-discovery.md index fdfc094c54..c4e1bcc932 100644 --- a/Website/docs/application/mdns-discovery.md +++ b/Website/docs/application/mdns-discovery.md @@ -26,7 +26,7 @@ Discovery uses IPv4 (`224.0.0.251`) and IPv6 (`ff02::fb`) multicast on UDP port | Service type | Editable selection (history, service type profiles) | `*` | `Printers`, `_ipp._tcp`, `Printers; Scanners; _ssh._tcp` | | Duration (s) | Selection: `10`, `30`, `60`, `120`, `300`, **Until stopped** | `10` | `30` | -With `*`, the tool queries `_services._dns-sd._udp.local.` and browses the returned types. It also probes common printer, scanner, web, file sharing and media types because some devices do not answer service type enumeration. The list of the input shows the history (inputs other than a single profile) and the service type profiles with their service types. +With `*`, the tool queries `_services._dns-sd._udp.local.` and browses the returned types. It also probes common printer, scanner, web, file sharing and media types because some devices do not answer service type enumeration. The list of the input shows the history (inputs other than `*` or a single profile) and below it `*` (always first, like the Windows DNS server of the DNS Lookup) and the service type profiles with their service types. Discovery stops when its duration expires or when **Stop** is pressed. With a duration it continues in the background when you switch to another tool. With **Until stopped** it is paused while another tool is shown and continues when you return; the results are kept (records that expired meanwhile are removed). The last results remain available for inspection and export. Starting again clears the previous results. The interface, service type and duration are remembered. From f4f9e3e5531e1c9648f5421c9afea21b5ed38ef3 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:50:06 +0100 Subject: [PATCH 27/80] Fix: DNS Lookup - Last column of the DNS servers (settings) fills the grid The grid had no FillRemainingWidth: the DNS servers column stopped at its MinWidth. Co-Authored-By: Claude Opus 5.5 --- Source/NETworkManager/Views/DNSLookupSettingsView.xaml | 3 ++- Website/docs/changelog/next-release.md | 4 ++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/Source/NETworkManager/Views/DNSLookupSettingsView.xaml b/Source/NETworkManager/Views/DNSLookupSettingsView.xaml index e5ee4bf212..18b790693c 100644 --- a/Source/NETworkManager/Views/DNSLookupSettingsView.xaml +++ b/Source/NETworkManager/Views/DNSLookupSettingsView.xaml @@ -21,7 +21,8 @@ + SelectedItem="{Binding SelectedDNSServer}" Height="200" Margin="0,0,0,10" + wpfHelpers:DataGridHelper.FillRemainingWidth="True"> Date: Thu, 19 Nov 2026 00:50:06 +0100 Subject: [PATCH 28/80] Fix: SNTP Lookup - Last column of the SNTP servers (settings) fills the grid The grid had no FillRemainingWidth: the SNTP servers column stopped at its MinWidth. Co-Authored-By: Claude Opus 5.5 --- Source/NETworkManager/Views/SNTPLookupSettingsView.xaml | 3 ++- Website/docs/changelog/next-release.md | 4 ++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/Source/NETworkManager/Views/SNTPLookupSettingsView.xaml b/Source/NETworkManager/Views/SNTPLookupSettingsView.xaml index 4b75413311..f08320eed3 100644 --- a/Source/NETworkManager/Views/SNTPLookupSettingsView.xaml +++ b/Source/NETworkManager/Views/SNTPLookupSettingsView.xaml @@ -20,7 +20,8 @@ + SelectedItem="{Binding SelectedSNTPServer}" Height="200" Margin="0,0,0,10" + wpfHelpers:DataGridHelper.FillRemainingWidth="True"> diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index 345d2b8a8d..0cd0cc37a7 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -47,6 +47,10 @@ Release date: **xx.xx.2026** - Fixed the last column of the DNS servers (settings) not filling the remaining width. [#3719](https://github.com/BornToBeRoot/NETworkManager/pull/3719) +**SNTP Lookup** + +- Fixed the last column of the SNTP servers (settings) not filling the remaining width. [#3719](https://github.com/BornToBeRoot/NETworkManager/pull/3719) + **About** - Fixed the license of ControlzEx in the library list: it showed the license text and link of Dragablz. [#3717](https://github.com/BornToBeRoot/NETworkManager/pull/3717) From 1c4edc9302840626a207abf2d497add7cc1fac1d Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:50:31 +0100 Subject: [PATCH 29/80] Fix: Hosts File Editor - Last column (comment) fills the grid The grid had no FillRemainingWidth: the comment column stopped at its MinWidth. Co-Authored-By: Claude Opus 5.5 --- Source/NETworkManager/Views/HostsFileEditorView.xaml | 3 ++- Website/docs/changelog/next-release.md | 4 ++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/Source/NETworkManager/Views/HostsFileEditorView.xaml b/Source/NETworkManager/Views/HostsFileEditorView.xaml index 1c0c781527..2e43c441b0 100644 --- a/Source/NETworkManager/Views/HostsFileEditorView.xaml +++ b/Source/NETworkManager/Views/HostsFileEditorView.xaml @@ -92,7 +92,8 @@ Grid.Column="0" Grid.Row="2" ItemsSource="{Binding ResultsView}" SelectedItem="{Binding SelectedResult}" - SelectedItemsList="{Binding SelectedResults, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"> + SelectedItemsList="{Binding SelectedResults, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" + wpfHelpers:DataGridHelper.FillRemainingWidth="True"> Date: Thu, 19 Nov 2026 00:50:32 +0100 Subject: [PATCH 30/80] Fix: Settings > Profiles - Name of the profile files fills the grid The grid had no FillRemainingWidth. The name column fills the remaining width (IsFillColumn), not the last column (the encrypted checkbox). Co-Authored-By: Claude Opus 5.5 --- Source/NETworkManager/Views/SettingsProfilesView.xaml | 5 +++-- Website/docs/changelog/next-release.md | 4 ++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/Source/NETworkManager/Views/SettingsProfilesView.xaml b/Source/NETworkManager/Views/SettingsProfilesView.xaml index 4066fc354b..551c848282 100644 --- a/Source/NETworkManager/Views/SettingsProfilesView.xaml +++ b/Source/NETworkManager/Views/SettingsProfilesView.xaml @@ -189,7 +189,8 @@ + SelectedItem="{Binding SelectedProfileFile}" Height="200" Margin="0,0,0,10" + wpfHelpers:DataGridHelper.FillRemainingWidth="True"> @@ -266,7 +267,7 @@ + wpfHelpers:DataGridHelper.IsFillColumn="True" /> diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index 8132513525..c39dab5e9a 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -55,6 +55,10 @@ Release date: **xx.xx.2026** - Fixed the last column (comment) not filling the remaining width. [#3719](https://github.com/BornToBeRoot/NETworkManager/pull/3719) +**Settings** + +- Fixed the profile files (Settings > Profiles) not filling the width of the grid: the name column fills the remaining width. [#3719](https://github.com/BornToBeRoot/NETworkManager/pull/3719) + **About** - Fixed the license of ControlzEx in the library list: it showed the license text and link of Dragablz. [#3717](https://github.com/BornToBeRoot/NETworkManager/pull/3717) From 175cfbc9438545ccec66b37fbfe7cf38dad1f98c Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:50:55 +0100 Subject: [PATCH 31/80] Fix: Profiles - Name of the profile list fills the grid The grid had no FillRemainingWidth. The name column fills the remaining width (IsFillColumn), not the last column (the Whois checkbox). Co-Authored-By: Claude Opus 5.5 --- Source/NETworkManager/Views/ProfilesView.xaml | 5 +++-- Website/docs/changelog/next-release.md | 4 ++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/Source/NETworkManager/Views/ProfilesView.xaml b/Source/NETworkManager/Views/ProfilesView.xaml index 75069be61d..bbd7465878 100644 --- a/Source/NETworkManager/Views/ProfilesView.xaml +++ b/Source/NETworkManager/Views/ProfilesView.xaml @@ -345,7 +345,8 @@ VirtualizingPanel.IsVirtualizingWhenGrouping="True" VirtualizingPanel.IsContainerVirtualizable="True" VirtualizingPanel.VirtualizationMode="Recycling" - VirtualizingPanel.ScrollUnit="Pixel"> + VirtualizingPanel.ScrollUnit="Pixel" + wpfHelpers:DataGridHelper.FillRemainingWidth="True"> + MinWidth="150" wpfHelpers:DataGridHelper.IsFillColumn="True" /> diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index c39dab5e9a..1de8eae93f 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -59,6 +59,10 @@ Release date: **xx.xx.2026** - Fixed the profile files (Settings > Profiles) not filling the width of the grid: the name column fills the remaining width. [#3719](https://github.com/BornToBeRoot/NETworkManager/pull/3719) +**Profiles** + +- Fixed the profile list not filling the width of the grid: the name column fills the remaining width. [#3719](https://github.com/BornToBeRoot/NETworkManager/pull/3719) + **About** - Fixed the license of ControlzEx in the library list: it showed the license text and link of Dragablz. [#3717](https://github.com/BornToBeRoot/NETworkManager/pull/3717) From 0d818cb048cd90bb127f9f709fc9fc633ef70e8f Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:53:20 +0100 Subject: [PATCH 32/80] Feature: Run command - Service type profiles of mDNS / DNS-SD as suggestions (R1) Like the port profiles of the Port Scanner: * and the service type profiles (with their service types) are suggested while the target of mdns is typed, also after a ";" of a list (e.g. printers;sca), names with spaces in quotes. Tab completes the first one. The value suggestions of the second argument and of the target share their completion (GetValueSuggestions). Co-Authored-By: Claude Opus 5.5 --- Source/NETworkManager/RunCommandManager.cs | 10 +++++ Source/NETworkManager/RunCommandSuggestion.cs | 5 +++ .../ViewModels/RunCommandViewModel.cs | 42 +++++++++++++++++-- .../Views/RunCommandChildWindow.xaml | 6 +++ Website/docs/run-command.md | 3 +- 5 files changed, 61 insertions(+), 5 deletions(-) diff --git a/Source/NETworkManager/RunCommandManager.cs b/Source/NETworkManager/RunCommandManager.cs index bad55a577b..90d9da7d0d 100644 --- a/Source/NETworkManager/RunCommandManager.cs +++ b/Source/NETworkManager/RunCommandManager.cs @@ -121,6 +121,16 @@ public static IEnumerable GetPortProfiles() return SettingsManager.Current.PortScanner_PortProfiles; } + /// + /// Gets the service type profiles of the mDNS / DNS-SD tool (e.g. "Printers"), which can be used instead of + /// service types. + /// + /// Service type profiles. + public static IEnumerable GetMDNSServiceTypeProfiles() + { + return SettingsManager.Current.MDNSDiscovery_ServiceTypeProfiles; + } + /// /// Gets the translated name of the application (or settings) of a command. /// diff --git a/Source/NETworkManager/RunCommandSuggestion.cs b/Source/NETworkManager/RunCommandSuggestion.cs index 57ce6dda23..b44f268a65 100644 --- a/Source/NETworkManager/RunCommandSuggestion.cs +++ b/Source/NETworkManager/RunCommandSuggestion.cs @@ -38,6 +38,11 @@ public enum RunCommandSuggestionKind /// PortProfile, + /// + /// Service type profile of the mDNS / DNS-SD tool (e.g. "Printers") or * (all service types). + /// + ServiceTypeProfile, + /// /// Command for a target typed without a command (e.g. "ping 10.0.0.1" for "10.0.0.1"). /// diff --git a/Source/NETworkManager/ViewModels/RunCommandViewModel.cs b/Source/NETworkManager/ViewModels/RunCommandViewModel.cs index cb2ac8de80..df3284f11d 100644 --- a/Source/NETworkManager/ViewModels/RunCommandViewModel.cs +++ b/Source/NETworkManager/ViewModels/RunCommandViewModel.cs @@ -449,6 +449,8 @@ public void Complete() { RunCommandPosition.Target when _result.ProfileName is { Length: > 0 } => Suggestions.FirstOrDefault(x => x.Kind == RunCommandSuggestionKind.Profile), + RunCommandPosition.Target when _result.CurrentWord is { Length: > 0 } => + Suggestions.FirstOrDefault(x => x.Kind == RunCommandSuggestionKind.ServiceTypeProfile), RunCommandPosition.Argument when _result.CurrentWord.Length > 0 => Suggestions.FirstOrDefault(x => x.Kind is RunCommandSuggestionKind.DNSServer or RunCommandSuggestionKind.PortProfile or RunCommandSuggestionKind.Type), @@ -657,6 +659,7 @@ .. GetHistorySuggestions().Take(MaxSuggestions) RunCommandPosition.Target when _result.ProfileName != null => GetProfileSuggestions().Take(MaxSuggestions), RunCommandPosition.Target => [ + .. GetServiceTypeProfileSuggestions().Take(MaxSuggestions), .. GetHistorySuggestions().Take(MaxCommandHistorySuggestions), .. GetProfileSuggestions().Take(MaxSuggestions) ], @@ -1157,6 +1160,23 @@ private IEnumerable GetDNSServerSuggestions() Strings.DNSServers, isList: true); } + /// + /// Service type profiles of the mDNS / DNS-SD tool (e.g. "Printers") and * that contain the typed word, while + /// the target is typed. The target can be a list of service types and profiles (e.g. "printers;_ssh._tcp"), the + /// last entry is completed. + /// + private IEnumerable GetServiceTypeProfileSuggestions() + { + if (_result.Command?.Application != ApplicationName.MDNSDiscovery || _result.ProfileName != null) + return []; + + return GetValueSuggestions(RunCommandManager.GetMDNSServiceTypeProfiles() + .OrderBy(x => x.Name, StringComparer.OrdinalIgnoreCase) + .Select(x => (x.Name, x.ServiceTypes)) + .Prepend(("*", Strings.MDNSDiscovery_AllServiceTypes)), + RunCommandSuggestionKind.ServiceTypeProfile, Strings.MDNSDiscovery_ServiceTypeProfiles, isList: true); + } + /// /// Named values of the second argument of the command (e.g. DNS servers, port profiles) that contain the typed /// word, if the argument was not entered yet. Names with spaces are inserted in quotes. @@ -1177,17 +1197,31 @@ private IEnumerable GetArgumentValueSuggestions(RunCommand _result.Argument != null && !string.Equals(_result.Argument, _result.CurrentWord)) return []; + return GetValueSuggestions(values, kind, group, isList); + } + + /// + /// Named values that contain the word that is being typed (the target or the second argument), see + /// . + /// + private IEnumerable GetValueSuggestions(IEnumerable<(string Name, string Description)> values, + RunCommandSuggestionKind kind, string group, bool isList) + { + // Nothing typed yet (e.g. "mdns ") + var currentToken = _result.CurrentToken ?? string.Empty; + var currentWord = _result.CurrentWord ?? string.Empty; + // Entries before the one that is being typed, as entered (e.g. "webserver;" of "webserver;dat") - var separator = isList ? _result.CurrentToken.LastIndexOf(';') : -1; - var previousEntries = _result.CurrentToken[..(separator + 1)]; + var separator = isList ? currentToken.LastIndexOf(';') : -1; + var previousEntries = currentToken[..(separator + 1)]; // Typed in the open quote of the previous entry (e.g. "DNS (via TCP); web) - close it before the ";" if (previousEntries.Count(x => x == '"') % 2 == 1) previousEntries = previousEntries[..^1].TrimEnd() + "\";"; var entry = separator < 0 - ? _result.CurrentWord - : _result.CurrentToken[(separator + 1)..].Replace("\"", string.Empty).Trim(); + ? currentWord + : currentToken[(separator + 1)..].Replace("\"", string.Empty).Trim(); return values .Where(x => x.Name.Contains(entry, StringComparison.OrdinalIgnoreCase)) diff --git a/Source/NETworkManager/Views/RunCommandChildWindow.xaml b/Source/NETworkManager/Views/RunCommandChildWindow.xaml index 17985879b5..28114e7da1 100644 --- a/Source/NETworkManager/Views/RunCommandChildWindow.xaml +++ b/Source/NETworkManager/Views/RunCommandChildWindow.xaml @@ -292,6 +292,12 @@ + + + + diff --git a/Website/docs/run-command.md b/Website/docs/run-command.md index b219dc68e3..00902cc2b9 100644 --- a/Website/docs/run-command.md +++ b/Website/docs/run-command.md @@ -56,6 +56,7 @@ All features that accept a target also accept a profile (`@profile`), except the - **Remote Desktop, PowerShell, PuTTY, TigerVNC and Web Console** open the connect dialog with the host, so the connection settings can be adjusted before connecting. A profile connects directly with its settings. - **DNS lookup:** The type is the DNS record type (`a`, `aaaa`, `any`, `caa`, `cname`, `dnskey`, `mx`, `ns`, `ptr`, `soa`, `srv`, `txt`). Without a type, IP addresses are looked up with `ptr` and other hosts with the type selected in the feature. The DNS server is the name of a configured DNS server (case-insensitive, e.g. `cloudflare`) or a custom DNS server (an IP address or a host with a domain, with an optional port, e.g. `1.1.1.1`, `dns.google:53`), also several separated by `;` (e.g. `"Google Public DNS";cloudflare;9.9.9.9`, the configured DNS servers are suggested after a `;` as well). +- **mDNS / DNS-SD:** The target is `*` (all service types), service types (e.g. `_ipp._tcp`) and / or names of service type profiles (case-insensitive, e.g. `mdns printers` or `mdns printers;_ssh._tcp`; a name with spaces in quotes, also in a list, e.g. `"File sharing";web`). `*` and the service type profiles are suggested while the target is typed, also after a `;`. - **RDAP:** The type is `domain`, `nameserver`, `tld`, `ip`, `asn` or `entity`. Without a type, it is detected from the query (see [RDAP](./application/rdap.md#example-inputs)). - **Subnet Calculator:** A subnet (e.g. `subnet 10.0.0.0/24`) is calculated in **Calculator**. With a new subnet mask or CIDR (e.g. `/26`, `26` or `255.255.255.192`), it is split in **Subnetting**; the new mask must be between the CIDR of the subnet and `/32` (IPv4) or `/128` (IPv6). With a second subnet (e.g. `subnet 10.0.0.0/24 10.0.1.0/24`), the **Wide Subnet** is calculated (IPv4 only). - **Lookup:** The first word after the command is the lookup: `oui` (MAC addresses or vendors, e.g. `lookup oui 00:11:22`) or `port` (ports, port ranges or services, e.g. `lookup port 22; 80-90/tcp; ssh`). The rest of the input is the query, so vendors can contain spaces without quotes (e.g. `lookup oui Cisco Systems`). Without a query (e.g. `lookup port`), the lookup is only shown. @@ -103,7 +104,7 @@ While typing, suggestions are shown below the input, grouped (e.g. _Recent_, _Pr | _empty_ | Commands for the clipboard (if enabled), recently run commands, examples (without recent commands) and all features | | Command (e.g. `tr`) | Matching features, recent commands that contain the word (e.g. a host) and commands for the clipboard (if enabled) that start with it | | Target (e.g. `10.0.0.1`) | Recent commands that contain the target and the commands that accept it, see [Target without a command](#target-without-a-command) | -| After the command (`rdp `) | Recent commands of the feature and its profiles | +| After the command (`rdp `) | Recent commands of the feature and its profiles; mDNS / DNS-SD: `*` and the service type profiles (also while typing the target) | | After `lookup ` | The lookups (`oui`, `port`) and recent commands | | `@` (e.g. `rdp @web`) | Profiles of the feature (with group and host); exact names first, recently run profiles first within the same match | | After the target | Configured DNS servers (DNS lookup), port profiles (Port Scanner), types of the feature (e.g. DNS record types) and recent commands, up to 10 of each | From 29f0864c233f8dcfa0d1ce5bed0114d814c15552 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:55:20 +0100 Subject: [PATCH 33/80] Feature: Run command - Optional duration of mDNS / DNS-SD (R2) mdns [duration], e.g. mdns printers 30: one of the durations of the tool (10, 30, 60, 120, 300, 0 = until stopped), validated and suggested after the target (Timer icon, like the duration of the Discovery Protocol). Without it the selected duration is used. MDNSDiscoveryRequest carries the duration; the durations are defined once (MDNSBrowser.Durations) for the tool and the run command. Co-Authored-By: Claude Opus 5.5 --- .../Resources/Strings.Designer.cs | 9 ++++++ .../Resources/Strings.resx | 3 ++ .../Network/MDNSBrowser.cs | 5 ++++ .../RunCommand/RunCommandArgument.cs | 5 ++-- Source/NETworkManager/ApplicationRequest.cs | 13 ++++++++ Source/NETworkManager/RunCommandManager.cs | 30 ++++++++++++++++++- Source/NETworkManager/RunCommandSuggestion.cs | 5 ++++ .../ViewModels/MDNSDiscoveryViewModel.cs | 6 +++- .../ViewModels/RunCommandViewModel.cs | 17 ++++++++++- .../Views/RunCommandChildWindow.xaml | 8 +++++ Website/docs/application/mdns-discovery.md | 7 +++-- Website/docs/changelog/next-release.md | 2 +- Website/docs/run-command.md | 6 ++-- 13 files changed, 104 insertions(+), 12 deletions(-) diff --git a/Source/NETworkManager.Localization/Resources/Strings.Designer.cs b/Source/NETworkManager.Localization/Resources/Strings.Designer.cs index 9c1deb1564..384f789026 100644 --- a/Source/NETworkManager.Localization/Resources/Strings.Designer.cs +++ b/Source/NETworkManager.Localization/Resources/Strings.Designer.cs @@ -8346,6 +8346,15 @@ public static string MDNSDiscovery_Empty { } } + /// + /// Looks up a localized string similar to Enter a duration in seconds: {0} (0 = until stopped).. + /// + public static string MDNSDiscovery_EnterValidDuration { + get { + return ResourceManager.GetString("MDNSDiscovery_EnterValidDuration", resourceCulture); + } + } + /// /// Looks up a localized string similar to Enter service types such as _ipp._tcp, separated by ";".. /// diff --git a/Source/NETworkManager.Localization/Resources/Strings.resx b/Source/NETworkManager.Localization/Resources/Strings.resx index 213ab91f4e..657653e807 100644 --- a/Source/NETworkManager.Localization/Resources/Strings.resx +++ b/Source/NETworkManager.Localization/Resources/Strings.resx @@ -5648,4 +5648,7 @@ Do you want to start the scan? All advertised service types + + Enter a duration in seconds: {0} (0 = until stopped). + \ No newline at end of file diff --git a/Source/NETworkManager.Models/Network/MDNSBrowser.cs b/Source/NETworkManager.Models/Network/MDNSBrowser.cs index 22bf413a05..53cca4366a 100644 --- a/Source/NETworkManager.Models/Network/MDNSBrowser.cs +++ b/Source/NETworkManager.Models/Network/MDNSBrowser.cs @@ -22,6 +22,11 @@ public static class MDNSBrowser { private static readonly ILog Log = LogManager.GetLogger(typeof(MDNSBrowser)); + /// + /// Durations of a browse in seconds that can be selected (tool and run command), 0 = until stopped. + /// + public static IReadOnlyList Durations { get; } = [10, 30, 60, 120, 300, 0]; + /// /// Windows reports an ICMP "port unreachable" of an earlier datagram as a connection reset on the next receive /// of an UDP socket (SIO_UDP_CONNRESET). Disabled, it would only end the receiver. diff --git a/Source/NETworkManager.Models/RunCommand/RunCommandArgument.cs b/Source/NETworkManager.Models/RunCommand/RunCommandArgument.cs index d3791215a3..759489a715 100644 --- a/Source/NETworkManager.Models/RunCommand/RunCommandArgument.cs +++ b/Source/NETworkManager.Models/RunCommand/RunCommandArgument.cs @@ -2,7 +2,7 @@ /// /// Second argument of a run command after the target. is a new subnet mask or a second -/// subnet (Subnet Calculator). +/// subnet (Subnet Calculator), the duration in seconds (mDNS / DNS-SD). /// public enum RunCommandArgument { @@ -10,5 +10,6 @@ public enum RunCommandArgument Ports, DNSServer, Broadcast, - Subnet + Subnet, + Duration } diff --git a/Source/NETworkManager/ApplicationRequest.cs b/Source/NETworkManager/ApplicationRequest.cs index 7adc6d201f..f41a02dce7 100644 --- a/Source/NETworkManager/ApplicationRequest.cs +++ b/Source/NETworkManager/ApplicationRequest.cs @@ -2,6 +2,7 @@ using DnsClient; using NETworkManager.Models; using NETworkManager.Models.Lookup; +using NETworkManager.Models.Network; using NETworkManager.Models.RDAP; using NETworkManager.Profiles; @@ -71,6 +72,18 @@ public sealed record WakeOnLANRequest() : ApplicationRequest(ApplicationName.Wak public string Broadcast { get; init; } } +/// +/// Request to open the mDNS / DNS-SD tool. +/// +public sealed record MDNSDiscoveryRequest() : ApplicationRequest(ApplicationName.MDNSDiscovery) +{ + /// + /// Duration of the browse in seconds (one of , 0 = until stopped). If null, + /// the duration selected in the tool is used. + /// + public int? Duration { get; init; } +} + /// /// Request to open RDAP. /// diff --git a/Source/NETworkManager/RunCommandManager.cs b/Source/NETworkManager/RunCommandManager.cs index 90d9da7d0d..20bbf254f8 100644 --- a/Source/NETworkManager/RunCommandManager.cs +++ b/Source/NETworkManager/RunCommandManager.cs @@ -131,6 +131,15 @@ public static IEnumerable GetMDNSServiceTypeProfiles return SettingsManager.Current.MDNSDiscovery_ServiceTypeProfiles; } + /// + /// Gets the durations of the mDNS / DNS-SD tool in seconds (0 = until stopped). + /// + /// Durations. + public static IEnumerable GetMDNSDurations() + { + return MDNSBrowser.Durations; + } + /// /// Gets the translated name of the application (or settings) of a command. /// @@ -350,6 +359,7 @@ ApplicationName.Traceroute or ApplicationName.PowerShell or ApplicationName.PuTT { RunCommandArgument.DNSServer => ValidateDNSServer(result.Argument), RunCommandArgument.Subnet => ValidateSubnetArgument(result.Target, result.Argument), + RunCommandArgument.Duration => ValidateDuration(result.Argument), _ => Validate(argumentValidator, result.Argument) }; @@ -383,6 +393,18 @@ private static string ValidateDNSServer(string dnsServer) return invalidEntry == null ? null : string.Format(Strings.UnknownArgumentX, invalidEntry); } + /// + /// Validates the duration of the mDNS / DNS-SD tool: one of the durations that can be selected in the tool + /// (seconds, 0 = until stopped). + /// + private static string ValidateDuration(string duration) + { + return int.TryParse(duration, NumberStyles.None, CultureInfo.InvariantCulture, out var seconds) && + MDNSBrowser.Durations.Contains(seconds) + ? null + : string.Format(Strings.MDNSDiscovery_EnterValidDuration, string.Join(", ", MDNSBrowser.Durations)); + } + /// /// Validates the second argument of the Subnet Calculator: a new subnet mask or CIDR (Subnetting), which must be /// between the CIDR of the subnet and the maximum of the address family, or a second subnet (Wide Subnet, IPv4 @@ -439,6 +461,11 @@ private static ApplicationRequest CreateRequest(RunCommandParseResult result) Ports = result.Argument }, ApplicationName.WakeOnLAN => new WakeOnLANRequest { Target = result.Target, Broadcast = result.Argument }, + ApplicationName.MDNSDiscovery => new MDNSDiscoveryRequest + { + Target = result.Target, + Duration = result.Argument != null ? int.Parse(result.Argument, CultureInfo.InvariantCulture) : null + }, ApplicationName.RDAP => new RDAPRequest { Target = result.Target, QueryType = GetRDAPQueryType(result.Type) }, // The argument is a new subnet mask (Subnetting) or a second subnet (Wide Subnet). ApplicationName.SubnetCalculator => result.Argument != null && IsSubnetmaskOrCidr(result.Argument) @@ -496,7 +523,8 @@ [.. DNSLookup.QueryTypes.Select(x => x.ToString().ToLowerInvariant()).Order()]), ApplicationName.RDAP => Create(name, [], [Target(Strings.Query), type], types: [.. RDAPTypes.Keys]), ApplicationName.Whois => Create(name, [], [Target(Strings.Domain)]), ApplicationName.IPGeolocation => Create(name, ["geo"], [Target(Strings.Host)]), - ApplicationName.MDNSDiscovery => Create(name, ["mdns", "dnssd"], [Target(Strings.MDNSDiscovery_ServiceType)], + ApplicationName.MDNSDiscovery => Create(name, ["mdns", "dnssd"], + [Target(Strings.MDNSDiscovery_ServiceType), Argument(Strings.DurationS)], RunCommandArgument.Duration, supportsProfile: false), ApplicationName.WakeOnLAN => Create(name, ["wol"], [Target(Strings.MACAddress), Argument(Strings.Broadcast)], RunCommandArgument.Broadcast), diff --git a/Source/NETworkManager/RunCommandSuggestion.cs b/Source/NETworkManager/RunCommandSuggestion.cs index b44f268a65..707ace1206 100644 --- a/Source/NETworkManager/RunCommandSuggestion.cs +++ b/Source/NETworkManager/RunCommandSuggestion.cs @@ -43,6 +43,11 @@ public enum RunCommandSuggestionKind /// ServiceTypeProfile, + /// + /// Duration of the mDNS / DNS-SD tool (seconds, 0 = until stopped). + /// + Duration, + /// /// Command for a target typed without a command (e.g. "ping 10.0.0.1" for "10.0.0.1"). /// diff --git a/Source/NETworkManager/ViewModels/MDNSDiscoveryViewModel.cs b/Source/NETworkManager/ViewModels/MDNSDiscoveryViewModel.cs index 8bcab97ae7..03e99b594a 100644 --- a/Source/NETworkManager/ViewModels/MDNSDiscoveryViewModel.cs +++ b/Source/NETworkManager/ViewModels/MDNSDiscoveryViewModel.cs @@ -117,7 +117,7 @@ public string ServiceType /// /// Gets the durations of a browse in seconds (0 = until stopped). /// - public IReadOnlyList Durations { get; } = [10, 30, 60, 120, 300, 0]; + public IReadOnlyList Durations => MDNSBrowser.Durations; /// /// Gets or sets the duration of a browse in seconds (0 = until stopped). @@ -838,6 +838,10 @@ public async Task OpenAsync(ApplicationRequest request) ServiceType = request.Target; + // Duration of the run command (e.g. "mdns printers 30"), otherwise the selected one + if (request is MDNSDiscoveryRequest { Duration: { } duration } && Durations.Contains(duration)) + SelectedDuration = duration; + if (request.Start) await (_browseTask = Browse()); } diff --git a/Source/NETworkManager/ViewModels/RunCommandViewModel.cs b/Source/NETworkManager/ViewModels/RunCommandViewModel.cs index df3284f11d..6e8292d4df 100644 --- a/Source/NETworkManager/ViewModels/RunCommandViewModel.cs +++ b/Source/NETworkManager/ViewModels/RunCommandViewModel.cs @@ -7,6 +7,7 @@ using NETworkManager.Utilities; using System; using System.Collections.Generic; +using System.Globalization; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; @@ -453,7 +454,8 @@ public void Complete() Suggestions.FirstOrDefault(x => x.Kind == RunCommandSuggestionKind.ServiceTypeProfile), RunCommandPosition.Argument when _result.CurrentWord.Length > 0 => Suggestions.FirstOrDefault(x => x.Kind is RunCommandSuggestionKind.DNSServer - or RunCommandSuggestionKind.PortProfile or RunCommandSuggestionKind.Type), + or RunCommandSuggestionKind.PortProfile or RunCommandSuggestionKind.Duration + or RunCommandSuggestionKind.Type), _ => null }); @@ -667,6 +669,7 @@ .. GetProfileSuggestions().Take(MaxSuggestions) _ => [ .. GetDNSServerSuggestions().Take(MaxSuggestions), .. GetPortProfileSuggestions().Take(MaxSuggestions), + .. GetDurationSuggestions().Take(MaxSuggestions), .. GetTypeSuggestions().Take(MaxSuggestions), .. GetHistorySuggestions().Take(MaxSuggestions) ] }; @@ -1160,6 +1163,18 @@ private IEnumerable GetDNSServerSuggestions() Strings.DNSServers, isList: true); } + /// + /// Durations of the mDNS / DNS-SD tool (seconds, 0 = until stopped) that contain the typed word, if no duration + /// was entered yet. + /// + private IEnumerable GetDurationSuggestions() + { + return GetArgumentValueSuggestions(RunCommandArgument.Duration, + RunCommandManager.GetMDNSDurations().Select(x => (x.ToString(CultureInfo.InvariantCulture), + x == 0 ? Strings.MDNSDiscovery_UntilStopped : Strings.DurationS)), + RunCommandSuggestionKind.Duration, Strings.DurationS); + } + /// /// Service type profiles of the mDNS / DNS-SD tool (e.g. "Printers") and * that contain the typed word, while /// the target is typed. The target can be a list of service types and profiles (e.g. "printers;_ssh._tcp"), the diff --git a/Source/NETworkManager/Views/RunCommandChildWindow.xaml b/Source/NETworkManager/Views/RunCommandChildWindow.xaml index 28114e7da1..512884377a 100644 --- a/Source/NETworkManager/Views/RunCommandChildWindow.xaml +++ b/Source/NETworkManager/Views/RunCommandChildWindow.xaml @@ -42,6 +42,9 @@ Visual="{icons:Lucide Kind=Server}" /> + +