diff --git a/Scripts/Create-LucideIcons.ps1 b/Scripts/Create-LucideIcons.ps1 index 393801cc36..64bcadc0aa 100644 --- a/Scripts/Create-LucideIcons.ps1 +++ b/Scripts/Create-LucideIcons.ps1 @@ -33,7 +33,8 @@ $Icons = @( "list-chevrons-down-up", "list-chevrons-up-down", "list-filter", "list-plus", "list-x", "lock", "map-pin", "maximize", "maximize-2", "minimize", "minus", "monitor", "monitor-check", "monitor-dot", "monitor-down", "monitor-x", "network", "octagon-alert", "palette", "pause", "pencil", "pin", "play", "plug-zap", "plus", "power", "radar", "radio-tower", "refresh-cw", "rocket", - "rotate-ccw", "route", "router", "save", "scan", "scan-line", "scissors", "search", "server", "settings", "shield", + "rotate-ccw", "route", "router", "satellite-dish", "save", "scan", "scan-line", "scissors", "search", "server", + "settings", "shield", "shield-lock", "shield-off", "sliders-horizontal", "square-chevron-right", "table", "tag", "terminal", "timer", "toggle-left", "toggle-right", "triangle-alert", "undo-2", "unplug", "user", "user-lock", "users", "wifi", "wifi-high", "wifi-lock", "wifi-low", "wifi-off", "wifi-zero", "x" diff --git a/Source/GlobalAssemblyInfo.cs b/Source/GlobalAssemblyInfo.cs index f3fd20736a..6800b95628 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.20.0")] +[assembly: AssemblyFileVersion("2026.11.20.0")] diff --git a/Source/NETworkManager.Controls/LucideIcons.cs b/Source/NETworkManager.Controls/LucideIcons.cs index 1bf8486e27..45445eaf4a 100644 --- a/Source/NETworkManager.Controls/LucideIcons.cs +++ b/Source/NETworkManager.Controls/LucideIcons.cs @@ -1,5 +1,5 @@ // -// Generated 2026-11-10 by Scripts/Create-LucideIcons.ps1 from lucide-static 1.71.0 +// Generated 2026-11-18 by Scripts/Create-LucideIcons.ps1 from lucide-static 1.71.0 // (https://lucide.dev). Don't edit this file, add the icon to the script and run it again. // // Custom icons: wifi-*-lock from the parts of wifi-lock (Lucide), github and x-logo from Simple Icons @@ -157,6 +157,7 @@ public enum LucideIconKind RotateCcw, Route, Router, + SatelliteDish, Save, Scan, ScanLine, @@ -299,6 +300,7 @@ internal static class LucideIconData [LucideIconKind.RotateCcw] = ("F1 M3 12 a9 9 0 1 0 9 -9 a9.75 9.75 0 0 0 -6.74 2.74 L3 8 M3 3 v5 h5", null), [LucideIconKind.Route] = ("F1 M3 19 A3 3 0 1 0 9 19 A3 3 0 1 0 3 19 Z M9 19 h8.5 a3.5 3.5 0 0 0 0 -7 h-11 a3.5 3.5 0 0 1 0 -7 H15 M15 5 A3 3 0 1 0 21 5 A3 3 0 1 0 15 5 Z", null), [LucideIconKind.Router] = ("F1 M4 14 H20 A2 2 0 0 1 22 16 V20 A2 2 0 0 1 20 22 H4 A2 2 0 0 1 2 20 V16 A2 2 0 0 1 4 14 Z M6.01 18 H6 M10.01 18 H10 M15 10 v4 M17.84 7.17 a4 4 0 0 0 -5.66 0 M20.66 4.34 a8 8 0 0 0 -11.31 0", null), + [LucideIconKind.SatelliteDish] = ("F1 M18 12 a6 6 0 0 0 -6 -6 M2.824 10.459 a8 8 0 0 0 10.717 10.717 c0.558 -0.276 0.623 -1.012 0.183 -1.452 l-9.448 -9.448 c-0.44 -0.44 -1.176 -0.375 -1.452 0.183 M22 12 A10 10 0 0 0 12 2 M9 15 l4 -4", null), [LucideIconKind.Save] = ("F1 M15.2 3 a2 2 0 0 1 1.4 0.6 l3.8 3.8 a2 2 0 0 1 0.6 1.4 V19 a2 2 0 0 1 -2 2 H5 a2 2 0 0 1 -2 -2 V5 a2 2 0 0 1 2 -2 z M17 21 v-7 a1 1 0 0 0 -1 -1 H8 a1 1 0 0 0 -1 1 v7 M7 3 v4 a1 1 0 0 0 1 1 h7", null), [LucideIconKind.Scan] = ("F1 M3 7 V5 a2 2 0 0 1 2 -2 h2 M17 3 h2 a2 2 0 0 1 2 2 v2 M21 17 v2 a2 2 0 0 1 -2 2 h-2 M7 21 H5 a2 2 0 0 1 -2 -2 v-2", null), [LucideIconKind.ScanLine] = ("F1 M3 7 V5 a2 2 0 0 1 2 -2 h2 M17 3 h2 a2 2 0 0 1 2 2 v2 M21 17 v2 a2 2 0 0 1 -2 2 h-2 M7 21 H5 a2 2 0 0 1 -2 -2 v-2 M7 12 h10", null), diff --git a/Source/NETworkManager.Documentation/DocumentationIdentifier.cs b/Source/NETworkManager.Documentation/DocumentationIdentifier.cs index 63b071e9a5..09e39a12a8 100644 --- a/Source/NETworkManager.Documentation/DocumentationIdentifier.cs +++ b/Source/NETworkManager.Documentation/DocumentationIdentifier.cs @@ -100,6 +100,11 @@ public enum DocumentationIdentifier /// ApplicationDiscoveryProtocol, + /// + /// mDNS Discovery documentation page. + /// + ApplicationMDNSDiscovery, + /// /// Wake on LAN documentation page. /// @@ -219,4 +224,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..e816644b2b 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, @@ -274,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..d8e4ae95ea 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,33 @@ public static string ExampleMACAddressesOrVendor { } } + /// + /// Looks up a localized string similar to Printers; _ssh._tcp. + /// + public static string ExampleMDNSServiceTypeInput { + get { + return ResourceManager.GetString("ExampleMDNSServiceTypeInput", resourceCulture); + } + } + + /// + /// 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 +851,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..b5d656d24a 100644 --- a/Source/NETworkManager.Localization/Resources/StaticStrings.resx +++ b/Source/NETworkManager.Localization/Resources/StaticStrings.resx @@ -381,4 +381,13 @@ a.iana-servers.net + + Printers + + + _ipp._tcp; _ipps._tcp + + + Printers; _ssh._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 5d071b5767..7580801224 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 Discovery. + /// + public static string ApplicationName_MDNSDiscovery { + get { + return ResourceManager.GetString("ApplicationName_MDNSDiscovery", resourceCulture); + } + } + /// /// Looks up a localized string similar to Neighbor Table. /// @@ -8256,6 +8265,258 @@ 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 All advertised service types. + /// + public static string MDNSDiscovery_AllServiceTypes { + get { + return ResourceManager.GetString("MDNSDiscovery_AllServiceTypes", resourceCulture); + } + } + + /// + /// 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 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.. + /// + public static string MDNSDiscovery_Empty { + get { + return ResourceManager.GetString("MDNSDiscovery_Empty", resourceCulture); + } + } + + /// + /// 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 ";".. + /// + 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.. + /// + public static string MDNSDiscovery_Failed { + get { + return ResourceManager.GetString("MDNSDiscovery_Failed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The last used network interface is not available, "{0}" is used instead.. + /// + public static string MDNSDiscovery_InterfaceNotAvailable { + get { + return ResourceManager.GetString("MDNSDiscovery_InterfaceNotAvailable", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Enter *, service types such as _ipp._tcp and/or service type profiles, separated by ";".. + /// + 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.. + /// + 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 Raw DNS records. + /// + public static string MDNSDiscovery_RawRecords { + get { + return ResourceManager.GetString("MDNSDiscovery_RawRecords", 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 service types such as _ipp._tcp and/or service type profiles (e.g. Printers), separated by ";". The profiles can be changed in the settings. 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 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. + /// + public static string MDNSDiscovery_TXTRecords { + get { + return ResourceManager.GetString("MDNSDiscovery_TXTRecords", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Until stopped. + /// + public static string MDNSDiscovery_UntilStopped { + get { + return ResourceManager.GetString("MDNSDiscovery_UntilStopped", 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 {0} records. + /// + public static string MDNSDiscovery_XRecords { + get { + return ResourceManager.GetString("MDNSDiscovery_XRecords", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} services. + /// + public static string MDNSDiscovery_XServices { + get { + return ResourceManager.GetString("MDNSDiscovery_XServices", resourceCulture); + } + } + /// /// Looks up a localized string similar to mDNS hostname. /// diff --git a/Source/NETworkManager.Localization/Resources/Strings.resx b/Source/NETworkManager.Localization/Resources/Strings.resx index ce63409d40..5d0258b122 100644 --- a/Source/NETworkManager.Localization/Resources/Strings.resx +++ b/Source/NETworkManager.Localization/Resources/Strings.resx @@ -5567,4 +5567,91 @@ Do you want to start the scan? ISC License + + mDNS Discovery + + + Browse + + + 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. + + + Service discovery failed. Check the network interface and whether UDP port 5353 is available and allowed by the firewall. + + + Enter *, service types such as _ipp._tcp and/or service type profiles, separated by ";". + + + 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 service types such as _ipp._tcp and/or service type profiles (e.g. Printers), separated by ";". The profiles can be changed in the settings. Discovery is limited to the local. domain. + + + TXT records + + + SRV weight + + + No DNS records received. + + + Until stopped + + + {0} services + + + {0} records + + + 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 ";". + + + All advertised service types + + + Enter a duration in seconds: {0} (0 = until stopped). + + + The last used network interface is not available, "{0}" is used instead. + \ No newline at end of file diff --git a/Source/NETworkManager.Models/ApplicationManager.cs b/Source/NETworkManager.Models/ApplicationManager.cs index bbf05016f8..7cf57f4b17 100644 --- a/Source/NETworkManager.Models/ApplicationManager.cs +++ b/Source/NETworkManager.Models/ApplicationManager.cs @@ -116,6 +116,9 @@ public static Canvas GetIcon(ApplicationName name) case ApplicationName.DiscoveryProtocol: canvas.Children.Add(new LucideIcon { Kind = LucideIconKind.ArrowLeftRight }); break; + case ApplicationName.MDNSDiscovery: + canvas.Children.Add(new LucideIcon { Kind = LucideIconKind.SatelliteDish }); + break; case ApplicationName.WakeOnLAN: canvas.Children.Add(new LucideIcon { Kind = LucideIconKind.Power }); 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..0df312ec59 100644 --- a/Source/NETworkManager.Models/ApplicationName.cs +++ b/Source/NETworkManager.Models/ApplicationName.cs @@ -107,6 +107,11 @@ public enum ApplicationName /// DiscoveryProtocol, + /// + /// mDNS Discovery (multicast DNS service discovery) application. + /// + MDNSDiscovery, + /// /// Wake on LAN application. /// @@ -163,4 +168,4 @@ public enum ApplicationName /// [System.Obsolete("Use NeighborTable instead.")] ARPTable -} \ No newline at end of file +} 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..7ae95722c6 --- /dev/null +++ b/Source/NETworkManager.Models/Network/MDNSBrowser.cs @@ -0,0 +1,285 @@ +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; +using log4net; + +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 +{ + 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. + /// + private const int SIO_UDP_CONNRESET = -1744830452; + + /// + /// Gets the active interfaces with multicast support and an IPv4 or IPv6 address (sorted by name). + /// + public static IReadOnlyList GetInterfaces() => System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces() + .Where(x => x.OperationalStatus == OperationalStatus.Up && x.SupportsMulticast && + x.NetworkInterfaceType != NetworkInterfaceType.Loopback) + .Select(TryCreateInterfaceInfo) + .Where(x => x != null && (x.IPv4Address != null || x.IPv6Index != 0)).OrderBy(x => x.Name).ToArray(); + + /// + /// Reads the addresses and indexes of an interface. An interface whose IP properties can't be read (e.g. some + /// virtual adapters) is skipped instead of failing the whole list. + /// + private static MDNSInterfaceInfo TryCreateInterfaceInfo(System.Net.NetworkInformation.NetworkInterface networkInterface) + { + IPInterfaceProperties properties; + IPAddress ipv4; + bool hasIPv6; + + // The properties and the address list (read when enumerated) + try + { + properties = networkInterface.GetIPProperties(); + ipv4 = properties.UnicastAddresses.FirstOrDefault(a => a.Address.AddressFamily == AddressFamily.InterNetwork)?.Address; + hasIPv6 = properties.UnicastAddresses.Any(a => a.Address.AddressFamily == AddressFamily.InterNetworkV6); + } + catch (NetworkInformationException ex) + { + Log.Warn($"Cannot read the IP properties of the network interface \"{networkInterface.Name}\", it is skipped.", ex); + + return null; + } + + // Each address family on its own: one that can't be read (e.g. IPv6 partly configured) doesn't drop the other + var ipv4Index = ipv4 == null ? 0 : GetIndex(() => properties.GetIPv4Properties().Index, "IPv4"); + var ipv6Index = hasIPv6 ? GetIndex(() => properties.GetIPv6Properties().Index, "IPv6") : 0; + + return new MDNSInterfaceInfo(networkInterface.Id, networkInterface.Name, ipv4Index == 0 ? null : ipv4, ipv4Index, + ipv6Index); + + int GetIndex(Func getIndex, string addressFamily) + { + try + { + return getIndex(); + } + catch (NetworkInformationException ex) + { + Log.Warn($"Cannot read the {addressFamily} properties of the network interface \"{networkInterface.Name}\".", ex); + + return 0; + } + } + } + + /// + /// 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 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, IReadOnlyCollection serviceTypes, + Action update, CancellationToken cancellationToken, MDNSServiceCache cache = null) + { + ArgumentNullException.ThrowIfNull(networkInterface); + 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(); + long droppedPackets = 0; + try + { + // One address family may fail (e.g. joining the IPv6 group on some adapters), the other is still used + SocketException socketError = null; + foreach (var ipv6 in new[] { false, true }) + { + if (ipv6 ? networkInterface.IPv6Index == 0 : networkInterface.IPv4Address == null) + continue; + + try + { + sockets.Add(CreateSocket(networkInterface, ipv6)); + } + catch (SocketException ex) + { + Log.Warn($"Cannot open the mDNS socket ({(ipv6 ? "IPv6" : "IPv4")}) on \"{networkInterface.Name}\".", ex); + socketError ??= ex; + } + } + + 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 {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))); + using var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(250)); + var lastVersion = -1L; + var lastUpdate = DateTimeOffset.MinValue; + do + { + cancellationToken.ThrowIfCancellationRequested(); + // A receiver ends only with an error (not a transient one, see ReceiveAsync). The browse fails if all + // receivers failed - never silently show an empty result. + if (receivers.All(x => x.IsCompleted)) + await Task.WhenAll(receivers).ConfigureAwait(false); + 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); + // Several questions per packet, with their known answers (RFC 6762 7.1) + var questions = cache.GetQuestions(now); + var queries = questions.Count == 0 + ? [] + : MDNSMessage.CreateQueries(questions, (name, type) => cache.GetKnownAnswers(name, type, now)); + foreach (var data in queries) + { + foreach (var socket in sockets) + { + try + { + await socket.Socket.SendToAsync(data, SocketFlags.None, socket.Destination, cancellationToken) + .ConfigureAwait(false); + } + catch (SocketException ex) + { + // E.g. the network is (temporarily) unreachable: the questions are asked again later + Log.Debug($"Cannot send the mDNS questions ({ex.SocketErrorCode})."); + } + } + } + // Only if something changed, or once per second for the TTL countdown + cache.Expire(now); + + if (cache.Version != lastVersion || now - lastUpdate >= TimeSpan.FromSeconds(1)) + { + lastVersion = cache.Version; + lastUpdate = now; + 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(); + + // 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) { } + 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 + { + if (OperatingSystem.IsWindows()) + socket.IOControl(SIO_UDP_CONNRESET, [0, 0, 0, 0], null); + + 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) + { + SocketReceiveMessageFromResult result; + + try + { + result = await socket.ReceiveMessageFromAsync(buffer.AsMemory(), SocketFlags.None, any, token) + .ConfigureAwait(false); + } + catch (SocketException ex) when (ex.SocketErrorCode is SocketError.ConnectionReset or + SocketError.NetworkReset or SocketError.MessageSize) + { + // ICMP error of an earlier datagram or a too large datagram: only this datagram is lost + continue; + } + catch (SocketException ex) when (!token.IsCancellationRequested) + { + // The other address family may still work (see BrowseAsync) + Log.Warn($"mDNS receiver ({socket.AddressFamily}) stopped.", ex); + throw; + } + + // Larger packets than allowed (RFC 6762 17) are not even copied, see MDNSMessage.ReadResponse + if (result.RemoteEndPoint is IPEndPoint { Port: 5353 } && result.PacketInformation.Interface == index && + (result.SocketFlags & SocketFlags.Truncated) == 0 && result.ReceivedBytes <= MDNSMessage.MaxPacketSize) + 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..88b41290fd --- /dev/null +++ b/Source/NETworkManager.Models/Network/MDNSMessage.cs @@ -0,0 +1,620 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Security.Cryptography; +using System.Text; +using NETworkManager.Utilities; + +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. Computed once: the record + // doesn't change and the identity is part of the cache key of every record of every packet. + public string Identity { get; } = $"{DNSNameComparer.ToLower(Target)}|{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; + + /// + /// Maximum size of a query packet: fits the minimum IPv6 MTU (1280 bytes - 40 bytes IPv6 header - 8 bytes UDP + /// header), so no packet is fragmented on any link. + /// + public const int MaxQuerySize = 1232; + + /// Builds a multicast question (ID zero, class IN, multicast response). + public static byte[] CreateQuery(string name, ushort type) => CreateQueries([(name, type)])[0]; + + /// + /// Maximum number of packets of one question with its known answers (the question packet and the packets with + /// only known answers, see ). Above, the known answers are left out: the responders + /// send them, like without known answers - a very large cache doesn't flood the link with questions. + /// + public const int MaxKnownAnswerPackets = 10; + + /// + /// Builds the packets of multicast questions (ID zero, class IN, multicast response): as many questions as fit + /// in one packet (, names compressed), each with its known answers (RFC 6762 7.1), so + /// the responders don't send the records again that are cached. Known answers that don't fit with their + /// question alone follow in packets with only known answers; every packet but the last of the question has + /// the TC bit set, so the responders wait for the rest (RFC 6762 7.2). At most + /// packets per question. + /// + /// Questions (escaped presentation format names). + /// + /// Gets the known answers of a question (PTR records: the target and the remaining TTL), may be null. + /// + /// Packets in the order of the questions. + public static IReadOnlyList CreateQueries(IReadOnlyList<(string Name, ushort Type)> questions, + Func> getKnownAnswers = null) + { + var packets = new List(); + var builder = new QueryBuilder(); + + foreach (var (name, type) in questions) + { + var question = new QueryQuestion(EncodeName(name), type, + (getKnownAnswers?.Invoke(name, type) ?? []).Select(x => (Target: TryEncodeName(x.Target), x.TTL)) + .Where(x => x.Target != null).ToArray()); + + if (builder.TryAdd(question, requireAllKnownAnswers: true)) + continue; + + if (builder.QuestionCount > 0) + { + packets.Add(builder.Build()); + builder = new QueryBuilder(); + } + + // Alone (always added): with as many known answers as fit - then the packet is full + if (builder.TryAdd(question, requireAllKnownAnswers: false, out var omitted)) + continue; + + // The other known answers in packets with only known answers (RFC 6762 7.2) + var questionPackets = new List { builder }; + + while (omitted.Count > 0 && questionPackets.Count < MaxKnownAnswerPackets) + { + var knownAnswers = new QueryBuilder(); + omitted = omitted.Where(x => !knownAnswers.TryAddKnownAnswer(question, x.Target, x.TTL)).ToList(); + questionPackets.Add(knownAnswers); + } + + // TC bit: more known answers follow in the next packet + for (var i = 0; i < questionPackets.Count; i++) + packets.Add(questionPackets[i].Build(truncated: i < questionPackets.Count - 1)); + + builder = new QueryBuilder(); + } + + if (builder.QuestionCount > 0) + packets.Add(builder.Build()); + + return packets; + } + + private sealed record QueryQuestion(List Name, ushort Type, (List Target, uint TTL)[] KnownAnswers); + + /// + /// Builds a query packet question by question: the questions, then their known answers. Names are compressed + /// against the names of the questions: their offsets don't change when a question is added (the answers follow + /// the questions and contain no pointers to each other), so a question that doesn't fit is simply removed again. + /// + private sealed class QueryBuilder + { + private readonly List _questions = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + private readonly List _answers = []; + private readonly Dictionary _offsets = new(StringComparer.Ordinal); + private int _answerCount; + + public int QuestionCount { get; private set; } + + /// + /// Adds a question with its known answers if it fits (). + /// + /// Question. + /// + /// True: only added if all known answers fit. False: added with as many known answers as fit (a question + /// alone always fits). + /// + /// True if the question was added with all its known answers. + public bool TryAdd(QueryQuestion question, bool requireAllKnownAnswers) => + TryAdd(question, requireAllKnownAnswers, out _); + + /// + /// Question. + /// See . + /// Known answers that were left out (they didn't fit). + public bool TryAdd(QueryQuestion question, bool requireAllKnownAnswers, + out List<(List Target, uint TTL)> omitted) + { + omitted = []; + var length = _questions.Count; + var registered = new List(); + + WriteName(_questions, question.Name, _offsets, registered); + _questions.AddRange([(byte)(question.Type >> 8), (byte)question.Type, 0, 1]); + + var size = _questions.Count + _answers.Count; + var answers = new List(); + var answerCount = 0; + var complete = true; + + foreach (var (target, ttl) in question.KnownAnswers) + { + var rdata = new List(); + WriteName(rdata, target, _offsets, null); + + var record = new List(); + WriteName(record, question.Name, _offsets, null); + record.AddRange([(byte)(question.Type >> 8), (byte)question.Type, 0, 1, + (byte)(ttl >> 24), (byte)(ttl >> 16), (byte)(ttl >> 8), (byte)ttl, + (byte)(rdata.Count >> 8), (byte)rdata.Count]); + record.AddRange(rdata); + + if (size + answers.Count + record.Count > MaxQuerySize) + { + complete = false; + omitted.Add((target, ttl)); + continue; + } + + answers.AddRange(record); + answerCount++; + } + + if (size > MaxQuerySize || !complete && requireAllKnownAnswers) + { + // Remove the question again + _questions.RemoveRange(length, _questions.Count - length); + + foreach (var key in registered) + _offsets.Remove(key); + + return false; + } + + _answers.AddRange(answers); + _answerCount += answerCount; + QuestionCount++; + + return complete; + } + + /// + /// Adds a known answer of a question to a packet without questions (more known answers of the question of + /// the previous packet, RFC 6762 7.2) if it fits. The names are compressed against the earlier answers. + /// + /// True if the known answer was added. + public bool TryAddKnownAnswer(QueryQuestion question, List target, uint ttl) + { + // Without questions, the answers are written right after the header (offsets of the packet) + var length = _questions.Count; + var registered = new List(); + + WriteName(_questions, question.Name, _offsets, registered); + _questions.AddRange([(byte)(question.Type >> 8), (byte)question.Type, 0, 1, + (byte)(ttl >> 24), (byte)(ttl >> 16), (byte)(ttl >> 8), (byte)ttl, 0, 0]); + var rdataStart = _questions.Count; + WriteName(_questions, target, _offsets, registered); + var rdataLength = _questions.Count - rdataStart; + _questions[rdataStart - 2] = (byte)(rdataLength >> 8); + _questions[rdataStart - 1] = (byte)rdataLength; + + if (_questions.Count > MaxQuerySize) + { + _questions.RemoveRange(length, _questions.Count - length); + + foreach (var key in registered) + _offsets.Remove(key); + + return false; + } + + _answerCount++; + + return true; + } + + /// + /// Builds the packet. + /// + /// Sets the TC bit: more known answers follow in the next packet. + public byte[] Build(bool truncated = false) + { + byte[] packet = [.. _questions, .. _answers]; + + if (truncated) + packet[2] = 0x02; + + packet[4] = (byte)(QuestionCount >> 8); + packet[5] = (byte)QuestionCount; + packet[6] = (byte)(_answerCount >> 8); + packet[7] = (byte)_answerCount; + + return packet; + } + } + + /// + /// Writes a name: its labels until a suffix that is already in the packet (a pointer to it, RFC 1035 4.1.4). + /// + /// Questions of the packet, or a record that is added after them (answers). + /// Labels of the name. + /// Offsets of the suffixes in the packet (key: lowercase ASCII, DNS compares like that). + /// + /// Adds the new suffixes to the offsets and their keys to this list (only if are the + /// questions), null to only use the offsets. + /// + private static void WriteName(List data, List labels, Dictionary offsets, + List registered) + { + for (var i = 0; i < labels.Count; i++) + { + var key = string.Join('.', labels.Skip(i).Select(x => Convert.ToHexString(x.Select(ToLowerAscii).ToArray()))); + + if (offsets.TryGetValue(key, out var offset)) + { + data.AddRange([(byte)(0xC0 | offset >> 8), (byte)offset]); + return; + } + + if (registered != null && data.Count < 0x4000) + { + offsets[key] = data.Count; + registered.Add(key); + } + + data.Add((byte)labels[i].Length); + data.AddRange(labels[i]); + } + + data.Add(0); + + static byte ToLowerAscii(byte value) => value is >= (byte)'A' and <= (byte)'Z' ? (byte)(value | 0x20) : value; + } + + private static List TryEncodeName(string name) + { + try + { + return EncodeName(name); + } + catch (ArgumentException) + { + return null; + } + } + + /// + /// Converts a name in the escaped presentation format (see ) to its labels. + /// + /// The name is no valid DNS name. + private static List EncodeName(string name) + { + var labels = new List(); + var label = new List(); + var escaped = false; + var wireLength = 1; + // 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. + var text = EndsWithUnescapedDot(name) ? name : name + "."; + + for (var i = 0; i < text.Length; i++) + { + // A character (also a surrogate pair) as UTF-8; a lone surrogate is no valid text + if (char.IsSurrogate(text[i]) && !char.IsSurrogatePair(text, i)) + throw new ArgumentException("Invalid DNS name.", nameof(name)); + + var length = char.IsSurrogatePair(text, i) ? 2 : 1; + var bytes = Encoding.UTF8.GetBytes(text, i, length); + + if (escaped) + { + escaped = false; + + // \DDD: a byte in decimal (RFC 1035 presentation format, see ReadResponse), e.g. a Latin-1 label; + // above 255 it is no byte (invalid, not the digits as text) + if (i + 2 < text.Length && char.IsAsciiDigit(text[i]) && char.IsAsciiDigit(text[i + 1]) && + char.IsAsciiDigit(text[i + 2])) + { + var value = int.Parse(text.AsSpan(i, 3)); + + if (value > 255) + throw new ArgumentException("Invalid DNS name.", nameof(name)); + + label.Add((byte)value); + i += 2; + continue; + } + + label.AddRange(bytes); + } + else if (text[i] == '\\') + escaped = true; + else if (text[i] != '.') + label.AddRange(bytes); + else + { + if (label.Count is < 1 or > 63) + throw new ArgumentException("Invalid DNS label.", nameof(name)); + wireLength += label.Count + 1; + labels.Add([.. label]); + label.Clear(); + } + + i += length - 1; + } + + // Open escape or a last label without a dot (e.g. name\ becomes name\. with an escaped dot) + if (escaped || label.Count > 0 || wireLength > 255) + throw new ArgumentException("Invalid DNS name.", nameof(name)); + + return labels; + } + + 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; + } + + /// + /// Maximum size of a received packet: a multicast DNS packet must not exceed 9000 bytes (RFC 6762 17). Larger ones + /// are ignored, so a single device can't fill the cache with records of up to 64 KB. + /// + public const int MaxPacketSize = 9000; + + /// + /// Rejects malformed/truncated packets atomically, including invalid compression and RDATA lengths, and packets + /// larger than . + /// + public static IReadOnlyList ReadResponse(byte[] data, long ipv6ScopeId = 0) + { + if (data.Length > MaxPacketSize) + return []; + + try + { + var reader = new Reader(data); + reader.U16(); + var flags = reader.U16(); + // Response with opcode 0 and rcode 0. The TC bit is ignored in multicast responses (RFC 6762 18.5). + if ((flags & 0x8000) == 0 || (flags & 0x780F) != 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(); + // The most significant bit set: treated as zero (RFC 2181 8), e.g. not kept for 136 years + if ((ttl & 0x80000000) != 0) + ttl = 0; + 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())); + } + + /// + /// Converts a name in the escaped presentation format (e.g. the instance name "My\.Printer" or "B\252ro") to text + /// for display: the escapes are read back to bytes and decoded as UTF-8, or as Latin-1 if they are no valid + /// UTF-8 (e.g. "Büro" of an older device). If the text would contain control characters, the escaped name is + /// returned (nothing invisible is shown). + /// + public static string ToDisplayText(string name) + { + var bytes = new List(); + + for (var i = 0; i < name.Length; i++) + { + if (name[i] == '\\' && i + 1 < name.Length) + { + // \DDD (byte) or an escaped character + if (i + 3 < name.Length && char.IsAsciiDigit(name[i + 1]) && char.IsAsciiDigit(name[i + 2]) && + char.IsAsciiDigit(name[i + 3]) && int.Parse(name.AsSpan(i + 1, 3)) <= 255) + { + bytes.Add(byte.Parse(name.AsSpan(i + 1, 3))); + i += 3; + continue; + } + + i++; + } + + var length = char.IsSurrogatePair(name, i) ? 2 : 1; + bytes.AddRange(Encoding.UTF8.GetBytes(name, i, length)); + i += length - 1; + } + + string text; + + try + { + text = new UTF8Encoding(false, true).GetString([.. bytes]); + } + catch (DecoderFallbackException) + { + text = Encoding.Latin1.GetString([.. bytes]); + } + + return text.Any(char.IsControl) ? name : text; + } + + /// + /// Formats a label in the escaped presentation format: "\" and "." escaped. A label that is not valid UTF-8 (e.g. + /// Latin-1 of an older device) or contains a control character is kept with its bytes: printable ASCII as is, + /// other bytes as \DDD (decimal, RFC 1035), so the other records of the packet are not lost and a question for + /// the name asks for the same bytes (see ). + /// + private static string FormatLabel(byte[] data, int offset, int count) + { + try + { + var text = new UTF8Encoding(false, true).GetString(data, offset, count); + + if (!text.Any(char.IsControl)) + return text.Replace("\\", "\\\\").Replace(".", "\\."); + } + catch (DecoderFallbackException) + { + // Bytes, see below + } + + var label = new StringBuilder(); + + foreach (var value in data.AsSpan(offset, count)) + { + label.Append(value switch + { + (byte)'\\' => "\\\\", + (byte)'.' => "\\.", + >= 0x20 and < 0x7F => ((char)value).ToString(), + _ => $"\\{value:D3}" + }); + } + + return label.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(); + labels.Add(FormatLabel(data, position, length)); + 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..42e7f17b9b --- /dev/null +++ b/Source/NETworkManager.Models/Network/MDNSServiceCache.cs @@ -0,0 +1,588 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using log4net; +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 +{ + 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.", + "_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); + + // 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(); + // Browsed service types (normalized), empty = all (*) + private readonly HashSet _serviceTypes = new(StringComparer.Ordinal); + private readonly 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) + { + 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). + /// + 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) => $"{DNSNameComparer.ToLower(record.Name)}|{record.Type}|{record.Identity}"; + + private static (string Name, ushort Type) RRset(MDNSRecord record) => (DNSNameComparer.ToLower(record.Name), record.Type); + + // Hosts of the cached SRV records of the browsed services, with the number of SRV records (see IsBrowsed: the + // addresses of these hosts are cached when the cache is full) + private readonly Dictionary _browsedSrvTargets = new(DNSNameComparer.Instance); + + private void Set(string key, Entry entry) + { + if (_records.TryAdd(key, entry)) + { + var rrset = RRset(entry.Record); + + if (!_rrsets.TryGetValue(rrset, out var keys)) + _rrsets[rrset] = keys = new HashSet(StringComparer.Ordinal); + + keys.Add(key); + + if (entry.Record.Type == MDNSMessage.SRV && IsBrowsedInstance(entry.Record.Name)) + _browsedSrvTargets[entry.Record.Target] = _browsedSrvTargets.GetValueOrDefault(entry.Record.Target) + 1; + + Version++; + + return; + } + + // Same key = same owner, type and value; the flag can change + if (_records[key].Record.CacheFlush != entry.Record.CacheFlush) + Version++; + + _records[key] = entry; + } + + private void Remove(string key) + { + if (!_records.Remove(key, out var entry)) + return; + + _rowValues.Remove(key); + + var rrset = RRset(entry.Record); + + if (_rrsets.TryGetValue(rrset, out var keys) && keys.Remove(key) && keys.Count == 0) + _rrsets.Remove(rrset); + + // Only the SRV records counted by Set (of browsed instances) + if (entry.Record.Type == MDNSMessage.SRV && IsBrowsedInstance(entry.Record.Name) && + _browsedSrvTargets.TryGetValue(entry.Record.Target, out var count)) + { + if (count > 1) + _browsedSrvTargets[entry.Record.Target] = count - 1; + else + _browsedSrvTargets.Remove(entry.Record.Target); + } + + Version++; + } + + /// + /// Adds the records of a response. Expired records are removed by the Get methods (once per tick of the browser, + /// not per packet). + /// + public void ProcessResponse(byte[] message, DateTimeOffset now, long ipv6ScopeId = 0) + { + // 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); + + Packets++; + + if (records.Count == 0) + PacketsWithoutRecords++; + + // Hosts of the SRV records of browsed services in this packet (an address can come before its SRV record), + // only read if the cache is full (see IsBrowsed); the cached ones are kept in _browsedSrvTargets + HashSet packetSrvTargets = null; + + HashSet GetPacketSrvTargets() => packetSrvTargets ??= records + .Where(x => x.Type == MDNSMessage.SRV && IsBrowsedInstance(x.Name)).Select(x => x.Target) + .ToHashSet(DNSNameComparer.Instance); + + // RRsets with a cache-flush record of this packet that was cached (not if the cache is full: the old values are + // kept instead of losing the RRset) + HashSet<(string Name, ushort Type)> flushedRRsets = null; + + 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)) }; + } + // Full: records of the browsed services are still cached (up to twice the limit), so other traffic of the + // link (reverse names, other services) can't hide them + else if (_records.ContainsKey(key) || _records.Count < MaxRecords || + _records.Count < MaxRecords * 2 && IsBrowsed(record, GetPacketSrvTargets)) + { + Set(key, new Entry(record, now, now.AddSeconds(record.TTL))); + + if (record.CacheFlush) + (flushedRRsets ??= []).Add(RRset(record)); + } + else if (RecordsNotCached++ == 0) + Log.Warn($"mDNS cache on \"{_networkInterface}\" is full ({MaxRecords} records), new records of other services are ignored until others expire."); + } + + if (flushedRRsets == null) + return; + + // A cache-flush RRset may span packets. Give older values one second's grace, and preserve values received in + // the same second (RFC 6762 section 10.2), e.g. the ones of this packet; a goodbye is also held for one second. + foreach (var rrset in flushedRRsets) + { + foreach (var key in _rrsets[rrset]) + { + var old = _records[key]; + + if (now - old.Received >= TimeSpan.FromSeconds(1)) + _records[key] = old with { Expires = Min(old.Expires, now.AddSeconds(1)) }; + } + } + } + + /// + /// Checks if a record belongs to the browsed services: PTR of a browsed type (or of the service type + /// enumeration with *), SRV / TXT of an instance of a browsed type, A / AAAA of a host of such an SRV record + /// (cached or in the packet). + /// + private bool IsBrowsed(MDNSRecord record, Func> getPacketSrvTargets) + { + switch (record.Type) + { + case MDNSMessage.PTR: + if (BrowsesAll && DNSNameComparer.Instance.Equals(record.Name, MDNSServiceType.Enumeration)) + return true; + + return MDNSServiceType.TryNormalize(record.Name, out var type) && type != "*" && + (BrowsesAll || _serviceTypes.Contains(type)); + case MDNSMessage.SRV: + case MDNSMessage.TXT: + return IsBrowsedInstance(record.Name); + case MDNSMessage.A: + case MDNSMessage.AAAA: + return _browsedSrvTargets.ContainsKey(record.Name) || getPacketSrvTargets().Contains(record.Name); + default: + return false; + } + } + + /// + /// Checks if a name is an instance of a browsed type: the instance is the first label, the rest of the name is + /// its type. + /// + private bool IsBrowsedInstance(string name) + { + var separator = FirstUnescapedDot(name); + + return separator > 0 && MDNSServiceType.TryNormalize(name[(separator + 1)..], out var type) && type != "*" && + (BrowsesAll || _serviceTypes.Contains(type)); + } + + /// + /// Gets the index of the first dot that separates labels (not escaped by a backslash), -1 if there is none. + /// + private static int FirstUnescapedDot(string name) + { + for (var i = 0; i < name.Length; i++) + { + if (name[i] == '\\') + i++; // escaped character + else if (name[i] == '.') + return i; + } + + return -1; + } + + private static DateTimeOffset Min(DateTimeOffset first, DateTimeOffset second) => first < second ? first : second; + + // Time of the last Expire: the browser and the Get methods expire with the same time of a tick, only once + private DateTimeOffset _lastExpire = DateTimeOffset.MinValue; + + /// + /// Removes the expired records (also done by the Get methods). Records added since expire later than their + /// time of receipt (at least one second), so a second call with the same time has nothing to do. + /// + public void Expire(DateTimeOffset now) + { + if (now == _lastExpire) + return; + + _lastExpire = now; + + foreach (var key in _records.Where(x => x.Value.Expires <= now).Select(x => x.Key).ToArray()) + Remove(key); + } + + // Derived from the cached records (see UpdateDerived): only rebuilt when the cache changed (Version), not for + // every tick of the browser and every snapshot + private long _derivedVersion = -1; + private (string Key, string Type)[] _instanceKeys = []; + private Dictionary<(string Name, ushort Type), string> _wanted = []; + + /// + /// PTR records of the browsed service types that point to an instance of the type, with the normalized type + /// (the owner name of the record can differ, e.g. without ".local." or with spaces, see + /// ). + /// + private IEnumerable<(Entry Entry, string Type)> Instances + { + get + { + UpdateDerived(); + + // The current entries (TTL): a record that is announced again keeps its key, but gets a new entry + return _instanceKeys.Select(x => (_records[x.Key], x.Type)); + } + } + + /// + /// Gets the cached records of an RRset (name, type). + /// + private IEnumerable GetEntries(string name, ushort type) => + _rrsets.TryGetValue((DNSNameComparer.ToLower(name), type), out var keys) ? keys.Select(x => _records[x]) : []; + + /// + /// Rebuilds the instances and the wanted questions (and removes the questions no longer wanted) if the cache + /// changed since the last call. Every change of the records that matters here (added, value replaced, removed) + /// increments . + /// + private void UpdateDerived() + { + if (_derivedVersion == Version) + return; + + _derivedVersion = Version; + + _instanceKeys = _records + .Select(x => (x.Key, Entry: x.Value, + Type: x.Value.Record.Type == MDNSMessage.PTR && MDNSServiceType.TryNormalize(x.Value.Record.Name, out var type) + ? type + : null)) + .Where(x => x.Type != null && x.Type != "*" && (BrowsesAll || _serviceTypes.Contains(x.Type)) && + IsInstanceOf(x.Entry.Record.Target, x.Type)) + .Select(x => (x.Key, x.Type)).ToArray(); + + var wanted = new Dictionary<(string Name, ushort Type), string>(); + void Add(string name, ushort type) => wanted.TryAdd((DNSNameComparer.ToLower(name), type), name); + if (BrowsesAll) + { + Add(MDNSServiceType.Enumeration, MDNSMessage.PTR); + foreach (var type in CommonServiceTypes) + Add(type, MDNSMessage.PTR); + foreach (var record in GetEntries(MDNSServiceType.Enumeration, MDNSMessage.PTR)) + if (MDNSServiceType.TryNormalize(record.Record.Target, out var type) && type != "*") + Add(type, MDNSMessage.PTR); + } + else + foreach (var type in _serviceTypes) + Add(type, MDNSMessage.PTR); + + foreach (var instance in _instanceKeys.Select(x => _records[x.Key].Record.Target)) + { + Add(instance, MDNSMessage.SRV); + Add(instance, MDNSMessage.TXT); + + foreach (var srv in GetEntries(instance, MDNSMessage.SRV)) + { + // In .local (an unescaped dot before "local.": "host\\.local." is one label under the root) + if (!IsInstanceOf(srv.Record.Target, "local.")) + continue; + Add(srv.Record.Target, MDNSMessage.A); + Add(srv.Record.Target, MDNSMessage.AAAA); + } + } + + _wanted = wanted; + + foreach (var key in _questions.Keys.Where(x => !wanted.ContainsKey(x)).ToArray()) + _questions.Remove(key); + } + + /// + /// Checks if a name (escaped presentation format) is an instance of the type: "<instance>.<type>" with an + /// unescaped dot before the type - "x\._ipp._tcp.local." is the label "x._ipp" in "_tcp.local.", not an instance + /// of "_ipp._tcp.local.". + /// + private static bool IsInstanceOf(string name, string type) + { + if (name.Length <= type.Length + 1 || !DNSNameComparer.EndsWith(name, "." + type)) + return false; + + // An even number of backslashes before the dot escape each other, not the dot + var backslashes = 0; + for (var i = name.Length - type.Length - 2; i >= 0 && name[i] == '\\'; i--) + backslashes++; + + return backslashes % 2 == 0; + } + + /// Maximum interval of a repeated question in seconds (RFC 6762 5.2: 60 minutes). + private const int MaxQuestionInterval = 3600; + + /// + /// Returns at most 256 due questions per tick (RFC 6762 5.2). The interval of a question doubles from 1 second + /// up to . An answered question is asked again at 80 % of the remaining TTL of + /// its records (refresh before they expire): SRV / TXT / A / AAAA (one answer) only then, PTR (several + /// answers, new instances can appear) also on its interval. + /// + public IReadOnlyList<(string Name, ushort Type)> GetQuestions(DateTimeOffset now) + { + Expire(now); + UpdateDerived(); + + var due = new List<(string Name, ushort Type)>(); + foreach (var (key, name) in _wanted) + { + // Not due yet (most questions on most ticks): checked first, the records are only read for due ones + if (_questions.TryGetValue(key, out var question) && question.Next > now) + continue; + + // The key is the RRset of the question (lowercase name, type) + var cached = _rrsets.TryGetValue(key, out var keys) ? keys.Select(x => _records[x]).ToArray() : []; + + // An answered SRV / TXT / A / AAAA question only from 80 % of the TTL of its records (also if it was + // scheduled earlier, before the answer arrived) + if (key.Type != MDNSMessage.PTR && cached.Length > 0 && + cached.Min(x => x.Received + (x.Expires - x.Received) * 0.8) > now) + continue; + if (due.Count == 256) + break; + due.Add((name, key.Type)); + var interval = Math.Min(MaxQuestionInterval, question == null ? 1 : question.Interval * 2); + double next = interval; + + if (cached.Length > 0) + { + // Refresh the records before they expire (also when the interval is longer) + var refresh = cached.Min(x => (x.Expires - now).TotalSeconds) * 0.8; + + next = key.Type == MDNSMessage.PTR ? Math.Min(interval, refresh) : refresh; + } + + _questions[key] = new Question(now.AddSeconds(Math.Max(1, next)), interval); + } + return due; + } + + /// + /// Gets the known answers of a question (RFC 6762 7.1): the cached PTR records of the name with more than half of + /// their TTL remaining, so the responders don't send them again. Other questions are only asked when their + /// records are about to expire (see ), so they have none. + /// + /// Name of the question. + /// Type of the question. + /// Current time. + /// Targets and remaining TTLs (seconds). + public IReadOnlyList<(string Target, uint TTL)> GetKnownAnswers(string name, ushort type, DateTimeOffset now) + { + if (type != MDNSMessage.PTR || !_rrsets.TryGetValue((DNSNameComparer.ToLower(name), type), out var keys)) + return []; + + return keys.Select(x => _records[x]) + .Where(x => (x.Expires - now).TotalSeconds > x.Record.TTL / 2.0) + .Select(x => (x.Record.Target, (uint)(x.Expires - now).TotalSeconds)).ToArray(); + } + + /// Creates detached snapshots, including instances whose SRV/address resolution is still pending. + public IReadOnlyList GetServices(DateTimeOffset now) + { + Expire(now); + var result = new List(); + foreach (var (instance, type) in Instances) + { + var fullName = instance.Record.Target; + var srv = GetEntries(fullName, MDNSMessage.SRV).MaxBy(x => x.Received); + var txt = GetEntries(fullName, MDNSMessage.TXT).MaxBy(x => x.Received); + var addresses = srv == null + ? [] + : GetEntries(srv.Record.Target, MDNSMessage.A).Concat(GetEntries(srv.Record.Target, MDNSMessage.AAAA)) + // Not an A / AAAA record with another length (kept as raw data, see MDNSMessage.ReadResponse) + .Where(x => x.Record.Address != null) + .Select(x => x.Record.Address.ToString()).Distinct().Order().ToArray(); + // Without the type (its normalized length, matched by Instances), as text (escapes decoded) + var name = MDNSMessage.ToDisplayText(fullName[..^(type.Length + 1)]); + result.Add(new MDNSServiceInfo(fullName, name, type, _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; + } + + /// + /// Maximum number of rows of : as many as the cache can hold (see + /// ), TXT strings are rows of their own. + /// + public const int MaxRecordRows = MaxRecords * 2; + + /// + /// One row per resource record, with each character string of a TXT record on its own row, in the order of the + /// keys. At most rows: above, the records of the browsed services are kept first, so + /// every service has its records. The same rows are shown in every snapshot. + /// + public IReadOnlyList GetRecords(DateTimeOffset now) + { + Expire(now); + UpdateRecordRows(); + + // Only the TTL (and the current record of a key, e.g. its cache-flush flag) changes between snapshots + var rows = new List(_recordRowCount); + + foreach (var (key, count) in _recordRows) + { + var entry = _records[key]; + var values = _rowValues[key]; + var ttl = (uint)Math.Max(0, Math.Ceiling((entry.Expires - now).TotalSeconds)); + + for (var i = 0; i < count; i++) + rows.Add(new MDNSRecordInfo(values.Ids[i], entry.Record.Name, values.Type, values.Values[i], + _networkInterface, entry.Record.CacheFlush, ttl)); + } + + return rows; + } + + // Records of GetRecords in their order with the number of rows shown (a TXT record above the limit partly): only + // rebuilt when the cache changed (Version), not for every snapshot + private long _recordRowsVersion = -1; + private (string Key, int Count)[] _recordRows = []; + private int _recordRowCount; + + /// + /// Rebuilds if the cache changed: all rows in the order of the keys, or above + /// the rows of the browsed services first, then the others as long as there is + /// room - shown in the order of the keys too. + /// + private void UpdateRecordRows() + { + if (_recordRowsVersion == Version) + return; + + _recordRowsVersion = Version; + + var records = _records.OrderBy(x => x.Key, StringComparer.Ordinal) + .Select(x => (x.Key, x.Value.Record, Rows: GetRowValues(x.Key, x.Value.Record).Values.Length)).ToArray(); + var counts = records.Select(x => x.Rows).ToArray(); + + if (counts.Sum() > MaxRecordRows) + { + var noPacketSrvTargets = new HashSet(); + var browsed = records.Select(x => IsBrowsed(x.Record, () => noPacketSrvTargets)).ToArray(); + var room = MaxRecordRows; + + foreach (var i in Enumerable.Range(0, records.Length).OrderBy(i => browsed[i] ? 0 : 1)) + { + counts[i] = Math.Min(room, records[i].Rows); + room -= counts[i]; + } + } + + _recordRows = records.Select((x, i) => (x.Key, Count: counts[i])).Where(x => x.Count > 0).ToArray(); + _recordRowCount = _recordRows.Sum(x => x.Count); + } + + /// + /// Gets the type, values and IDs of the rows of a record, formatted once per record (not for every snapshot, + /// e.g. the hex of a large record of an unknown type). + /// + private RowValues GetRowValues(string key, MDNSRecord record) + { + if (!_rowValues.TryGetValue(key, out var values)) + _rowValues[key] = values = CreateRowValues(key, record); + + return values; + } + + // Type, values and IDs of the rows of a record (see GetRecords), by key: the same key has the same values + private sealed record RowValues(string Type, string[] Values, string[] Ids); + + private readonly Dictionary _rowValues = new(StringComparer.Ordinal); + + private static RowValues CreateRowValues(string key, MDNSRecord 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()] + }; + + return new RowValues(type, values, values.Select((_, index) => $"{key}|{index}").ToArray()); + } +} diff --git a/Source/NETworkManager.Models/Network/MDNSServiceInfo.cs b/Source/NETworkManager.Models/Network/MDNSServiceInfo.cs new file mode 100644 index 0000000000..560f6c4200 --- /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; + } + + /// + /// Takes the values of a newer snapshot. Only changed properties are raised: live filtering re-filters a row + /// only for its filtered properties (not every second for the TTL countdown). + /// + public void UpdateFrom(MDNSServiceInfo value) + { + if (Hostname != value.Hostname) { Hostname = value.Hostname; OnPropertyChanged(nameof(Hostname)); } + if (Port != value.Port) { Port = value.Port; OnPropertyChanged(nameof(Port)); } + if (Priority != value.Priority) { Priority = value.Priority; OnPropertyChanged(nameof(Priority)); } + if (Weight != value.Weight) { Weight = value.Weight; OnPropertyChanged(nameof(Weight)); } + if (Addresses != value.Addresses) { Addresses = value.Addresses; OnPropertyChanged(nameof(Addresses)); } + if (TXTRecords != value.TXTRecords) { TXTRecords = value.TXTRecords; OnPropertyChanged(nameof(TXTRecords)); } + if (TTL != value.TTL) { TTL = value.TTL; OnPropertyChanged(nameof(TTL)); } + } +} diff --git a/Source/NETworkManager.Models/Network/MDNSServiceTypeProfile.cs b/Source/NETworkManager.Models/Network/MDNSServiceTypeProfile.cs new file mode 100644 index 0000000000..8176398da9 --- /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 Discovery 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..9c97dfb320 --- /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 Discovery 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.Models/RunCommand/RunCommandArgument.cs b/Source/NETworkManager.Models/RunCommand/RunCommandArgument.cs index d3791215a3..57e32b43cd 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 Discovery). /// public enum RunCommandArgument { @@ -10,5 +10,6 @@ public enum RunCommandArgument Ports, DNSServer, Broadcast, - Subnet + Subnet, + Duration } 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..7b0120fe84 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 Discovery + 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; @@ -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..807838e473 100644 --- a/Source/NETworkManager.Settings/SettingsInfo.cs +++ b/Source/NETworkManager.Settings/SettingsInfo.cs @@ -4019,6 +4019,103 @@ public ExportFileType DiscoveryProtocol_ExportFileType #endregion + #region mDNS Discovery + + public string MDNSDiscovery_ServiceType + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = 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; + 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 @@ -4748,6 +4845,10 @@ public SettingsInfo() // SNTP Lookup SNTPLookup_SNTPServers.CollectionChanged += CollectionChanged; + // mDNS Discovery + MDNSDiscovery_ServiceTypeHistory.CollectionChanged += CollectionChanged; + MDNSDiscovery_ServiceTypeProfiles.CollectionChanged += CollectionChanged; + // Wake on LAN WakeOnLan_MACAddressHistory.CollectionChanged += CollectionChanged; WakeOnLan_BroadcastHistory.CollectionChanged += CollectionChanged; @@ -4804,4 +4905,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..ecd461ab0a 100644 --- a/Source/NETworkManager.Settings/SettingsManager.cs +++ b/Source/NETworkManager.Settings/SettingsManager.cs @@ -494,6 +494,10 @@ public static void Upgrade(Version fromVersion, Version toVersion) if (fromVersion < new Version(2026, 7, 7, 0)) UpgradeTo_2026_7_7_0(); + // 2026.11.15.0 + if (fromVersion < new Version(2026, 11, 15, 0)) + UpgradeTo_2026_11_15_0(); + // Latest if (fromVersion < toVersion) UpgradeToLatest(toVersion); @@ -738,12 +742,11 @@ private static void UpgradeTo_2026_7_7_0() } /// - /// Method to apply changes for the latest version. + /// Method to apply changes for version 2026.11.15.0. /// - /// Latest version. - private static void UpgradeToLatest(Version version) + private static void UpgradeTo_2026_11_15_0() { - Log.Info($"Apply upgrade to {version}..."); + Log.Info("Apply upgrade to 2026.11.15.0..."); // Add RDAP application if (Current.General_ApplicationList.All(x => x.Name != ApplicationName.RDAP)) @@ -916,5 +919,35 @@ .. Current } #pragma warning restore CS0618 } + + /// + /// Method to apply changes for the latest version. + /// + /// Latest version. + private static void UpgradeToLatest(Version version) + { + Log.Info($"Apply upgrade to {version}..."); + + // Add mDNS Discovery application + if (Current.General_ApplicationList.All(x => x.Name != ApplicationName.MDNSDiscovery)) + { + Log.Info($"Add new app {nameof(ApplicationName.MDNSDiscovery)}."); + + var defaultList = ApplicationManager.GetDefaultList().ToList(); + + Current.General_ApplicationList.Insert( + Math.Min(defaultList.FindIndex(x => x.Name == ApplicationName.MDNSDiscovery), + Current.General_ApplicationList.Count), + defaultList.First(x => x.Name == ApplicationName.MDNSDiscovery)); + } + + // mDNS Discovery - 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/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..a3c63f8e58 --- /dev/null +++ b/Source/NETworkManager.Tests/Network/MDNSDiscoveryTests.cs @@ -0,0 +1,906 @@ +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.")] + [InlineData("_1a-2._tcp", "_1a-2._tcp.local.")] + [InlineData("_a._udp", "_a._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("_ipp-._tcp")] + [InlineData("_1-2._tcp")] + [InlineData("_ipp._tcp.local.local")] + [InlineData("_1234567890123456._tcp")] + [InlineData("_http._tcp;_ipp._tcp")] + [InlineData("_Kerberos._tcp")] // Kelvin sign, not "k" + 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]); + } + + [Theory] + [InlineData(new byte[] { 0x42, 0xFC, 0x72, 0x6F }, "B\\252ro")] // Latin-1 "Büro", not valid UTF-8 + [InlineData(new byte[] { 0x61, 0x01, 0x62 }, "a\\001b")] // control character + [InlineData(new byte[] { 0x61, 0x2E, 0xFF }, "a\\.\\255")] // dot and invalid byte + public void KeepsLabelsThatAreNoUTF8TextAsBytesAndTheOtherRecords(byte[] label, string expected) + { + var instance = new byte[] { (byte)label.Length }.Concat(label).Concat(Name(Type)).ToArray(); + var records = MDNSMessage.ReadResponse(Packet(new Record(Type, 12, instance), Address())); + + // The other records of the packet are not lost + Assert.Equal(2, records.Count); + Assert.Equal(expected + "." + Type, records[0].Target); + + // A question for the name asks for the same bytes + Assert.Equal(instance, MDNSMessage.CreateQuery(records[0].Target, 33)[12..^4]); + } + + [Theory] + [InlineData(@"My\.Printer", "My.Printer")] + [InlineData(@"x\\", @"x\")] + [InlineData(@"B\252ro", "Büro")] // Latin-1 (no valid UTF-8) + [InlineData(@"B\195\188ro", "Büro")] // UTF-8 bytes + [InlineData(@"a\001b", @"a\001b")] // control character: kept escaped + [InlineData("Büro", "Büro")] + public void InstanceNamesAreShownAsText(string name, string expected) => + Assert.Equal(expected, MDNSMessage.ToDisplayText(name)); + + [Fact] + public void ServiceNameOfALatin1InstanceIsShownAsText() + { + var cache = new MDNSServiceCache(Type, "Ethernet"); + cache.ProcessResponse(Packet(new Record(Type, 12, [4, 0x42, 0xFC, 0x72, 0x6F, .. Name(Type)])), Now); + var service = Assert.Single(cache.GetServices(Now)); + Assert.Equal("Büro", service.Name); + Assert.Equal(@"B\252ro." + Type, service.FullName); // technical name: escaped + } + + [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 VersionChangesOnlyWhenTheCacheChanges() + { + var cache = new MDNSServiceCache(Type, "Ethernet"); + cache.ProcessResponse(Packet(Ptr(2)), Now); + var version = cache.Version; + cache.ProcessResponse(Packet(Ptr(2)), Now.AddSeconds(1)); // announced again + Assert.Equal(version, cache.Version); + cache.ProcessResponse(Packet(Srv()), Now.AddSeconds(1)); + Assert.NotEqual(version, version = cache.Version); + cache.Expire(Now.AddSeconds(3)); // PTR expired + Assert.NotEqual(version, cache.Version); + Assert.Empty(cache.GetServices(Now.AddSeconds(3))); + } + + [Fact] + public void IgnoresTheTruncatedBitOfResponses() + { + var packet = Packet(Ptr()); + packet[2] |= 0x02; // TC + Assert.Single(MDNSMessage.ReadResponse(packet)); + } + + [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))); + } + + [Theory] + [InlineData(" _ipp._tcp.local.")] // spaces are allowed in a label, the type is trimmed + [InlineData("_ipp._tcp.")] // without .local. + [InlineData("_IPP._TCP.LOCAL.")] + public void InstanceNameIsCutByTheNormalizedType(string owner) + { + var cache = new MDNSServiceCache(Type, "Ethernet"); + cache.ProcessResponse(Packet(new Record(owner, 12, Name(Instance))), Now); + var service = Assert.Single(cache.GetServices(Now)); + Assert.Equal("Office Printer", service.Name); + Assert.Equal(Type, service.ServiceType); + } + + [Fact] + public void EscapedDotBeforeTheTypeIsNoInstance() + { + var cache = new MDNSServiceCache(Type, "Ethernet"); + // Labels "x._ipp", "_tcp", "local" (the dot is part of the first label) + cache.ProcessResponse(Packet(new Record(Type, 12, Labels("x._ipp", "_tcp", "local"))), Now); + Assert.Empty(cache.GetServices(Now)); + // Labels "x\", "_ipp", "_tcp", "local": an instance named "x\" (escaped backslash, then a real dot) + cache.ProcessResponse(Packet(new Record(Type, 12, Labels("x\\", "_ipp", "_tcp", "local"))), Now); + Assert.Equal("x\\", Assert.Single(cache.GetServices(Now)).Name); + } + + [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() + { + 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"); + // Two TXT records with more empty strings than rows can be shown (packets up to 9000 bytes) + cache.ProcessResponse(Packet(new Record(Instance, 16, new byte[8000])), Now); + cache.ProcessResponse(Packet(new Record("Other._ipp._tcp.local.", 16, new byte[8000])), Now); + var rows = cache.GetRecords(Now); + Assert.Equal(MDNSServiceCache.MaxRecordRows, 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)); + } + + // Query building + + [Theory] + [InlineData("a\\256b.local.")] // \DDD above 255 + [InlineData("a\\999.local.")] + [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 CreateQueryRejectsLoneSurrogates() + { + // In code: InlineData strings are stored as UTF-8 (a lone surrogate would arrive as U+FFFD) + Assert.Throws(() => MDNSMessage.CreateQuery("a\uD800.local.", 12)); // would take the dot + Assert.Throws(() => MDNSMessage.CreateQuery("a\uDC00.local.", 12)); + Assert.Equal(Labels("a\U0001F5A8", "local"), MDNSMessage.CreateQuery("a\U0001F5A8.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)); + + private static int Count(byte[] packet, int offset) => (packet[offset] << 8) | packet[offset + 1]; + + // The known answers of a query, read like a response (QR bit set) + private static IReadOnlyList KnownAnswers(byte[] query) + { + var response = query.ToArray(); + response[2] = 0x84; + return MDNSMessage.ReadResponse(response); + } + + [Fact] + public void QueriesContainSeveralQuestionsWithCompressedNames() + { + var packet = Assert.Single(MDNSMessage.CreateQueries([(Type, 12), ("_IPPS._tcp.local.", 12), (Instance, 33)])); + + Assert.Equal(3, Count(packet, 4)); + Assert.Equal(0, Count(packet, 6)); + // First name in full, "_tcp.local." of the second and the type of the instance as pointers + Assert.Equal(Name(Type), packet[12..(12 + Name(Type).Length)]); + Assert.Equal(12 + Name(Type).Length + 4 + 1 + 5 + 2 + 4 + 1 + 14 + 2 + 4, packet.Length); + } + + [Fact] + public void QueriesContainTheKnownAnswersAfterTheQuestions() + { + var packet = Assert.Single(MDNSMessage.CreateQueries([(Type, 12), (Instance, 33)], + (name, type) => type == 12 ? [(Instance, 100), ("Other._ipp._tcp.local.", 4000)] : [])); + + Assert.Equal(2, Count(packet, 4)); + Assert.Equal(2, Count(packet, 6)); + var answers = KnownAnswers(packet); + Assert.Equal(new[] { Instance, "Other._ipp._tcp.local." }, answers.Select(x => x.Target)); + Assert.All(answers, x => Assert.Equal((Type, (ushort)12, false), (x.Name, x.Type, x.CacheFlush))); + Assert.Equal(new uint[] { 100, 4000 }, answers.Select(x => x.TTL)); + } + + [Fact] + public void QueriesAreSplitIntoPacketsThatFitTheMinimumIPv6MTU() + { + var questions = Enumerable.Range(0, 100) + .Select(i => ($"Printer {i} on the second floor._ipp._tcp.local.", (ushort)33)).ToArray(); + var packets = MDNSMessage.CreateQueries(questions); + + Assert.True(packets.Count > 1); + Assert.All(packets, x => Assert.True(x.Length <= MDNSMessage.MaxQuerySize)); + Assert.Equal(100, packets.Sum(x => Count(x, 4))); + } + + private static bool IsTruncated(byte[] packet) => (packet[2] & 0x02) != 0; + + [Fact] + public void KnownAnswersThatDoNotFitFollowInPacketsWithTheTCBit() + { + var known = Enumerable.Range(0, 200).Select(i => ($"Printer {i}._ipp._tcp.local.", 120u)).ToArray(); + var packets = MDNSMessage.CreateQueries([(Type, 12), (Instance, 33)], (_, type) => type == 12 ? known : []); + + // The PTR question with known answers, packets with only known answers, then the next question + Assert.True(packets.Count > 3); + Assert.All(packets, x => Assert.True(x.Length <= MDNSMessage.MaxQuerySize)); + var question = packets.Take(packets.Count - 1).ToArray(); + Assert.Equal(1, Count(question[0], 4)); + Assert.All(question.Skip(1), x => Assert.Equal(0, Count(x, 4))); + + // TC bit on all but the last packet of the question, every known answer once + Assert.All(question[..^1], x => Assert.True(IsTruncated(x))); + Assert.False(IsTruncated(question[^1])); + Assert.Equal(known.Select(x => x.Item1).Order(), question.SelectMany(KnownAnswers).Select(x => x.Target).Order()); + Assert.All(question.SelectMany(KnownAnswers), x => Assert.Equal((Type, (ushort)12, 120u), (x.Name, x.Type, x.TTL))); + + Assert.Equal(1, Count(packets[^1], 4)); + Assert.Equal(0, Count(packets[^1], 6)); + Assert.False(IsTruncated(packets[^1])); + } + + [Fact] + public void KnownAnswersOfAQuestionUseAtMostMaxKnownAnswerPackets() + { + var known = Enumerable.Range(0, 5000).Select(i => ($"Printer {i}._ipp._tcp.local.", 120u)).ToArray(); + var packets = MDNSMessage.CreateQueries([(Type, 12)], (_, _) => known); + + Assert.Equal(MDNSMessage.MaxKnownAnswerPackets, packets.Count); + Assert.False(IsTruncated(packets[^1])); // no more known answers follow + Assert.InRange(packets.Sum(x => Count(x, 6)), 100, 4999); + } + + [Fact] + public void KnownAnswersArePTRRecordsWithMoreThanHalfOfTheirTTL() + { + var cache = new MDNSServiceCache(Type, "Ethernet"); + cache.ProcessResponse(Packet(Ptr(120), Srv()), Now); + + Assert.Equal(new[] { (Instance, 61u) }, cache.GetKnownAnswers("_IPP._tcp.local.", 12, Now.AddSeconds(59))); + Assert.Empty(cache.GetKnownAnswers(Type, 12, Now.AddSeconds(61))); + Assert.Empty(cache.GetKnownAnswers(Instance, 33, Now)); + } + + // 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); + } + + [Fact] + public void TTLsWithTheMostSignificantBitSetAreZero() + { + Assert.Equal((uint)0, Assert.Single(MDNSMessage.ReadResponse(Packet(Ptr(0xFFFFFFFF)))).TTL); + Assert.Equal((uint)int.MaxValue, Assert.Single(MDNSMessage.ReadResponse(Packet(Ptr(int.MaxValue)))).TTL); + + // Not cached (like a goodbye) + var cache = new MDNSServiceCache(Type, "Ethernet"); + cache.ProcessResponse(Packet(Ptr(0x80000000)), Now); + Assert.Empty(cache.GetServices(Now)); + } + + [Fact] + public void PacketsLargerThan9000BytesAreIgnored() + { + var packet = Packet(Ptr(), new Record(Instance, 16, new byte[9000])); + Assert.Empty(MDNSMessage.ReadResponse(packet)); + Assert.Single(MDNSMessage.ReadResponse(Packet(Ptr(), new Record(Instance, 16, new byte[8800]))), x => x.Type == 12); + } + + // 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(200)) + cache.ProcessResponse(Packet(chunk), Now); + + Assert.Equal(0, cache.RecordsNotCached); + // An address of a host without SRV record (other traffic of the link) is not cached + 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 records of a browsed service are still cached (SRV of the instance, then the address of its host) + cache.ProcessResponse(Packet(Srv()), Now); + cache.ProcessResponse(Packet(Address("192.168.1.99")), Now); + var service = Assert.Single(cache.GetServices(Now)); + Assert.Equal(Host, service.Hostname); + Assert.Contains("192.168.1.99", service.Addresses); + Assert.Equal(1, cache.RecordsNotCached); + + // The host of a service that is not browsed (SRV in the same packet) is not cached in the extra room + cache.ProcessResponse(Packet(new Record("Speaker._airplay._tcp.local.", 33, [0, 0, 0, 0, 0x1B, 0x58, .. Name("speaker.local.")]), + new Record("speaker.local.", 1, [192, 168, 1, 31])), Now); + Assert.Equal(3, cache.RecordsNotCached); + Assert.DoesNotContain(cache.GetRecords(Now), x => x.Value == "192.168.1.31"); + + // 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 InstanceNamesOnlyDifferingInTheCaseOfOtherThanAsciiLettersAreDifferentServices() + { + var cache = new MDNSServiceCache(Type, "Ethernet"); + cache.ProcessResponse(Packet(new Record(Type, 12, Labels("Büro", "_ipp", "_tcp", "local")), + new Record(Type, 12, Labels("BÜRO", "_ipp", "_tcp", "local")), + new Record(Type, 12, Labels("büro", "_IPP", "_TCP", "LOCAL"))), Now); // same as the first (ASCII case) + + var names = cache.GetServices(Now).Select(x => x.Name).ToArray(); + Assert.Equal(2, names.Length); + Assert.Contains("BÜRO", names); + } + + [Fact] + public void AddressRecordsWithAnInvalidLengthAreNoAddressesOfTheService() + { + var cache = new MDNSServiceCache(Type, "Ethernet"); + // A with 16 bytes and AAAA with 4 bytes: kept as raw data (no address) + cache.ProcessResponse(Packet(Ptr(), Srv(), Address(), new Record(Host, 1, new byte[16]), + new Record(Host, 28, [192, 168, 1, 21])), Now); + + Assert.Equal("192.168.1.20", Assert.Single(cache.GetServices(Now)).Addresses); + Assert.Contains(cache.GetRecords(Now), x => x.Type == "A" && x.Value.StartsWith("\\# 16")); + } + + [Fact] + public void AnnouncedAgainTheServiceAndItsQuestionsUseTheNewTTL() + { + var cache = new MDNSServiceCache(Type, "Ethernet"); + cache.ProcessResponse(Packet(Ptr(120), Srv()), Now); + Assert.Equal((uint)120, Assert.Single(cache.GetServices(Now)).TTL); + cache.GetQuestions(Now); + + // Same records again (the cache doesn't change its version), 60 s later + var version = cache.Version; + cache.ProcessResponse(Packet(Ptr(120), Srv()), Now.AddSeconds(60)); + Assert.Equal(version, cache.Version); + Assert.Equal((uint)120, Assert.Single(cache.GetServices(Now.AddSeconds(60))).TTL); + + // The SRV question at 80 % of the new TTL (60 + 96 s), not of the first one + Assert.DoesNotContain((Instance, (ushort)33), cache.GetQuestions(Now.AddSeconds(100))); + Assert.Contains((Instance, (ushort)33), cache.GetQuestions(Now.AddSeconds(156))); + } + + [Fact] + public void FullCacheKeepsTheOldValuesOfACacheFlushThatIsNotCached() + { + var cache = new MDNSServiceCache(Type, "Ethernet"); + var hosts = Enumerable.Range(0, MDNSServiceCache.MaxRecords) + .Select(i => new Record($"host{i}.local.", 1, [10, 0, (byte)(i >> 8), (byte)i])).ToArray(); + foreach (var chunk in hosts.Chunk(200)) + cache.ProcessResponse(Packet(chunk), Now); + + // New address of host0 with the cache-flush bit: not cached (full), the old one must not expire + cache.ProcessResponse(Packet(new Record("host0.local.", 1, [10, 9, 9, 9], Flush: true)), Now.AddSeconds(2)); + Assert.Equal(1, cache.RecordsNotCached); + Assert.Contains(cache.GetRecords(Now.AddSeconds(4)), x => x.Name == "host0.local." && x.Value == "10.0.0.0"); + } + + [Fact] + public void RecordRowsKeepTheRecordsOfTheBrowsedServicesWhenThereAreTooMany() + { + var cache = new MDNSServiceCache(Type, "Ethernet"); + cache.ProcessResponse(Packet(Ptr(), Srv(), Address()), Now); + + // TXT records of another service with more strings than rows can be shown (sorted before the printer) + var strings = Enumerable.Range(0, 3000).SelectMany(_ => new byte[] { 1, (byte)'a' }).ToArray(); + foreach (var name in new[] { "A", "B", "C" }) + cache.ProcessResponse(Packet(new Record($"{name}._airplay._tcp.local.", 16, strings)), Now); + + var rows = cache.GetRecords(Now); + Assert.Equal(MDNSServiceCache.MaxRecordRows, rows.Count); + Assert.Contains(rows, x => x.Name == Type && x.Type == "PTR"); + Assert.Contains(rows, x => x.Name == Instance && x.Type == "SRV"); + Assert.Contains(rows, x => x.Name == Host && x.Value == "192.168.1.20"); + // In the order of the records, the strings of a TXT record in their order (not "|10" before "|2") + var owners = rows.Select(x => x.Name).Distinct().ToArray(); + Assert.Equal(owners.OrderBy(DNSNameComparer.ToLower, StringComparer.Ordinal), owners); // key: lowercase name + Assert.Equal(Enumerable.Range(0, 3000).Select(i => i.ToString()), + rows.Where(x => x.Name == "A._airplay._tcp.local.").Select(x => x.Id.Split('|')[^1])); + } + + [Fact] + public void UnansweredQuestionsBackOffExponentially() + { + var cache = new MDNSServiceCache(Type, "Ethernet"); + var times = new List(); + for (var second = 0.0; second <= 300; second += 0.25) + if (cache.GetQuestions(Now.AddSeconds(second)).Count > 0) + times.Add(second); + + // The interval doubles (1, 2, 4, ... s), not capped at 60 seconds (RFC 6762 5.2: up to 60 minutes) + Assert.Equal(new[] { 0.0, 1, 3, 7, 15, 31, 63, 127, 255 }, times); + } + + [Fact] + public void AnsweredUniqueRecordsAreOnlyAskedAgainBeforeTheyExpire() + { + var cache = new MDNSServiceCache(Type, "Ethernet"); + cache.ProcessResponse(Packet(Ptr(4500)), Now); + Assert.Contains((Instance, (ushort)33), cache.GetQuestions(Now)); + cache.ProcessResponse(Packet(Srv()), Now); // TTL 120 + + var srvQuestions = new List(); + for (var second = 0.25; second <= 110; second += 0.25) + if (cache.GetQuestions(Now.AddSeconds(second)).Contains((Instance, (ushort)33))) + srvQuestions.Add(second); + + // Not on the backoff interval (1, 3, 7, ... s), only at 80 % of the TTL (96 s) + Assert.Equal(new[] { 96.0 }, srvQuestions); + } + + [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 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 NoAddressQuestionsForAHostWithAnEscapedDotBeforeLocal() + { + var cache = new MDNSServiceCache(Type, "Ethernet"); + // Target: one label "host.local" under the root, not in .local + cache.ProcessResponse(Packet(Ptr(), new Record(Instance, 33, [0, 0, 0, 0, 0, 80, .. Labels("host.local")])), Now); + Assert.DoesNotContain(cache.GetQuestions(Now), x => x.Type is 1 or 28); + } + + [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); + } +} 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.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.Tests/Utilities/DNSNameComparerTests.cs b/Source/NETworkManager.Tests/Utilities/DNSNameComparerTests.cs new file mode 100644 index 0000000000..4581227c19 --- /dev/null +++ b/Source/NETworkManager.Tests/Utilities/DNSNameComparerTests.cs @@ -0,0 +1,35 @@ +using NETworkManager.Utilities; +using Xunit; + +namespace NETworkManager.Tests.Utilities; + +public class DNSNameComparerTests +{ + [Theory] + [InlineData("Printer.local.", "printer.LOCAL.")] + [InlineData("B\u00fcro.local.", "b\u00fcro.local.")] + public void AsciiLettersAreComparedCaseInsensitively(string x, string y) + { + Assert.True(DNSNameComparer.Instance.Equals(x, y)); + Assert.Equal(DNSNameComparer.Instance.GetHashCode(x), DNSNameComparer.Instance.GetHashCode(y)); + } + + [Theory] + [InlineData("B\u00fcro.local.", "B\u00dcro.local.")] // u umlaut: only ASCII letters are folded + [InlineData("\u212a.local.", "k.local.")] // Kelvin sign + [InlineData("\u0131.local.", "i.local.")] // dotless i + [InlineData("a.local.", "a.local")] + public void OtherCharactersAreComparedExactly(string x, string y) => + Assert.False(DNSNameComparer.Instance.Equals(x, y)); + + [Fact] + public void ToLowerOnlyChangesAsciiLetters() => + Assert.Equal("office b\u00dcro.local.", DNSNameComparer.ToLower("Office B\u00dcRO.Local.")); + + [Theory] + [InlineData("Printer._IPP._tcp.local.", "._ipp._tcp.local.", true)] + [InlineData("Printer._ipp._tcp.local.", "._ipps._tcp.local.", false)] + [InlineData("local.", "x.local.", false)] + public void EndsWith(string name, string suffix, bool expected) => + Assert.Equal(expected, DNSNameComparer.EndsWith(name, suffix)); +} diff --git a/Source/NETworkManager.Utilities/DNSNameComparer.cs b/Source/NETworkManager.Utilities/DNSNameComparer.cs new file mode 100644 index 0000000000..fc6329ff09 --- /dev/null +++ b/Source/NETworkManager.Utilities/DNSNameComparer.cs @@ -0,0 +1,80 @@ +using System; +using System.Collections.Generic; + +namespace NETworkManager.Utilities; + +/// +/// Compares DNS names like DNS does: ASCII letters case-insensitively, all other characters (e.g. UTF-8 labels of +/// mDNS) exactly (RFC 4343, RFC 6762 16). Not or +/// : they also fold other letters, so e.g. "Büro" and "BÜRO" or the +/// Kelvin sign and "k" would be the same name. +/// +public sealed class DNSNameComparer : IEqualityComparer +{ + /// + /// Gets the comparer. + /// + public static DNSNameComparer Instance { get; } = new(); + + private DNSNameComparer() + { + } + + /// + /// Converts the ASCII letters of a name to lowercase (other characters are kept), e.g. for a key. + /// + /// DNS name. + /// Name with lowercase ASCII letters. + public static string ToLower(string name) + { + return string.Create(name.Length, name, static (span, value) => + { + for (var i = 0; i < value.Length; i++) + span[i] = ToLower(value[i]); + }); + } + + /// + /// Checks if a name ends with a suffix (e.g. a service type), see . + /// + /// DNS name. + /// Suffix. + /// True if the name ends with the suffix. + public static bool EndsWith(string name, string suffix) + { + return name.Length >= suffix.Length && SpanEquals(name.AsSpan(name.Length - suffix.Length), suffix); + } + + /// + public bool Equals(string x, string y) + { + if (ReferenceEquals(x, y)) + return true; + + return x != null && y != null && x.Length == y.Length && SpanEquals(x, y); + } + + /// + public int GetHashCode(string obj) + { + var hash = new HashCode(); + + foreach (var c in obj) + hash.Add(ToLower(c)); + + return hash.ToHashCode(); + } + + private static bool SpanEquals(ReadOnlySpan x, ReadOnlySpan y) + { + for (var i = 0; i < x.Length; i++) + { + if (ToLower(x[i]) != ToLower(y[i])) + return false; + } + + return true; + } + + private static char ToLower(char c) => char.IsAsciiLetterUpper(c) ? (char)(c | 0x20) : c; +} diff --git a/Source/NETworkManager.Utilities/MDNSServiceType.cs b/Source/NETworkManager.Utilities/MDNSServiceType.cs new file mode 100644 index 0000000000..b7676ac93c --- /dev/null +++ b/Source/NETworkManager.Utilities/MDNSServiceType.cs @@ -0,0 +1,31 @@ +using System; + +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 == null ? null : DNSNameComparer.ToLower(input.Trim().TrimEnd('.')); + 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 (!RegexHelper.MDNSServiceTypeRegex().IsMatch(value)) + return false; + + serviceType = value.EndsWith(".local", StringComparison.Ordinal) ? value + "." : value + ".local."; + return true; + } +} diff --git a/Source/NETworkManager.Utilities/RegexHelper.cs b/Source/NETworkManager.Utilities/RegexHelper.cs index 4e13deb629..a3d1be892d 100644 --- a/Source/NETworkManager.Utilities/RegexHelper.cs +++ b/Source/NETworkManager.Utilities/RegexHelper.cs @@ -291,6 +291,17 @@ public static partial class RegexHelper [GeneratedRegex(@"^[A-Za-z][A-Za-z0-9-]*=[^,]+(,\s*[A-Za-z][A-Za-z0-9-]*=[^,]+)*$")] public static partial Regex LdapSearchBaseRegex(); + /// + /// Provides a compiled regular expression that matches a DNS-SD service type in lowercase, with an optional + /// ".local" (without the final dot), e.g. "_ipp._tcp" or "_pdl-datastream._tcp.local". The service name is an + /// RFC 6335 service name: 1 - 15 letters, digits and hyphens, at least one letter, no hyphen at the start / end + /// and no consecutive hyphens. + /// + /// A instance that matches local DNS-SD service types. + [GeneratedRegex(@"^_(?=[a-z0-9-]*[a-z])(?![a-z0-9-]*--)[a-z0-9](?:[a-z0-9-]{0,13}[a-z0-9])?\._(?:tcp|udp)(?:\.local)?$", + RegexOptions.CultureInvariant)] + public static partial Regex MDNSServiceTypeRegex(); + // Match a hosts file entry with optional comments, supporting IPv4, IPv6, and hostnames // ^* : Matches the beginning of the line // (#)? : Optionally matches a comment (#) at the start of the line diff --git a/Source/NETworkManager.Validators/IsNameUnique.cs b/Source/NETworkManager.Validators/IsNameUnique.cs index 51e9309c31..b82b369ebb 100644 --- a/Source/NETworkManager.Validators/IsNameUnique.cs +++ b/Source/NETworkManager.Validators/IsNameUnique.cs @@ -6,13 +6,19 @@ namespace NETworkManager.Validators; +/// +/// Validates that a name is not used yet (case-insensitive). Leading / trailing spaces are ignored, like when a name +/// is found (e.g. a port profile in the ports input), so "Webserver " is a duplicate of "Webserver". +/// public class IsNameUnique : ValidationRule { public IsNameUniqueDependencyObjectWrapper Wrapper { get; set; } public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - return Wrapper.UsedNames.Any(x => x.Equals(value as string, StringComparison.OrdinalIgnoreCase)) + var name = (value as string)?.Trim(); + + return Wrapper.UsedNames.Any(x => string.Equals(x?.Trim(), name, StringComparison.OrdinalIgnoreCase)) ? new ValidationResult(false, Strings.ErrorMessage_NameIsAlreadyUsed) : ValidationResult.ValidResult; } diff --git a/Source/NETworkManager.Validators/MDNSServiceTypeProfileNameValidator.cs b/Source/NETworkManager.Validators/MDNSServiceTypeProfileNameValidator.cs new file mode 100644 index 0000000000..23f79758e6 --- /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 Discovery 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/MDNSServiceTypeValidator.cs b/Source/NETworkManager.Validators/MDNSServiceTypeValidator.cs new file mode 100644 index 0000000000..415bf35e94 --- /dev/null +++ b/Source/NETworkManager.Validators/MDNSServiceTypeValidator.cs @@ -0,0 +1,21 @@ +using System.Globalization; +using System.Windows.Controls; +using NETworkManager.Localization.Resources; +using NETworkManager.Models.Network; +using NETworkManager.Settings; + +namespace NETworkManager.Validators; + +/// +/// Validates the service type input of the mDNS Discovery tool (input field and run command): *, service +/// types and / or names of service type profiles separated by ";" (e.g. "Printers; _ssh._tcp"), see +/// . +/// +public sealed class MDNSServiceTypeValidator : ValidationRule +{ + public override ValidationResult Validate(object value, CultureInfo cultureInfo) => + MDNSServiceTypeProfile.TryResolve(value as string, SettingsManager.Current.MDNSDiscovery_ServiceTypeProfiles, + out _) + ? ValidationResult.ValidResult + : new ValidationResult(false, Strings.MDNSDiscovery_InvalidServiceType); +} diff --git a/Source/NETworkManager.Validators/MDNSServiceTypesValidator.cs b/Source/NETworkManager.Validators/MDNSServiceTypesValidator.cs new file mode 100644 index 0000000000..00864e8a64 --- /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 Discovery 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/ApplicationRequest.cs b/Source/NETworkManager/ApplicationRequest.cs index 7adc6d201f..9842db29ca 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 Discovery 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/InputSuggestions.cs b/Source/NETworkManager/InputSuggestions.cs index 630ec51630..d601875cb9 100644 --- a/Source/NETworkManager/InputSuggestions.cs +++ b/Source/NETworkManager/InputSuggestions.cs @@ -81,6 +81,30 @@ public static InputSuggestions ForPortScannerPorts() Strings.PortProfiles, SettingsManager.Current.PortScanner_PortHistory); } + /// + /// Creates the list for the service types of the mDNS Discovery 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, + GetMDNSDiscoveryServiceTypeProfiles, Strings.MDNSDiscovery_ServiceTypeProfiles, + SettingsManager.Current.MDNSDiscovery_ServiceTypeHistory); + } + + /// + /// Gets * (all service types, always first) and the service type profiles of the mDNS Discovery tool (sorted by + /// name), with their description - the same list in the input of the tool and in the run command. + /// + public static IEnumerable<(string Name, string Description)> GetMDNSDiscoveryServiceTypeProfiles() + { + return SettingsManager.Current.MDNSDiscovery_ServiceTypeProfiles + .OrderBy(x => x.Name, StringComparer.OrdinalIgnoreCase) + .Select(x => (x.Name, x.ServiceTypes)) + .Prepend(("*", Strings.MDNSDiscovery_AllServiceTypes)); + } + /// /// Creates the list for the DNS server of DNS Lookup: the DNS servers (Windows DNS first, then sorted by name, /// with their servers) and the DNS server history. diff --git a/Source/NETworkManager/MainWindow.xaml.cs b/Source/NETworkManager/MainWindow.xaml.cs index c19e372ffb..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()]; @@ -693,6 +694,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 +859,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 +1011,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..f8ad26d44b 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] }; /// @@ -120,6 +121,15 @@ public static IEnumerable GetPortProfiles() return SettingsManager.Current.PortScanner_PortProfiles; } + /// + /// Gets the durations of the mDNS Discovery 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. /// @@ -313,6 +323,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 }; @@ -338,6 +349,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) }; @@ -371,6 +383,18 @@ private static string ValidateDNSServer(string dnsServer) return invalidEntry == null ? null : string.Format(Strings.UnknownArgumentX, invalidEntry); } + /// + /// Validates the duration of the mDNS Discovery 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 @@ -427,6 +451,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) @@ -484,6 +513,9 @@ [.. 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), Argument(Strings.DurationS)], RunCommandArgument.Duration, + supportsProfile: false), ApplicationName.WakeOnLAN => Create(name, ["wol"], [Target(Strings.MACAddress), Argument(Strings.Broadcast)], RunCommandArgument.Broadcast), ApplicationName.SubnetCalculator => Create(name, ["subnet", "ipcalc"], diff --git a/Source/NETworkManager/RunCommandSuggestion.cs b/Source/NETworkManager/RunCommandSuggestion.cs index 57ce6dda23..099d14da87 100644 --- a/Source/NETworkManager/RunCommandSuggestion.cs +++ b/Source/NETworkManager/RunCommandSuggestion.cs @@ -38,6 +38,16 @@ public enum RunCommandSuggestionKind /// PortProfile, + /// + /// Service type profile of the mDNS Discovery tool (e.g. "Printers") or * (all service types). + /// + ServiceTypeProfile, + + /// + /// Duration of the mDNS Discovery 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/ScreenshotData.cs b/Source/NETworkManager/ScreenshotData.cs index 53ce5837f6..f14be1ef43 100644 --- a/Source/NETworkManager/ScreenshotData.cs +++ b/Source/NETworkManager/ScreenshotData.cs @@ -1,8 +1,12 @@ using System; using System.Collections.Generic; +using System.Linq; +using System.Net; using NETworkManager.Models.Cloudflare; using NETworkManager.Models.IPApi; +using NETworkManager.Models.Network; using NETworkManager.Settings; +using NETworkManager.Utilities; namespace NETworkManager; @@ -101,6 +105,86 @@ public static IPGeolocationResult CreateIPGeolocationResult() #endregion + #region mDNS Discovery + + /// + /// Creates the network interface of the mDNS Discovery tool (instead of the real adapters). + /// + public static IReadOnlyList CreateMDNSInterfaces() + { + return [new MDNSInterfaceInfo("screenshot", "Ethernet", IPAddress.Parse(ComputerIPv4), 12, 12)]; + } + + /// + /// Services of a home network: (instance, type, host, port, IPv4 address, TXT entries). + /// + private static readonly (string Instance, string Type, string Host, ushort Port, string IPv4, string[] Text)[] + MDNSServices = + [ + ("Office Printer", "_ipp._tcp", "office-printer", 631, "192.168.1.20", + ["txtvers=1", "ty=Example LaserJet 400", "rp=ipp/print", "pdl=application/pdf,image/urf", "Color=T", "Duplex=T"]), + ("Office Printer", "_ipps._tcp", "office-printer", 631, "192.168.1.20", + ["txtvers=1", "ty=Example LaserJet 400", "rp=ipp/print", "TLS=1.3"]), + ("Office Printer", "_uscan._tcp", "office-printer", 80, "192.168.1.20", + ["txtvers=1", "ty=Example LaserJet 400", "rs=eSCL", "vers=2.63", "is=platen,adf"]), + ("NAS", "_smb._tcp", "nas", 445, "192.168.1.40", []), + ("NAS", "_http._tcp", "nas", 5000, "192.168.1.40", ["path=/"]), + ("NAS", "_ssh._tcp", "nas", 22, "192.168.1.40", []), + ("Living Room TV", "_googlecast._tcp", "living-room-tv", 8009, "192.168.1.30", + ["md=Example TV", "fn=Living Room TV", "ca=465413", "st=0"]), + ("Living Room Speaker", "_airplay._tcp", "living-room-speaker", 7000, "192.168.1.31", + ["model=ExampleSpeaker1,1", "srcvers=770.8.1", "flags=0x4"]), + ("Router", "_http._tcp", "router", 80, RouterIPv4, ["path=/"]), + ("Hallway Light", "_hap._tcp", "hallway-light", 5541, "192.168.1.50", + ["c#=2", "md=Example Light", "sf=0", "ci=5"]) + ]; + + /// + /// Creates the services and the DNS records (PTR, SRV, TXT, A, AAAA and the service type enumeration) of the + /// mDNS Discovery tool, consistent with each other. + /// + public static MDNSDiscoverySnapshot CreateMDNSDiscoverySnapshot(string networkInterface) + { + const uint sharedTTL = 4498; // PTR (4500 s), announced a moment ago + const uint uniqueTTL = 118; // SRV / TXT / A / AAAA (120 s) + + var services = new List(); + var records = new List(); + + void AddRecord(string name, string type, string value, bool cacheFlush, uint ttl) => + records.Add(new MDNSRecordInfo($"screenshot|{records.Count}", name, type, value, networkInterface, cacheFlush, ttl)); + + foreach (var service in MDNSServices) + { + var type = service.Type + ".local."; + var fullName = $"{service.Instance}.{type}"; + var host = service.Host + ".local."; + var ipv6 = $"fe80::{service.IPv4.Split('.')[^1]}%12"; + + services.Add(new MDNSServiceInfo(fullName, service.Instance, type, networkInterface, host, service.Port, 0, 0, + $"{service.IPv4}; {ipv6}", string.Join(Environment.NewLine, service.Text), sharedTTL)); + + AddRecord(type, "PTR", fullName, false, sharedTTL); + AddRecord(fullName, "SRV", $"0 0 {service.Port} {host}", true, uniqueTTL); + + foreach (var text in service.Text.DefaultIfEmpty(string.Empty)) + AddRecord(fullName, "TXT", text, true, uniqueTTL); + } + + foreach (var service in MDNSServices.DistinctBy(x => x.Host)) + { + AddRecord(service.Host + ".local.", "A", service.IPv4, true, uniqueTTL); + AddRecord(service.Host + ".local.", "AAAA", $"fe80::{service.IPv4.Split('.')[^1]}%12", true, uniqueTTL); + } + + foreach (var type in MDNSServices.Select(x => x.Type + ".local.").Distinct()) + AddRecord(MDNSServiceType.Enumeration, "PTR", type, false, sharedTTL); + + return new MDNSDiscoverySnapshot(services, records); + } + + #endregion + #region Speed test /// diff --git a/Source/NETworkManager/ViewModels/MDNSDiscoverySettingsViewModel.cs b/Source/NETworkManager/ViewModels/MDNSDiscoverySettingsViewModel.cs new file mode 100644 index 0000000000..d41afd3d59 --- /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 Discovery 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/MDNSDiscoveryViewModel.cs b/Source/NETworkManager/ViewModels/MDNSDiscoveryViewModel.cs new file mode 100644 index 0000000000..b2480393c8 --- /dev/null +++ b/Source/NETworkManager/ViewModels/MDNSDiscoveryViewModel.cs @@ -0,0 +1,1214 @@ +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.Diagnostics; +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; + +/// +/// View model of the mDNS Discovery tool: browses the services advertised on the selected network interface +/// (see ) and shows them (Services) and the received DNS records (Records). +/// +public sealed class MDNSDiscoveryViewModel : ViewModelBase +{ + #region Variables + + private static readonly ILog Log = LogManager.GetLogger(typeof(MDNSDiscoveryViewModel)); + + /// + /// Maximum effort (changed rows x all rows) to add / remove rows one by one, like the Port Scanner: WPF inserts + /// every row into the sorted view with a linear search. Above, the rows are replaced with one reset. + /// + private const long MaxRowChangesOneByOne = 10_000_000; + + 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 IReadOnlyList _browseServiceTypes; + private MDNSServiceCache _browseCache; + private bool _isPaused; + + // The view is shown (OnViewVisible / OnViewHide): a pending resume is only done while it is shown + private bool _isViewVisible = true; + + // Request to fill in only (run command) that arrived while browsing: filled in when the browse has ended, so a + // running browse is not stopped and its input not changed (see OpenAsync) + private ApplicationRequest _pendingFillIn; + + // Number of the last request of OpenAsync (run command), see there + private int _openRequestId; + + // 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; + private readonly DispatcherTimer _flushTimer; + private readonly Stopwatch _browseStopwatch = new(); + + // Rows by key (service: full name, record: id), so a new snapshot updates the existing rows + private readonly Dictionary _serviceRows = new(DNSNameComparer.Instance); + private readonly Dictionary _recordRows = new(StringComparer.Ordinal); + + /// + /// Gets the network interfaces with multicast support. + /// + public ObservableCollection Interfaces { get; } = []; + + /// + /// Gets or sets the network interface to browse on. + /// + public MDNSInterfaceInfo SelectedInterface + { + get; + set + { + if (value == field) + return; + + field = value; + + // Another interface was selected: the message that the last used one is not available no longer applies + // (set again after the selection by SetInterfaces) + _showInterfaceNotAvailableOnBrowse = false; + + if (IsStatusMessageDisplayed && StatusMessage == _interfaceNotAvailableMessage) + IsStatusMessageDisplayed = false; + + OnPropertyChanged(); + } + } + + /// + /// History and service type profiles of the service type input (like the ports of the Port Scanner). + /// + private readonly InputSuggestions _serviceTypeSuggestions = InputSuggestions.ForMDNSDiscoveryServiceTypes(); + + /// + /// Gets the history and the service type profiles (grouped) of the service type input. + /// + public ICollectionView ServiceTypeSuggestions => _serviceTypeSuggestions.View; + + /// + /// Gets the names of the service type profiles, for the Tab completion of the service type input. + /// + public IEnumerable ServiceTypeProfileNames => _serviceTypeSuggestions.ProfileNames; + + /// + /// Gets or sets the service types to browse: *, service types (e.g. _ipp._tcp) and / or names + /// of service type profiles, separated by ";" (e.g. Printers; _ssh._tcp). + /// + public string ServiceType + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets the durations of a browse in seconds (0 = until stopped). + /// + public IReadOnlyList Durations => MDNSBrowser.Durations; + + /// + /// Gets or sets the duration of a browse in seconds (0 = until stopped). + /// + public int SelectedDuration + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets a value indicating whether a browse is running. + /// + public bool IsRunning + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// 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. + /// + public bool IsCanceling + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets a value indicating whether a browse was started (counters, empty state). + /// + public bool IsBrowsed + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets the seconds since the browse was started (progress bar). + /// + public double SecondsElapsed + { + get; + private set + { + if (Math.Abs(value - field) < 0.01) + return; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets the duration of the running browse in seconds (0 = until stopped, progress bar). + /// + public int BrowseDuration + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets the time when the last browse ended. + /// + public DateTime? LastScanTime + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets or sets a value indicating whether the status message is displayed. + /// + public bool IsStatusMessageDisplayed + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets the status message to display. + /// + public string StatusMessage + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Level of the status message (icon and color, see ). + /// + public StatusLevel StatusMessageLevel + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Delays filtering the results while the user is typing (see ). + /// + private readonly SearchDelay _searchDelay; + + /// + /// Gets or sets the search text for filtering the services (name, type, hostname, port, addresses, TXT + /// records) and the records (name, type, value). + /// + public string Search + { + get; + set + { + if (value == field) + return; + + field = value; + + _searchDelay.Restart(); + + OnPropertyChanged(); + } + } + + /// + /// Gets the discovered services. + /// + public ObservableRangeCollection Results { get; } = []; + + /// + /// Gets the filtered and sorted view of the services. + /// + public ICollectionView ResultsView { get; } + + /// + /// Gets or sets the selected service. + /// + public MDNSServiceInfo SelectedResult + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets or sets the selected services. + /// + public IList SelectedResults + { + get; + set + { + if (Equals(value, field)) + return; + + field = value; + OnPropertyChanged(); + } + } = new ArrayList(); + + /// + /// Gets the received DNS records. + /// + public ObservableRangeCollection Records { get; } = []; + + /// + /// Gets the filtered and sorted view of the records. + /// + public ICollectionView RecordsView { get; } + + /// + /// Gets or sets the selected record. + /// + public MDNSRecordInfo SelectedRecord + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets or sets the selected records. + /// + public IList SelectedRecords + { + get; + set + { + if (Equals(value, field)) + return; + + field = value; + OnPropertyChanged(); + } + } = new ArrayList(); + + /// + /// 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 bool ShowRecords + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + #endregion + + #region Constructor, load settings + + /// + /// Initializes a new instance of the class. + /// + public MDNSDiscoveryViewModel() + { + // Services sorted by type and name, filtered by the search + 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 = o => + { + if (string.IsNullOrEmpty(Search)) + return true; + + if (o is not MDNSServiceInfo info) + return false; + + bool Matches(string value) => value?.Contains(Search, StringComparison.OrdinalIgnoreCase) == true; + + return Matches(info.Name) || + Matches(info.ServiceType) || + Matches(info.Hostname) || + Matches(info.Port?.ToString()) || + Matches(info.Addresses) || + Matches(info.TXTRecords); + }; + + // Hostname, port, addresses and TXT records can arrive after the service was added - filter it again when + // they change. Only enabled while searching, see ApplySearch. + var liveShaping = (ICollectionViewLiveShaping)ResultsView; + liveShaping.LiveFilteringProperties.Add(nameof(MDNSServiceInfo.Hostname)); + liveShaping.LiveFilteringProperties.Add(nameof(MDNSServiceInfo.Port)); + liveShaping.LiveFilteringProperties.Add(nameof(MDNSServiceInfo.Addresses)); + liveShaping.LiveFilteringProperties.Add(nameof(MDNSServiceInfo.TXTRecords)); + + // Records sorted by name and type, their values don't change (only the TTL) + 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 = o => + { + if (string.IsNullOrEmpty(Search)) + return true; + + if (o is not MDNSRecordInfo info) + return false; + + return info.Name.Contains(Search, StringComparison.OrdinalIgnoreCase) || + info.Type.Contains(Search, StringComparison.OrdinalIgnoreCase) || + info.Value.Contains(Search, StringComparison.OrdinalIgnoreCase); + }; + + _searchDelay = new SearchDelay(GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan, ApplySearch); + + _flushTimer = new DispatcherTimer(DispatcherPriority.Background) + { + Interval = TimeSpan.FromMilliseconds(250) + }; + + _flushTimer.Tick += (_, _) => FlushSnapshot(); + + LoadSettings(); + + LoadInterfaces(); + + // Screenshot mode: results right away (like the dashboard) + if (ScreenshotData.IsEnabled) + ShowScreenshotData(); + } + + private void LoadSettings() + { + ServiceType = MDNSServiceTypeProfile.TryResolve(SettingsManager.Current.MDNSDiscovery_ServiceType, + SettingsManager.Current.MDNSDiscovery_ServiceTypeProfiles, out _) + ? SettingsManager.Current.MDNSDiscovery_ServiceType + : GlobalStaticConfiguration.MDNSDiscovery_ServiceType; + + SelectedDuration = Durations.Contains(SettingsManager.Current.MDNSDiscovery_Duration) + ? SettingsManager.Current.MDNSDiscovery_Duration + : GlobalStaticConfiguration.MDNSDiscovery_Duration; + } + + #endregion + + #region ICommands & Actions + + /// + /// Gets the command to start or stop the browse. + /// + public ICommand BrowseCommand => new RelayCommand(_ => BrowseAction(), Browse_CanExecute); + + private bool Browse_CanExecute(object parameter) + { + return !DialogHelper.IsAnyDialogOpen() && !IsInterfacesLoading && (IsRunning || SelectedInterface != null); + } + + private void BrowseAction() + { + if (IsRunning) + Stop(); + else + _browseTask = Browse(); + } + + /// + /// Gets the command to reload the network interfaces. + /// + public ICommand RefreshInterfacesCommand => new RelayCommand(_ => RefreshInterfacesAction(), RefreshInterfaces_CanExecute); + + private bool RefreshInterfaces_CanExecute(object parameter) + { + return !IsRunning && !IsInterfacesLoading && !DialogHelper.IsAnyDialogOpen(); + } + + private void RefreshInterfacesAction() + { + _ = RefreshInterfaces(); + } + + /// + /// Gets the command to filter the results right away (Enter in the search box, see + /// ). + /// + public ICommand ApplySearchCommand => _searchDelay.ApplyCommand; + + /// + /// Gets the command to copy a value of all selected services (one per line, in the order shown in the grid). + /// Parameter: Name, ServiceType, Hostname, Port, Addresses, + /// TXTRecords or Details (all values of a service). + /// + public ICommand CopySelectedResultsCommand => new RelayCommand(CopySelectedResultsAction); + + private void CopySelectedResultsAction(object parameter) + { + Func selector = parameter switch + { + "Name" => x => x.FullName, + "ServiceType" => x => x.ServiceType, + "Hostname" => x => x.Hostname, + "Port" => x => x.Port?.ToString(CultureInfo.InvariantCulture), + "Addresses" => x => x.Addresses, + "TXTRecords" => x => x.TXTRecords, + "Details" => x => string.Join(Environment.NewLine, + new[] { x.FullName, $"{x.Hostname}\t{x.Port}\t{x.Addresses}", x.TXTRecords } + .Where(value => !string.IsNullOrEmpty(value?.Trim()))), + _ => null + }; + + if (selector == null) + return; + + var separator = parameter is "Details" or "TXTRecords" ? Environment.NewLine + Environment.NewLine : Environment.NewLine; + + ClipboardHelper.SetClipboard(string.Join(separator, + ResultsView.GetSelectedItemsInViewOrder(SelectedResults).Select(selector) + .Where(x => !string.IsNullOrEmpty(x)).Distinct())); + } + + /// + /// Gets the command to copy a value of all selected records (one per line, in the order shown in the grid). + /// Parameter: Name, Value or Details (name, type, class, TTL and value). + /// + public ICommand CopySelectedRecordsCommand => new RelayCommand(CopySelectedRecordsAction); + + private void CopySelectedRecordsAction(object parameter) + { + Func selector = parameter switch + { + "Name" => x => x.Name, + "Value" => x => x.Value, + "Details" => x => $"{x.Name}\t{x.Type}\t{x.Class}\t{x.TTL}\t{x.Value}", + _ => null + }; + + if (selector == null) + return; + + var values = RecordsView.GetSelectedItemsInViewOrder(SelectedRecords).Select(selector); + + // Every record is one line; names are listed once + ClipboardHelper.SetClipboard(string.Join(Environment.NewLine, + parameter is "Name" ? values.Distinct() : values)); + } + + /// + /// Gets the command to export the services or the records (what is shown, see ). + /// + public ICommand ExportCommand => new RelayCommand(_ => ExportAction()); + + private void ExportAction() + { + _ = Export(); + } + + #endregion + + #region Methods + + /// + /// Loads the network interfaces right away (constructor: a run command may browse right after the view was + /// created). Shown again: see . + /// + private void LoadInterfaces() + { + try + { + SetInterfaces(GetInterfaces()); + } + catch (Exception ex) + { + LoadInterfacesFailed(ex); + } + } + + /// + /// 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; + + try + { + var interfaces = await TaskHelper.WithMinimumDurationAsync(() => Task.Run(GetInterfaces), + GlobalStaticConfiguration.ApplicationUIRefreshInterval); + + SetInterfaces(interfaces); + } + catch (Exception ex) + { + LoadInterfacesFailed(ex); + } + finally + { + IsInterfacesLoading = false; + } + } + + /// + /// Gets the interfaces with multicast support (screenshot mode: a sample interface instead of the real ones). + /// + private static IReadOnlyList GetInterfaces() + { + return ScreenshotData.IsEnabled ? ScreenshotData.CreateMDNSInterfaces() : MDNSBrowser.GetInterfaces(); + } + + /// + /// Screenshot mode (--screenshot): shows sample services and records instead of a browse (no sockets, + /// settings or history are changed). + /// + private void ShowScreenshotData() + { + IsStatusMessageDisplayed = false; + + var snapshot = ScreenshotData.CreateMDNSDiscoverySnapshot(SelectedInterface?.Name ?? string.Empty); + + _serviceRows.Clear(); + _recordRows.Clear(); + Results.Clear(); + Records.Clear(); + Merge(Results, _serviceRows, snapshot.Services, x => x.FullName, (row, value) => row.UpdateFrom(value)); + Merge(Records, _recordRows, snapshot.Records, x => x.Id, (row, value) => row.UpdateFrom(value)); + + IsBrowsed = true; + LastScanTime = DateTime.Now; + } + + /// + /// 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); + + var previousInterface = Interfaces.FirstOrDefault(x => x.Id == id); + + SelectedInterface = previousInterface ?? Interfaces.FirstOrDefault(); + + Log.Debug($"Found {Interfaces.Count} network interfaces with multicast support, selected: \"{SelectedInterface?.Name}\"."); + + if (SelectedInterface == null) + { + SetStatusMessage(Strings.MDNSDiscovery_NoInterface, StatusLevel.Warning); + } + // The last used interface is gone (e.g. a USB adapter or VPN): say which one is used instead, also a run + // command browses on it right away + // (not the sample interface of the screenshot mode) + else if (previousInterface == null && !string.IsNullOrEmpty(id) && !ScreenshotData.IsEnabled) + { + Log.Info($"Network interface \"{id}\" is not available, \"{SelectedInterface.Name}\" is used."); + + _interfaceNotAvailableMessage = string.Format(Strings.MDNSDiscovery_InterfaceNotAvailable, SelectedInterface.Name); + _showInterfaceNotAvailableOnBrowse = true; + + SetStatusMessage(_interfaceNotAvailableMessage, StatusLevel.Warning); + } + // Messages of an earlier load that no longer apply (not the error of a browse, it starts like the load error) + else if (StatusMessage is not null && + (StatusMessage == Strings.MDNSDiscovery_NoInterface || StatusMessage == _interfaceNotAvailableMessage || + StatusMessage == _loadInterfacesErrorMessage)) + { + IsStatusMessageDisplayed = false; + } + } + + // Message of the last load if the last used interface was not available (removed when it applies no longer). Shown + // again by the next browse (which clears the messages), e.g. a run command right after the view was created. + private string _interfaceNotAvailableMessage; + private bool _showInterfaceNotAvailableOnBrowse; + + // Message of the last failed load of the interfaces (removed by the next successful load) + private string _loadInterfacesErrorMessage; + + private void LoadInterfacesFailed(Exception ex) + { + Log.Error("Cannot load the network interfaces with multicast support.", ex); + + _loadInterfacesErrorMessage = Strings.MDNSDiscovery_Failed + Environment.NewLine + ex.Message; + + SetStatusMessage(_loadInterfacesErrorMessage, StatusLevel.Error); + } + + /// + /// Shows a message below the input (replaces the previous one). + /// + private void SetStatusMessage(string message, StatusLevel level) + { + StatusMessage = message; + StatusMessageLevel = level; + IsStatusMessageDisplayed = true; + } + + /// + /// Browses on the selected interface until the duration expires or is called. The results + /// are updated while browsing and kept afterward. + /// + private async Task Browse() + { + if (IsRunning || SelectedInterface == null) + return; + + // Service type profiles in the input (e.g. "Printers; _ssh._tcp") are replaced by their service types. The + // input is validated, but a profile may have been renamed or deleted since. + if (!MDNSServiceTypeProfile.TryResolve(ServiceType, SettingsManager.Current.MDNSDiscovery_ServiceTypeProfiles, + out var serviceTypes)) + { + SetStatusMessage(Strings.MDNSDiscovery_InvalidServiceType, StatusLevel.Error); + + return; + } + + if (ScreenshotData.IsEnabled) + { + ShowScreenshotData(); + + return; + } + + _isPaused = false; + + _browseInterface = SelectedInterface; + _browseServiceTypes = serviceTypes; + _browseCache = new MDNSServiceCache(_browseServiceTypes, _browseInterface.Name); + + // * 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); + + SettingsManager.Current.MDNSDiscovery_ServiceType = ServiceType; + SettingsManager.Current.MDNSDiscovery_Duration = SelectedDuration; + SettingsManager.Current.MDNSDiscovery_InterfaceId = _browseInterface.Id; + + IsStatusMessageDisplayed = false; + StatusMessage = string.Empty; + StatusMessageLevel = StatusLevel.None; + + // Browses on another interface than the last used one (not available) + if (_showInterfaceNotAvailableOnBrowse) + { + _showInterfaceNotAvailableOnBrowse = false; + + SetStatusMessage(_interfaceNotAvailableMessage, StatusLevel.Warning); + } + + Results.Clear(); + Records.Clear(); + _serviceRows.Clear(); + _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 serviceTypes = _browseServiceTypes; + var cache = _browseCache; + + _cancellationTokenSource?.Dispose(); + _cancellationTokenSource = new CancellationTokenSource(); + + using var timeout = new CancellationTokenSource(); + + if (duration > 0) + timeout.CancelAfter(TimeSpan.FromSeconds(duration)); + + using var linked = + CancellationTokenSource.CreateLinkedTokenSource(_cancellationTokenSource.Token, timeout.Token); + + BrowseDuration = duration; + SecondsElapsed = 0; + IsBrowsed = true; + IsCanceling = false; + IsRunning = true; + + _browseStopwatch.Restart(); + _flushTimer.Start(); + + try + { + await Task.Run(() => MDNSBrowser.BrowseAsync(networkInterface, serviceTypes, + snapshot => Interlocked.Exchange(ref _pendingSnapshot, snapshot), linked.Token, cache)); + } + catch (OperationCanceledException) when (linked.IsCancellationRequested) + { + // Stopped before the duration expired (until stopped / paused: the normal end) + if (_cancellationTokenSource.IsCancellationRequested && duration > 0) + SetStatusMessage(Strings.CanceledByUserMessage, StatusLevel.None); + } + catch (Exception ex) + { + Log.Error("mDNS Discovery service discovery failed.", ex); + + SetStatusMessage(Strings.MDNSDiscovery_Failed + Environment.NewLine + ex.Message, StatusLevel.Error); + } + finally + { + _flushTimer.Stop(); + _browseStopwatch.Stop(); + + FlushSnapshot(); + + LastScanTime = DateTime.Now; + + IsCanceling = false; + IsRunning = false; + + // Not if paused: the browse continues when the view is shown + if (!_isPaused) + FillInPendingRequest(); + } + } + + /// + /// Stops the running browse (the results are kept). + /// + private void Stop() + { + if (!IsRunning) + return; + + IsCanceling = true; + _cancellationTokenSource?.Cancel(); + } + + /// + /// Opens the tool with service types / profiles (run command). = false + /// only fills in the input: a running (or paused) browse is not stopped, the input is filled in when it has + /// ended (see ). + /// + /// Request with the service types / profiles as target. + public async Task OpenAsync(ApplicationRequest request) + { + if (!MDNSServiceTypeProfile.TryResolve(request.Target, SettingsManager.Current.MDNSDiscovery_ServiceTypeProfiles, + out _)) + return; + + // The last request wins: an earlier one that is still waiting for the browse to end gives up (see below) + var requestId = ++_openRequestId; + + if (!request.Start) + { + _pendingFillIn = request; + + if (!IsRunning && !_isPaused) + FillInPendingRequest(); + + return; + } + + // A newer request than a pending fill in + _pendingFillIn = null; + + // A paused browse is not resumed: the view was just shown (OnViewVisible) and a resume may wait for the same + // browse to end - it would win and this request would be ignored (IsRunning) + _isPaused = false; + + Stop(); + + await _browseTask; + + // A newer request arrived while the browse was ending (e.g. two run commands right after each other): it is + // used instead - otherwise this one would change the input of the newer browse and lose track of it + if (requestId != _openRequestId) + return; + + FillIn(request); + + await (_browseTask = Browse()); + } + + /// + /// Fills in the request to fill in only that arrived while browsing (see ). + /// + private void FillInPendingRequest() + { + var request = _pendingFillIn; + + _pendingFillIn = null; + + if (request != null) + FillIn(request); + } + + /// + /// Fills in the service types / profiles and the duration of a request (e.g. "mdns printers 30", otherwise the + /// selected duration is kept). + /// + private void FillIn(ApplicationRequest request) + { + ServiceType = request.Target; + + if (request is MDNSDiscoveryRequest { Duration: { } duration } && Durations.Contains(duration)) + SelectedDuration = duration; + } + + /// + /// Called when the view is shown: resumes a paused browse (see ), otherwise reloads + /// the interfaces in the background (not while browsing). + /// + public void OnViewVisible() + { + _isViewVisible = true; + + if (_isPaused) + { + _ = Resume(); + + return; + } + + if (!IsRunning && !IsInterfacesLoading) + _ = ReloadInterfacesInBackground(); + } + + /// + /// Reloads the interfaces when the view is shown again, in the background: reading the IP properties of every + /// adapter can take a while (many virtual adapters). No reload animation (not requested by the user). If a + /// browse was started meanwhile (e.g. run command), the result is dropped - the browse keeps its interface. + /// + private async Task ReloadInterfacesInBackground() + { + try + { + var interfaces = await Task.Run(GetInterfaces); + + if (!IsRunning && !IsInterfacesLoading) + SetInterfaces(interfaces); + } + catch (Exception ex) + { + LoadInterfacesFailed(ex); + } + } + + /// + /// 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() + { + _isViewVisible = false; + + // Not a browse that is being stopped (Stop pressed, then another tool selected): it would be resumed + if (!IsRunning || IsCanceling || 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), or the view was hidden again while the pause + // was ending (it stays paused and is resumed when the view is shown) + if (!_isPaused || IsRunning || !_isViewVisible) + return; + + _isPaused = false; + + await (_browseTask = Run(0)); + } + + private Task Export() + { + var window = Application.Current.Windows.OfType().FirstOrDefault(x => x.IsActive); + + var exportRecords = ShowRecords; + + var childWindow = new ExportChildWindow(); + + var childWindowViewModel = new ExportViewModel(async instance => + { + childWindow.IsOpen = false; + ConfigurationManager.Current.IsChildWindowOpen = false; + + try + { + // Copy the rows on the UI thread (they are updated while browsing) and export them in the + // background. In the order shown in 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 services = 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, services)); + } + } + catch (Exception ex) + { + Log.Error("Error while exporting data as " + instance.FileType, ex); + + await DialogHelper.ShowMessageAsync(window, Strings.Error, + Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine + + Environment.NewLine + ex.Message, ChildWindowIcon.Error); + } + + SettingsManager.Current.MDNSDiscovery_ExportFileType = instance.FileType; + SettingsManager.Current.MDNSDiscovery_ExportFilePath = instance.FilePath; + }, _ => + { + childWindow.IsOpen = false; + ConfigurationManager.Current.IsChildWindowOpen = false; + }, [ + ExportFileType.Csv, ExportFileType.Xml, ExportFileType.Json + ], true, SettingsManager.Current.MDNSDiscovery_ExportFileType, + SettingsManager.Current.MDNSDiscovery_ExportFilePath); + + childWindow.Title = Strings.Export; + + childWindow.DataContext = childWindowViewModel; + + ConfigurationManager.Current.IsChildWindowOpen = true; + + return window.ShowChildWindowAsync(childWindow); + } + + #endregion + + #region Events + + /// + /// Filters the results with the current right away (e.g. Enter in the search box). + /// + private void ApplySearch() + { + // Live filtering only while searching - without a search every service is shown anyway, but it would still + // listen to the filtered properties of every row (see the constructor) + var liveShaping = (ICollectionViewLiveShaping)ResultsView; + var isSearching = !string.IsNullOrEmpty(Search); + + if (liveShaping.IsLiveFiltering != isSearching) + liveShaping.IsLiveFiltering = isSearching; + + ResultsView.Refresh(); + RecordsView.Refresh(); + } + + /// + /// Merges the latest snapshot of the browser into the rows (UI thread, flush timer and end of the browse). + /// + private void FlushSnapshot() + { + SecondsElapsed = _browseStopwatch.Elapsed.TotalSeconds; + + var snapshot = Interlocked.Exchange(ref _pendingSnapshot, null); + + if (snapshot == null) + return; + + Merge(Results, _serviceRows, snapshot.Services, x => x.FullName, (row, value) => row.UpdateFrom(value)); + Merge(Records, _recordRows, snapshot.Records, x => x.Id, (row, value) => row.UpdateFrom(value)); + } + + /// + /// Merges a snapshot into the rows: existing rows are updated (selection and expanded details are kept), rows + /// that are no longer in the snapshot are removed and new ones added - one by one, or with one reset if there + /// are many changes (see ). + /// + private static void Merge(ObservableRangeCollection rows, Dictionary index, + IReadOnlyList values, Func getKey, Action update) + { + var keys = values.Select(getKey).ToHashSet(index.Comparer); + var removed = index.Where(x => !keys.Contains(x.Key)).ToArray(); + var added = new List(); + + foreach (var value in values) + { + if (index.TryGetValue(getKey(value), out var row)) + update(row, value); + else if (index.TryAdd(getKey(value), value)) + added.Add(value); + } + + foreach (var row in removed) + index.Remove(row.Key); + + if (removed.Length == 0 && added.Count == 0) + return; + + if ((long)(removed.Length + added.Count) * (rows.Count + added.Count) > MaxRowChangesOneByOne) + { + var removedRows = removed.Select(x => x.Value).ToHashSet(); + + rows.ReplaceAll(rows.Where(x => !removedRows.Contains(x)).Concat(added)); + + return; + } + + foreach (var row in removed) + rows.Remove(row.Value); + + foreach (var row in added) + rows.Add(row); + } + + #endregion +} diff --git a/Source/NETworkManager/ViewModels/MDNSServiceTypeProfileViewModel.cs b/Source/NETworkManager/ViewModels/MDNSServiceTypeProfileViewModel.cs new file mode 100644 index 0000000000..c22ee16b20 --- /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 Discovery 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/RunCommandViewModel.cs b/Source/NETworkManager/ViewModels/RunCommandViewModel.cs index cb2ac8de80..39d46b1079 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; @@ -449,9 +450,12 @@ 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), + or RunCommandSuggestionKind.PortProfile or RunCommandSuggestionKind.Duration + or RunCommandSuggestionKind.Type), _ => null }); @@ -657,6 +661,7 @@ .. GetHistorySuggestions().Take(MaxSuggestions) RunCommandPosition.Target when _result.ProfileName != null => GetProfileSuggestions().Take(MaxSuggestions), RunCommandPosition.Target => [ + .. GetServiceTypeProfileSuggestions().Take(MaxSuggestions), .. GetHistorySuggestions().Take(MaxCommandHistorySuggestions), .. GetProfileSuggestions().Take(MaxSuggestions) ], @@ -664,6 +669,7 @@ .. GetProfileSuggestions().Take(MaxSuggestions) _ => [ .. GetDNSServerSuggestions().Take(MaxSuggestions), .. GetPortProfileSuggestions().Take(MaxSuggestions), + .. GetDurationSuggestions().Take(MaxSuggestions), .. GetTypeSuggestions().Take(MaxSuggestions), .. GetHistorySuggestions().Take(MaxSuggestions) ] }; @@ -1157,6 +1163,33 @@ private IEnumerable GetDNSServerSuggestions() Strings.DNSServers, isList: true); } + /// + /// Durations of the mDNS Discovery 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 Discovery 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 []; + + // The same list as in the input of the tool + return GetValueSuggestions(InputSuggestions.GetMDNSDiscoveryServiceTypeProfiles(), + 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 +1210,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/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/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"> + SelectedItemsList="{Binding SelectedResults, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" + wpfHelpers:DataGridHelper.FillRemainingWidth="True"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/MDNSDiscoveryView.xaml b/Source/NETworkManager/Views/MDNSDiscoveryView.xaml new file mode 100644 index 0000000000..f84884d837 --- /dev/null +++ b/Source/NETworkManager/Views/MDNSDiscoveryView.xaml @@ -0,0 +1,630 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/NETworkManager/Views/MDNSDiscoveryView.xaml.cs b/Source/NETworkManager/Views/MDNSDiscoveryView.xaml.cs new file mode 100644 index 0000000000..1635eaf0b1 --- /dev/null +++ b/Source/NETworkManager/Views/MDNSDiscoveryView.xaml.cs @@ -0,0 +1,38 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Media; +using NETworkManager.ViewModels; + +namespace NETworkManager.Views; + +public partial class MDNSDiscoveryView : IApplicationRequestHandler +{ + private readonly MDNSDiscoveryViewModel _viewModel = new(); + + public MDNSDiscoveryView() + { + InitializeComponent(); + DataContext = _viewModel; + } + + 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/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 @@ + + + + + + + + + + + + +