From 9aaa7018e4c13dd5c12929fe4c43eb9ecb5fd30d Mon Sep 17 00:00:00 2001 From: agent Date: Sun, 29 Nov 2026 15:36:36 +0100 Subject: [PATCH 01/18] Feature: Ping Monitor TCP check (TCP ping) Besides ICMP, the Ping Monitor checks a host with a TCP connection to one port (#2795). - TCPHostMonitorProbe (shared PortProbe, one attempt): open = up (time to connect), closed = down ("Port closed" in the tooltip), no answer = timed out; HostMonitorMethod and Method / Port on PingInfo - Input row like DNS Lookup: Host, Port (TCP only), Protocol; protocol and last port remembered, port history - Own port profiles with one port (e.g. "HTTPS" = 443/tcp): Settings > Ping Monitor > TCP with add / edit / delete like the Port Scanner, input with suggestions and Tab completion, "443" or "443/tcp" or a port profile name - Profiles and groups: protocol and port with "Override default settings" like the Port Scanner (group for its profiles, profile overrides the group), port profile referenced by ID with the saved port as fallback, tooltip of the profiles shows the check - Run command: ping [port | port profile] with suggestions, ICMP without a port - Timeout and wait time per protocol (ICMP / TCP) - Tag "icmp" / "443/tcp", notifications and duplicates per port, export of a TCP host with the port, a TCP host opens in the Port Scanner with its port - Tests: TCP probe, HostMonitor loop, duplicates, port profiles, profile / group resolution, run command, TCP export Co-Authored-By: Claude Opus 5.5 --- .../PingMonitorProfileCheckConverter.cs | 35 +++ .../Resources/Strings.Designer.cs | 40 ++- .../Resources/Strings.resx | 12 + .../Export/ExportManager.PingInfo.cs | 21 +- .../Network/HostMonitorMethod.cs | 17 ++ .../Network/ICMPHostMonitorProbe.cs | 6 +- .../Network/IHostMonitorProbe.cs | 4 +- .../NETworkManager.Models/Network/PingInfo.cs | 10 + .../Network/PingMonitorHostHelper.cs | 33 ++- .../Network/PingMonitorPortProfile.cs | 165 ++++++++++++ .../Network/PingMonitorPortProfileInfo.cs | 45 ++++ .../Network/TCPHostMonitorProbe.cs | 68 +++++ .../RunCommand/RunCommandArgument.cs | 3 +- .../Application/PingMonitor.cs | 105 ++++++++ Source/NETworkManager.Profiles/GroupInfo.cs | 28 ++ .../GroupViewManager.cs | 1 + .../NETworkManager.Profiles/GroupViewName.cs | 3 +- Source/NETworkManager.Profiles/ProfileInfo.cs | 27 ++ .../GlobalStaticConfiguration.cs | 7 +- .../NETworkManager.Settings/SettingsInfo.cs | 76 ++++++ .../Export/ExportManagerToolTests.cs | 17 ++ .../Network/HostMonitorTests.cs | 124 +++++++++ .../Network/PingMonitorHostHelperTests.cs | 19 ++ .../Network/PingMonitorPortProfileTests.cs | 119 +++++++++ .../Network/TCPHostMonitorProbeTests.cs | 79 ++++++ .../Profiles/PingMonitorProfileTests.cs | 102 ++++++++ .../RunCommand/RunCommandParserTests.cs | 26 +- .../PingMonitorPortOrPortProfileValidator.cs | 22 ++ .../PingMonitorPortProfileNameValidator.cs | 20 ++ Source/NETworkManager/ApplicationRequest.cs | 8 + Source/NETworkManager/InputSuggestions.cs | 14 + Source/NETworkManager/MainWindow.xaml.cs | 1 + Source/NETworkManager/ProfileDialogManager.cs | 14 + Source/NETworkManager/RunCommandManager.cs | 25 +- .../ViewModels/GroupViewModel.cs | 76 ++++++ .../ViewModels/PingMonitorHostViewModel.cs | 165 +++++++++++- .../PingMonitorPortProfileViewModel.cs | 147 +++++++++++ .../PingMonitorSettingsViewModel.cs | 240 +++++++++++++++++- .../ViewModels/PingMonitorViewModel.cs | 86 ++++++- .../ViewModels/ProfileViewModel.cs | 71 ++++++ .../ViewModels/RunCommandViewModel.cs | 13 + .../Views/GroupChildWindow.xaml | 98 +++++++ .../Views/PingMonitorHostView.xaml | 74 +++++- .../Views/PingMonitorHostView.xaml.cs | 2 +- .../PingMonitorPortProfileChildWindow.xaml | 100 ++++++++ .../PingMonitorPortProfileChildWindow.xaml.cs | 22 ++ .../Views/PingMonitorSettingsView.xaml | 112 +++++++- .../Views/PingMonitorSettingsView.xaml.cs | 11 +- .../NETworkManager/Views/PingMonitorView.xaml | 2 +- .../Views/PingMonitorView.xaml.cs | 4 +- .../Views/ProfileChildWindow.xaml | 73 +++++- 51 files changed, 2537 insertions(+), 55 deletions(-) create mode 100644 Source/NETworkManager.Converters/PingMonitorProfileCheckConverter.cs create mode 100644 Source/NETworkManager.Models/Network/HostMonitorMethod.cs create mode 100644 Source/NETworkManager.Models/Network/PingMonitorPortProfile.cs create mode 100644 Source/NETworkManager.Models/Network/PingMonitorPortProfileInfo.cs create mode 100644 Source/NETworkManager.Models/Network/TCPHostMonitorProbe.cs create mode 100644 Source/NETworkManager.Profiles/Application/PingMonitor.cs create mode 100644 Source/NETworkManager.Tests/Network/HostMonitorTests.cs create mode 100644 Source/NETworkManager.Tests/Network/PingMonitorPortProfileTests.cs create mode 100644 Source/NETworkManager.Tests/Network/TCPHostMonitorProbeTests.cs create mode 100644 Source/NETworkManager.Tests/Profiles/PingMonitorProfileTests.cs create mode 100644 Source/NETworkManager.Validators/PingMonitorPortOrPortProfileValidator.cs create mode 100644 Source/NETworkManager.Validators/PingMonitorPortProfileNameValidator.cs create mode 100644 Source/NETworkManager/ViewModels/PingMonitorPortProfileViewModel.cs create mode 100644 Source/NETworkManager/Views/PingMonitorPortProfileChildWindow.xaml create mode 100644 Source/NETworkManager/Views/PingMonitorPortProfileChildWindow.xaml.cs diff --git a/Source/NETworkManager.Converters/PingMonitorProfileCheckConverter.cs b/Source/NETworkManager.Converters/PingMonitorProfileCheckConverter.cs new file mode 100644 index 0000000000..6bfc7276e8 --- /dev/null +++ b/Source/NETworkManager.Converters/PingMonitorProfileCheckConverter.cs @@ -0,0 +1,35 @@ +using System; +using System.Globalization; +using System.Windows.Data; +using NETworkManager.Profiles; +using PingMonitorProfile = NETworkManager.Profiles.Application.PingMonitor; + +namespace NETworkManager.Converters; + +/// +/// Converts a to its check in the Ping Monitor ("icmp", "22/tcp", "HTTPS · 443/tcp"), +/// null if the profile and its group don't override the protocol (tooltip of the profile). +/// +public sealed class PingMonitorProfileCheckConverter : IValueConverter +{ + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value is not ProfileInfo profile) + return null; + + try + { + return PingMonitorProfile.GetCheckText(profile); + } + catch (Exception) + { + // Only a tooltip (e.g. the profile file is being switched) + return null; + } + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } +} diff --git a/Source/NETworkManager.Localization/Resources/Strings.Designer.cs b/Source/NETworkManager.Localization/Resources/Strings.Designer.cs index 2a5a02ac87..6de355c5da 100644 --- a/Source/NETworkManager.Localization/Resources/Strings.Designer.cs +++ b/Source/NETworkManager.Localization/Resources/Strings.Designer.cs @@ -5116,6 +5116,15 @@ public static string EnterValidPort { } } + /// + /// Looks up a localized string similar to Enter a valid port (1 - 65535) or port profile!. + /// + public static string EnterValidPortOrPortProfile { + get { + return ResourceManager.GetString("EnterValidPortOrPortProfile", resourceCulture); + } + } + /// /// Looks up a localized string similar to Enter a valid port and/or port range (1 - 65535)!. /// @@ -5260,6 +5269,15 @@ public static string ErrorMessage_NameMustNotContainSemicolon { } } + /// + /// Looks up a localized string similar to The name must not be a port (e.g. 443 or 443/tcp).. + /// + public static string ErrorMessage_PingMonitorPortProfileNameInvalid { + get { + return ResourceManager.GetString("ErrorMessage_PingMonitorPortProfileNameInvalid", resourceCulture); + } + } + /// /// Looks up a localized string similar to The name must not contain ";" and must not be a port or port range.. /// @@ -6383,7 +6401,7 @@ public static string HelpMessage_Animations { /// ///Only the PowerShell consoles configured in the PowerShell settings are modified. Both Windows PowerShell and PWSH (PowerShell 7 and higher) are supported. /// - ///Click in the upper right corner on the help / documentation button ( [rest of string was truncated]";. + ///Click in the upper right corner on the help / documentation button (left [rest of string was truncated]";. /// public static string HelpMessage_ApplyThemeToPowerShellConsole { get { @@ -10727,6 +10745,15 @@ public static string PingMonitorNotification { } } + /// + /// Looks up a localized string similar to The port profile of this profile or its group was not found, the port saved with the profile or group is used. Port profiles are saved in the settings and the profile or group refers to them by an internal ID - if the profile file was shared from another computer, create the port profile and then select it in the profile or group again (edit it).. + /// + public static string PingMonitorPortProfileOfProfileNotFoundMessage { + get { + return ResourceManager.GetString("PingMonitorPortProfileOfProfileNotFoundMessage", resourceCulture); + } + } + /// /// Looks up a localized string similar to {0} hosts cannot be monitored at once (maximum {1}). Split the input into smaller ranges.. /// @@ -10844,6 +10871,15 @@ public static string PortChange_Opened { } } + /// + /// Looks up a localized string similar to Port closed. + /// + public static string PortClosed { + get { + return ResourceManager.GetString("PortClosed", resourceCulture); + } + } + /// /// Looks up a localized string similar to Port description. /// @@ -11117,7 +11153,7 @@ public static string Profile { /// /// Looks up a localized string similar to Profile files are encrypted on disk using AES with a key size of 256 bits and a block size of 128 bits in CBC mode. The encryption key is derived from a master password using Rfc2898DeriveBytes (PBKDF2) with 1,000,000 iterations. At runtime, passwords are stored as SecureString once the profile file is loaded. For some functions, the password must be converted to a normal string and remains unencrypted in memory until the garbage collector cleans them up. /// - ///First make a backup copy of your profile files be [rest of string was truncated]";. + ///First make a backup copy of your profile files befo [rest of string was truncated]";. /// public static string ProfileEncryptionDisclaimer { get { diff --git a/Source/NETworkManager.Localization/Resources/Strings.resx b/Source/NETworkManager.Localization/Resources/Strings.resx index e0cd7f8828..4d1848e5e7 100644 --- a/Source/NETworkManager.Localization/Resources/Strings.resx +++ b/Source/NETworkManager.Localization/Resources/Strings.resx @@ -1586,6 +1586,9 @@ Profile files are not affected! Enter a valid OID! + + Enter a valid port (1 - 65535) or port profile! + Enter a valid port and/or port range (1 - 65535)! @@ -3116,6 +3119,9 @@ Enable profile file encryption in Settings>Profile to store credentials secur Device description + + Port closed + Port description @@ -5145,6 +5151,9 @@ Do you want to start the scan? Enter valid ports, port ranges (1 - 65535) and/or port profiles! + + The name must not be a port (e.g. 443 or 443/tcp). + The name must not contain ";" and must not be a port or port range. @@ -5922,6 +5931,9 @@ Open Windows Settings > Privacy & security > Location and enable acces Do you want to add the hosts? + + The port profile of this profile or its group was not found, the port saved with the profile or group is used. Port profiles are saved in the settings and the profile or group refers to them by an internal ID - if the profile file was shared from another computer, create the port profile and then select it in the profile or group again (edit it). + {0} hosts cannot be monitored at once (maximum {1}). Split the input into smaller ranges. diff --git a/Source/NETworkManager.Models/Export/ExportManager.PingInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.PingInfo.cs index 9a7a55ca35..6d22ca5b9e 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.PingInfo.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.PingInfo.cs @@ -20,14 +20,31 @@ public static partial class ExportManager new(nameof(PingInfo.Bytes), x => HasPingReply(x.Status) ? x.Bytes : null) ]; + /// + /// Exported fields of a TCP check of a (no TTL / bytes, the port instead). + /// + private static readonly ExportField[] PingInfoTCPExportFields = + [ + new(nameof(PingInfo.Timestamp), x => x.Timestamp), + new(nameof(PingInfo.IPAddress), x => x.IPAddress), + new(nameof(PingInfo.Hostname), x => x.Hostname, true), + new(nameof(PingInfo.Port), x => x.Port), + new(nameof(PingInfo.Status), x => x.Status), + new(nameof(PingInfo.Time), x => HasPingReply(x.Status) ? x.Time : null) + ]; + /// /// Method to export objects from type to a file. /// /// Path to the export file. /// Allowed are CSV, XML or JSON. /// Objects as to export. - public static void Export(string filePath, ExportFileType fileType, IReadOnlyList collection) + /// Method of the checks, selects the exported fields (ICMP by default). + public static void Export(string filePath, ExportFileType fileType, IReadOnlyList collection, + HostMonitorMethod method = HostMonitorMethod.ICMP) { - Export(filePath, fileType, collection, PingInfoExportFields, ApplicationName.PingMonitor); + Export(filePath, fileType, collection, + method == HostMonitorMethod.TCP ? PingInfoTCPExportFields : PingInfoExportFields, + ApplicationName.PingMonitor); } } diff --git a/Source/NETworkManager.Models/Network/HostMonitorMethod.cs b/Source/NETworkManager.Models/Network/HostMonitorMethod.cs new file mode 100644 index 0000000000..0541f2f24a --- /dev/null +++ b/Source/NETworkManager.Models/Network/HostMonitorMethod.cs @@ -0,0 +1,17 @@ +namespace NETworkManager.Models.Network; + +/// +/// How a host is checked by the Ping Monitor. +/// +public enum HostMonitorMethod +{ + /// + /// ICMP echo request (ping). + /// + ICMP, + + /// + /// TCP connect to a port (TCP ping), e.g. for hosts that block ICMP. + /// + TCP +} diff --git a/Source/NETworkManager.Models/Network/ICMPHostMonitorProbe.cs b/Source/NETworkManager.Models/Network/ICMPHostMonitorProbe.cs index 06fd725e5b..ce2675b1ac 100644 --- a/Source/NETworkManager.Models/Network/ICMPHostMonitorProbe.cs +++ b/Source/NETworkManager.Models/Network/ICMPHostMonitorProbe.cs @@ -45,8 +45,12 @@ public async Task ProbeAsync(CancellationToken cancellationToken) var pingReply = await ping.SendPingAsync(_ipAddress, _timeout, _buffer, _options, cancellationToken) .ConfigureAwait(false); - return pingReply.Status == IPStatus.Success + var pingInfo = pingReply.Status == IPStatus.Success ? PingInfo.FromSuccessfulReply(timestamp, pingReply) : new PingInfo(timestamp, _ipAddress, pingReply.Status); + + pingInfo.Method = HostMonitorMethod.ICMP; + + return pingInfo; } } diff --git a/Source/NETworkManager.Models/Network/IHostMonitorProbe.cs b/Source/NETworkManager.Models/Network/IHostMonitorProbe.cs index daec5343ad..d263264b46 100644 --- a/Source/NETworkManager.Models/Network/IHostMonitorProbe.cs +++ b/Source/NETworkManager.Models/Network/IHostMonitorProbe.cs @@ -8,8 +8,8 @@ namespace NETworkManager.Models.Network; /// once per interval, so a probe only has to check the host once. /// /// -/// Only ICMP () exists so far. Further methods (e.g. TCP connect, HTTP) are -/// planned; they return the same result type, its status is the +/// ICMP () and TCP connect () exist; HTTP(S) is +/// planned. They return the same result type, its status is the /// that matches the outcome (e.g. Success, TimedOut). /// public interface IHostMonitorProbe diff --git a/Source/NETworkManager.Models/Network/PingInfo.cs b/Source/NETworkManager.Models/Network/PingInfo.cs index e3c5c5bcfc..900674ca25 100644 --- a/Source/NETworkManager.Models/Network/PingInfo.cs +++ b/Source/NETworkManager.Models/Network/PingInfo.cs @@ -173,6 +173,16 @@ internal static PingInfo FromSuccessfulReply(DateTime timestamp, PingReply pingR /// public IPStatus Status { get; set; } + /// + /// Method of the check (Ping Monitor), null for results of other features. + /// + public HostMonitorMethod? Method { get; set; } + + /// + /// Port of a TCP check (Ping Monitor), null for other methods. + /// + public int? Port { get; set; } + /// /// IP address as an integer. /// diff --git a/Source/NETworkManager.Models/Network/PingMonitorHostHelper.cs b/Source/NETworkManager.Models/Network/PingMonitorHostHelper.cs index f3d81ea8a4..2ae96466fa 100644 --- a/Source/NETworkManager.Models/Network/PingMonitorHostHelper.cs +++ b/Source/NETworkManager.Models/Network/PingMonitorHostHelper.cs @@ -14,9 +14,6 @@ public static class PingMonitorHostHelper /// group they are added to). Several entries of the input for the same IP address (e.g. different hostnames, see /// ) are kept. /// - /// - /// With further check methods (e.g. TCP, HTTP), the method and its port / URL become part of the key. - /// /// Hosts to add. /// IP addresses already monitored in the group. /// Hosts to add and hosts that are already monitored, in the order of . @@ -24,13 +21,35 @@ public static (List<(IPAddress ipAddress, string hostname)> hostsToAdd, List<(IPAddress ipAddress, string hostname)> alreadyMonitored) SplitAlreadyMonitored( IEnumerable<(IPAddress ipAddress, string hostname)> hosts, IEnumerable monitoredIPAddresses) { - var monitored = monitoredIPAddresses.ToHashSet(); + var (hostsToAdd, alreadyMonitored) = + SplitAlreadyMonitored(hosts, [0], monitoredIPAddresses.Select(x => (x, 0))); - var hostsToAdd = new List<(IPAddress ipAddress, string hostname)>(); - var alreadyMonitored = new List<(IPAddress ipAddress, string hostname)>(); + return (hostsToAdd.Select(x => x.host).ToList(), alreadyMonitored.Select(x => x.host).ToList()); + } + + /// + /// Splits the hosts and ports to add (every host with every port, e.g. "Webserver" = 80 and 443 are two hosts + /// per IP address) into the new ones and the ones that are already monitored with the same method in the group + /// (key: IP address and port; port 0 for ICMP). Several entries of the input for the same IP address are kept. + /// + /// Hosts to add. + /// Ports of the TCP checks, [0] for ICMP. + /// IP addresses and ports already monitored with the method in the group. + /// Hosts and ports to add and already monitored, by host (in the order of ), then + /// by port (in the order of ). + public static (List<((IPAddress ipAddress, string hostname) host, int port)> hostsToAdd, + List<((IPAddress ipAddress, string hostname) host, int port)> alreadyMonitored) SplitAlreadyMonitored( + IEnumerable<(IPAddress ipAddress, string hostname)> hosts, IReadOnlyList ports, + IEnumerable<(IPAddress ipAddress, int port)> monitored) + { + var monitoredSet = monitored.ToHashSet(); + + var hostsToAdd = new List<((IPAddress ipAddress, string hostname) host, int port)>(); + var alreadyMonitored = new List<((IPAddress ipAddress, string hostname) host, int port)>(); foreach (var host in hosts) - (monitored.Contains(host.ipAddress) ? alreadyMonitored : hostsToAdd).Add(host); + foreach (var port in ports) + (monitoredSet.Contains((host.ipAddress, port)) ? alreadyMonitored : hostsToAdd).Add((host, port)); return (hostsToAdd, alreadyMonitored); } diff --git a/Source/NETworkManager.Models/Network/PingMonitorPortProfile.cs b/Source/NETworkManager.Models/Network/PingMonitorPortProfile.cs new file mode 100644 index 0000000000..86f69df60e --- /dev/null +++ b/Source/NETworkManager.Models/Network/PingMonitorPortProfile.cs @@ -0,0 +1,165 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using NETworkManager.Utilities; + +namespace NETworkManager.Models.Network; + +/// +/// Port of the TCP checks of the Ping Monitor: a port ("443" or "443/tcp") or the name of a port profile (e.g. +/// "HTTPS"), see . One port per host - the Ping Monitor is not a port +/// scanner, so there are no lists or port ranges. +/// +public static class PingMonitorPortProfile +{ + /// + /// Suffix of a port of a TCP check, e.g. "443/tcp" (like the tag of a host and the notification lines). + /// + private const string TcpSuffix = "/tcp"; + + /// + /// Formats a port of a TCP check, e.g. "443/tcp". + /// + /// Port. + /// Port with the protocol. + public static string Format(int port) + { + return port.ToString(CultureInfo.InvariantCulture) + TcpSuffix; + } + + /// + /// Parses a port: "443" or "443/tcp" (case-insensitive, leading / trailing spaces are ignored). + /// + /// Text to parse. + /// Port if the text is a valid port. + /// True if the text is a port (1 - 65535). + public static bool TryParsePort(string text, out int port) + { + port = 0; + + if (string.IsNullOrWhiteSpace(text)) + return false; + + var value = text.Trim(); + + if (value.EndsWith(TcpSuffix, StringComparison.OrdinalIgnoreCase)) + value = value[..^TcpSuffix.Length].TrimEnd(); + + return int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out port) && + PortRangeHelper.IsValidPort(port); + } + + /// + /// Finds a port profile by its name (case-insensitive, leading / trailing spaces are ignored). + /// + /// Port profiles. + /// Name of the port profile. + /// Port profile, or null if there is none with the name. + public static PingMonitorPortProfileInfo FindByName(IEnumerable portProfiles, + string name) + { + return NamedReferenceInput.FindByName(portProfiles, name); + } + + /// + /// Checks if a name can be used for a port profile: the name is entered instead of a port, so it must not be a + /// port (e.g. "443" or "443/tcp"). + /// + /// Name to check. + /// True if the name can be used. + public static bool IsValidName(string name) + { + return !string.IsNullOrWhiteSpace(name) && !TryParsePort(name, out _); + } + + /// + /// Resolves the port input: a port or the name of a port profile. + /// + /// Port input. + /// Port profiles. + /// Port if the input is valid. + /// True if the input is a port or the name of a port profile. + public static bool TryResolvePort(string input, IEnumerable portProfiles, out int port) + { + if (TryParsePort(input, out port)) + return true; + + var portProfile = FindByName(portProfiles ?? [], input); + port = portProfile?.Port ?? 0; + + return portProfile != null; + } + + /// + /// Converts a port input (e.g. of a profile or group) to the values that are saved: the port (a port profile + /// replaced by its port, used if the port profile can't be found later, e.g. a profile file from another + /// computer) and the reference to the port profile (its ID, so it is also found after a rename), like the ports + /// of the Port Scanner (see ). + /// + /// Port input. + /// Port profiles. + /// Port (0 if the input is not valid) and the reference (null if the input is no port profile). + public static (int Port, string PortInput) Encode(string input, IEnumerable portProfiles) + { + var portProfileList = portProfiles?.ToList() ?? []; + + var port = TryResolvePort(input, portProfileList, out var resolvedPort) ? resolvedPort : 0; + + // A port is never a port profile (see IsValidName); a port profile is referenced by its ID + var portProfile = TryParsePort(input, out _) ? null : FindByName(portProfileList, input); + + return (port, portProfile is { } profile && profile.Id != Guid.Empty ? profile.Id.ToString("B") : null); + } + + /// + /// Converts the saved values (see ) back to the port input: the port profile with its + /// current name (also after a rename), or the saved port if the port profile can't be found. + /// + /// Saved port, 0 if none. + /// Saved reference to a port profile. + /// Port profiles. + /// True if the port profile can't be found. + /// Port input (name of the port profile or the port), null if there is none. + public static string Decode(int port, string portInput, IEnumerable portProfiles, + out bool portProfileNotFound) + { + portProfileNotFound = false; + + var savedPort = PortRangeHelper.IsValidPort(port) ? port.ToString(CultureInfo.InvariantCulture) : null; + + if (string.IsNullOrEmpty(portInput)) + return savedPort; + + if (NamedReferenceInput.TryDecodeReferences(portInput, portProfiles ?? [], out var input)) + return input; + + portProfileNotFound = true; + + return savedPort; + } + + /// + /// Gets the default port profiles: common services that are checked with a TCP connection (no UDP services, + /// e.g. NTP). + /// + /// Port profiles, each with a new ID. + public static List GetDefaultList() + { + return + [ + new("DNS", 53), + new("HTTP", 80), + new("HTTPS", 443), + new("SSH", 22), + new("Telnet", 23), + new("SMTP", 25), + new("LDAP", 389), + new("LDAPS", 636), + new("SMB", 445), + new("RDP", 3389), + new("WinRM", 5985), + new("WinRM (HTTPS)", 5986) + ]; + } +} diff --git a/Source/NETworkManager.Models/Network/PingMonitorPortProfileInfo.cs b/Source/NETworkManager.Models/Network/PingMonitorPortProfileInfo.cs new file mode 100644 index 0000000000..661a10e95b --- /dev/null +++ b/Source/NETworkManager.Models/Network/PingMonitorPortProfileInfo.cs @@ -0,0 +1,45 @@ +using System; + +namespace NETworkManager.Models.Network; + +/// +/// Port profile of the Ping Monitor: a named port of the TCP checks (e.g. "HTTPS" = 443/tcp). The Ping Monitor +/// checks one port per host, so a port profile has one port (other than the port profiles of the Port Scanner). +/// +public class PingMonitorPortProfileInfo : INamedReference +{ + /// + /// Creates an empty port profile (serializer). + /// + public PingMonitorPortProfileInfo() + { + } + + /// + /// Creates a new port profile with a new . + /// + /// Name of the port profile, e.g. "HTTPS". + /// Port, e.g. 443. + public PingMonitorPortProfileInfo(string name, int port) + { + Id = Guid.NewGuid(); + Name = name; + Port = port; + } + + /// + /// Internal ID of the port profile - profiles and groups reference a port profile by it, so a renamed port + /// profile is still found. Kept when the port profile is edited. + /// + public Guid Id { get; set; } + + /// + /// Name of the port profile, e.g. "HTTPS". + /// + public string Name { get; set; } + + /// + /// Port of the TCP check (1 - 65535). + /// + public int Port { get; set; } +} diff --git a/Source/NETworkManager.Models/Network/TCPHostMonitorProbe.cs b/Source/NETworkManager.Models/Network/TCPHostMonitorProbe.cs new file mode 100644 index 0000000000..c0e0fc7a90 --- /dev/null +++ b/Source/NETworkManager.Models/Network/TCPHostMonitorProbe.cs @@ -0,0 +1,68 @@ +using System; +using System.Diagnostics; +using System.Net; +using System.Net.NetworkInformation; +using System.Threading; +using System.Threading.Tasks; + +namespace NETworkManager.Models.Network; + +/// +/// Checks a host with one TCP connect to a port per call (TCP ping). An open port is up, a closed port (the host +/// answered with a reset) is down with , no answer is +/// . +/// +public sealed class TCPHostMonitorProbe : IHostMonitorProbe +{ + private readonly IPAddress _ipAddress; + private readonly int _port; + private readonly int _timeout; + + /// + /// Creates a new TCP probe. + /// + /// IP address of the host. + /// Port to connect to (1 - 65535). + /// Time in milliseconds to wait for the connection. + public TCPHostMonitorProbe(IPAddress ipAddress, int port, int timeout) + { + if (port is < 1 or > 65535) + throw new ArgumentOutOfRangeException(nameof(port), port, "The port must be between 1 and 65535."); + + _ipAddress = ipAddress; + _port = port; + _timeout = timeout; + } + + /// + public string Name => "TCP"; + + /// + public async Task ProbeAsync(CancellationToken cancellationToken) + { + var timestamp = DateTime.Now; + var start = Stopwatch.GetTimestamp(); + + // One connection request: the monitor repeats the check every wait time, so no retries here + var portState = await PortProbe.ProbeAsync(_ipAddress, _port, _timeout, 1, cancellationToken) + .ConfigureAwait(false); + + var status = portState switch + { + PortState.Open => IPStatus.Success, + PortState.Closed => IPStatus.DestinationPortUnreachable, + _ => IPStatus.TimedOut + }; + + // Time to connect (only for a successful connect, like the round-trip time of a ping) + var time = status == IPStatus.Success + ? (long)Stopwatch.GetElapsedTime(start).TotalMilliseconds + : 0; + + return new PingInfo(timestamp, _ipAddress, 0, time, status) + { + Method = HostMonitorMethod.TCP, + Port = _port + }; + } +} diff --git a/Source/NETworkManager.Models/RunCommand/RunCommandArgument.cs b/Source/NETworkManager.Models/RunCommand/RunCommandArgument.cs index 57e32b43cd..f1a551c661 100644 --- a/Source/NETworkManager.Models/RunCommand/RunCommandArgument.cs +++ b/Source/NETworkManager.Models/RunCommand/RunCommandArgument.cs @@ -11,5 +11,6 @@ public enum RunCommandArgument DNSServer, Broadcast, Subnet, - Duration + Duration, + Port } diff --git a/Source/NETworkManager.Profiles/Application/PingMonitor.cs b/Source/NETworkManager.Profiles/Application/PingMonitor.cs new file mode 100644 index 0000000000..884b5daa8e --- /dev/null +++ b/Source/NETworkManager.Profiles/Application/PingMonitor.cs @@ -0,0 +1,105 @@ +using System.Collections.Generic; +using NETworkManager.Models.Network; +using NETworkManager.Settings; + +namespace NETworkManager.Profiles.Application; + +public static class PingMonitor +{ + /// + /// Gets the protocol and port for a profile: its own (if overridden), otherwise the ones of its group (if + /// overridden), otherwise none (the protocol and port of the input of the Ping Monitor are used). A port profile + /// with its current name (also after a rename); if it can't be found (deleted, or a profile file shared from + /// another computer - port profiles are saved in the settings), the port saved with the profile or group. + /// + /// Profile to get the protocol and port for. + /// True if the port profile can't be found. + /// Protocol (null if not overridden) and port input (null for ICMP or if not overridden). + public static (HostMonitorMethod? Method, string Port) GetMethodAndPort(ProfileInfo profile, + out bool portProfileNotFound) + { + return GetMethodAndPort(profile, ProfileManager.GetGroupByName(profile.Group), + SettingsManager.Current.PingMonitor_PortProfiles, out portProfileNotFound); + } + + /// + /// Gets the protocol and port for a profile and its group, see + /// . + /// + /// Profile to get the protocol and port for. + /// Group of the profile, null if not found. + /// Port profiles of the Ping Monitor. + /// True if the port profile can't be found. + /// Protocol (null if not overridden) and port input (null for ICMP or if not overridden). + public static (HostMonitorMethod? Method, string Port) GetMethodAndPort(ProfileInfo profile, GroupInfo group, + IEnumerable portProfiles, out bool portProfileNotFound) + { + portProfileNotFound = false; + + HostMonitorMethod method; + int port; + string portInput; + + if (profile.PingMonitor_OverrideMethod) + { + (method, port, portInput) = + (profile.PingMonitor_Method, profile.PingMonitor_Port, profile.PingMonitor_PortInput); + } + else if (group is { PingMonitor_OverrideMethod: true }) + { + (method, port, portInput) = (group.PingMonitor_Method, group.PingMonitor_Port, group.PingMonitor_PortInput); + } + else + { + return (null, null); + } + + return method != HostMonitorMethod.TCP + ? (method, null) + : (method, PingMonitorPortProfile.Decode(port, portInput, portProfiles, out portProfileNotFound)); + } + + /// + /// Gets the check of a profile for its tooltip in the Ping Monitor: "icmp", "22/tcp" or "HTTPS · 443/tcp" (port + /// profile), null if neither the profile nor its group overrides the protocol (the input is used). + /// + /// Profile. + /// Check of the profile, null if not overridden. + public static string GetCheckText(ProfileInfo profile) + { + var group = string.IsNullOrWhiteSpace(profile.Group) || ProfileManager.LoadedProfileFileData == null + ? null + : ProfileManager.GetGroupByName(profile.Group); + + return GetCheckText(profile, group, SettingsManager.Current.PingMonitor_PortProfiles); + } + + /// + /// Gets the check of a profile and its group, see . + /// + /// Profile. + /// Group of the profile, null if not found. + /// Port profiles of the Ping Monitor. + /// Check of the profile, null if not overridden. + public static string GetCheckText(ProfileInfo profile, GroupInfo group, + IEnumerable portProfiles) + { + var portProfileList = portProfiles as IList ?? [.. portProfiles]; + + var (method, port) = GetMethodAndPort(profile, group, portProfileList, out _); + + if (method == null) + return null; + + if (method != HostMonitorMethod.TCP) + return method.Value.ToString().ToLowerInvariant(); + + // A port ("22" -> "22/tcp") or a port profile with its port ("HTTPS · 443/tcp") + if (PingMonitorPortProfile.TryParsePort(port, out var tcpPort)) + return PingMonitorPortProfile.Format(tcpPort); + + return PingMonitorPortProfile.TryResolvePort(port, portProfileList, out tcpPort) + ? $"{port} · {PingMonitorPortProfile.Format(tcpPort)}" + : port; + } +} diff --git a/Source/NETworkManager.Profiles/GroupInfo.cs b/Source/NETworkManager.Profiles/GroupInfo.cs index d3a961b220..3a2dc8ecd5 100644 --- a/Source/NETworkManager.Profiles/GroupInfo.cs +++ b/Source/NETworkManager.Profiles/GroupInfo.cs @@ -58,6 +58,10 @@ public GroupInfo(GroupInfo group) : this(group.Name) // Port Scanner PortScanner_OverridePorts = group.PortScanner_OverridePorts; + PingMonitor_OverrideMethod = group.PingMonitor_OverrideMethod; + PingMonitor_Method = group.PingMonitor_Method; + PingMonitor_Port = group.PingMonitor_Port; + PingMonitor_PortInput = group.PingMonitor_PortInput; PortScanner_Ports = group.PortScanner_Ports; PortScanner_PortsInput = group.PortScanner_PortsInput; @@ -234,6 +238,30 @@ public GroupInfo(GroupInfo group) : this(group.Name) public bool PortScanner_OverridePorts { get; set; } + /// + /// Use the protocol () and the port () of the + /// group for its profiles (a profile can override them), otherwise the input of the Ping Monitor. + /// + public bool PingMonitor_OverrideMethod { get; set; } + + /// + /// Protocol of the checks (ICMP or TCP). + /// + public HostMonitorMethod PingMonitor_Method { get; set; } = HostMonitorMethod.ICMP; + + /// + /// Port of the TCP checks (one port, the Ping Monitor is not a port scanner). If a port profile was selected, its + /// port at the time the group was saved - used if the port profile of can't be + /// found (e.g. a profile file from another computer). 0 if none. + /// + public int PingMonitor_Port { get; set; } + + /// + /// Port profile of the Ping Monitor, referenced by its ID (e.g. "{8f1c...}"), so it is also found after a rename. + /// Null if a port was entered. + /// + public string PingMonitor_PortInput { get; set; } + /// /// Ports to scan (ports and port ranges) for the profiles of the group, see /// . diff --git a/Source/NETworkManager.Profiles/GroupViewManager.cs b/Source/NETworkManager.Profiles/GroupViewManager.cs index 7a796dbb4c..9e188fc3aa 100644 --- a/Source/NETworkManager.Profiles/GroupViewManager.cs +++ b/Source/NETworkManager.Profiles/GroupViewManager.cs @@ -15,6 +15,7 @@ public static class GroupViewManager // Applications new GroupViewInfo(GroupViewName.IPScanner, ApplicationManager.GetIcon(ApplicationName.IPScanner)), new GroupViewInfo(GroupViewName.PortScanner, ApplicationManager.GetIcon(ApplicationName.PortScanner)), + new GroupViewInfo(GroupViewName.PingMonitor, ApplicationManager.GetIcon(ApplicationName.PingMonitor)), new GroupViewInfo(GroupViewName.DNSLookup, ApplicationManager.GetIcon(ApplicationName.DNSLookup)), new GroupViewInfo(GroupViewName.RemoteDesktop, ApplicationManager.GetIcon(ApplicationName.RemoteDesktop)), new GroupViewInfo(GroupViewName.PowerShell, ApplicationManager.GetIcon(ApplicationName.PowerShell)), diff --git a/Source/NETworkManager.Profiles/GroupViewName.cs b/Source/NETworkManager.Profiles/GroupViewName.cs index 5f0de1cad6..e773f78248 100644 --- a/Source/NETworkManager.Profiles/GroupViewName.cs +++ b/Source/NETworkManager.Profiles/GroupViewName.cs @@ -10,5 +10,6 @@ public enum GroupViewName PowerShell, PuTTY, TigerVNC, - SNMP + SNMP, + PingMonitor } \ No newline at end of file diff --git a/Source/NETworkManager.Profiles/ProfileInfo.cs b/Source/NETworkManager.Profiles/ProfileInfo.cs index eca7bbf3b3..66272d9ea7 100644 --- a/Source/NETworkManager.Profiles/ProfileInfo.cs +++ b/Source/NETworkManager.Profiles/ProfileInfo.cs @@ -87,6 +87,10 @@ public ProfileInfo(ProfileInfo profile) PingMonitor_Enabled = profile.PingMonitor_Enabled; PingMonitor_InheritHost = profile.PingMonitor_InheritHost; PingMonitor_Host = profile.PingMonitor_Host; + PingMonitor_OverrideMethod = profile.PingMonitor_OverrideMethod; + PingMonitor_Method = profile.PingMonitor_Method; + PingMonitor_Port = profile.PingMonitor_Port; + PingMonitor_PortInput = profile.PingMonitor_PortInput; // Traceroute Traceroute_Enabled = profile.Traceroute_Enabled; @@ -407,6 +411,29 @@ public ProfileInfo(ProfileInfo profile) public bool PingMonitor_Enabled { get; set; } public bool PingMonitor_InheritHost { get; set; } = true; public string PingMonitor_Host { get; set; } + /// + /// Use the protocol () and the port () of the + /// profile instead of the ones of its group (or of the input of the Ping Monitor). + /// + public bool PingMonitor_OverrideMethod { get; set; } + + /// + /// Protocol of the checks (ICMP or TCP). + /// + public HostMonitorMethod PingMonitor_Method { get; set; } = HostMonitorMethod.ICMP; + + /// + /// Port of the TCP checks (one port, the Ping Monitor is not a port scanner). If a port profile was selected, its + /// port at the time the profile was saved - used if the port profile of can't be + /// found (e.g. a profile file from another computer). 0 if none. + /// + public int PingMonitor_Port { get; set; } + + /// + /// Port profile of the Ping Monitor, referenced by its ID (e.g. "{8f1c...}"), so it is also found after a rename. + /// Null if a port was entered. + /// + public string PingMonitor_PortInput { get; set; } public bool Traceroute_Enabled { get; set; } public bool Traceroute_InheritHost { get; set; } = true; diff --git a/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs b/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs index d4f583d229..93d174fdee 100644 --- a/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs +++ b/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs @@ -310,7 +310,12 @@ public static class GlobalStaticConfiguration public static bool PingMonitor_DontFragment => true; public static int PingMonitor_Timeout => 4000; // ms public static int PingMonitor_TTL => 64; - public static int PingMonitor_WaitTime => 1000; // ms + public static NETworkManager.Models.Network.HostMonitorMethod PingMonitor_Method => + NETworkManager.Models.Network.HostMonitorMethod.ICMP; // last used method is the default + public static string PingMonitor_Port => "443"; // port input of the TCP checks without history + public static int PingMonitor_TCPTimeout => 4000; // ms + public static int PingMonitor_WaitTime => 1000; // ms (ICMP) + public static int PingMonitor_TCPWaitTime => 1000; // ms (TCP) public static bool PingMonitor_ExpandHostView => false; public static int PingMonitor_ChartTime => 120; // s public static int PingMonitor_HistoryHours => 12; // h (a workday) diff --git a/Source/NETworkManager.Settings/SettingsInfo.cs b/Source/NETworkManager.Settings/SettingsInfo.cs index 02803bb418..218ff6f60e 100644 --- a/Source/NETworkManager.Settings/SettingsInfo.cs +++ b/Source/NETworkManager.Settings/SettingsInfo.cs @@ -2272,6 +2272,41 @@ public ObservableCollection PingMonitor_HostHistory } } = []; + /// + /// History of the port input of the TCP checks (ports and port profiles of the Ping Monitor). + /// + /// + /// Port profiles of the TCP checks of the Ping Monitor (one port each), see + /// . + /// + public ObservableCollection PingMonitor_PortProfiles + { + get; + set + { + if (value == field) + return; + + UpdateCollectionChanged(field, value); + field = value; + OnPropertyChanged(); + } + } = [.. NETworkManager.Models.Network.PingMonitorPortProfile.GetDefaultList()]; + + public ObservableCollection PingMonitor_PortHistory + { + get; + set + { + if (value == field) + return; + + UpdateCollectionChanged(field, value); + field = value; + OnPropertyChanged(); + } + } = []; + public int PingMonitor_Buffer { get; @@ -2324,6 +2359,45 @@ public int PingMonitor_TTL } } = GlobalStaticConfiguration.PingMonitor_TTL; + public NETworkManager.Models.Network.HostMonitorMethod PingMonitor_Method + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = GlobalStaticConfiguration.PingMonitor_Method; + + public int PingMonitor_TCPTimeout + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = GlobalStaticConfiguration.PingMonitor_TCPTimeout; + + public int PingMonitor_TCPWaitTime + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = GlobalStaticConfiguration.PingMonitor_TCPWaitTime; + public int PingMonitor_WaitTime { get; @@ -4997,6 +5071,8 @@ public SettingsInfo() // Ping Monitor PingMonitor_HostHistory.CollectionChanged += CollectionChanged; + PingMonitor_PortHistory.CollectionChanged += CollectionChanged; + PingMonitor_PortProfiles.CollectionChanged += CollectionChanged; // Traceroute Traceroute_HostHistory.CollectionChanged += CollectionChanged; diff --git a/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs b/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs index a36c755ba8..bcdf6c3b0a 100644 --- a/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs +++ b/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs @@ -80,6 +80,23 @@ public void PingMonitor_Consistent() Assert.Equal(128, (int)files.JsonValue("TTL")); } + [Fact] + public void PingMonitor_TCP_Columns() + { + // TCP: the port instead of TTL and bytes (no ICMP packet) + var files = ExportAll((f, t) => ExportManager.Export(f, t, + [ + new PingInfo(Time, IPAddress, "host", 0, 3, IPStatus.Success) { Method = HostMonitorMethod.TCP, Port = 443 }, + new PingInfo(Time, IPAddress, "host", IPStatus.DestinationPortUnreachable) + { Method = HostMonitorMethod.TCP, Port = 443 } + ], HostMonitorMethod.TCP)); + + AssertConsistent(files, "Timestamp,IPAddress,Hostname,Port,Status,Time"); + Assert.Equal("443", files.CsvValue("Port")); + Assert.Equal(3, (long)files.JsonValue("Time")); + Assert.Equal("2026-11-08 10:15:30.123,10.0.0.1,\"host\",443,DestinationPortUnreachable,", files.CsvLines[2]); + } + [Fact] public void PingMonitor_NoReply_Empty() { diff --git a/Source/NETworkManager.Tests/Network/HostMonitorTests.cs b/Source/NETworkManager.Tests/Network/HostMonitorTests.cs new file mode 100644 index 0000000000..ef68b667f0 --- /dev/null +++ b/Source/NETworkManager.Tests/Network/HostMonitorTests.cs @@ -0,0 +1,124 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.NetworkInformation; +using System.Threading; +using System.Threading.Tasks; +using NETworkManager.Models.Network; +using Xunit; + +namespace NETworkManager.Tests.Network; + +public class HostMonitorTests +{ + private static readonly IPAddress Address = IPAddress.Parse("10.0.0.1"); + + /// + /// Probe that runs the given steps one after another, then waits until it is canceled. + /// + private sealed class FakeProbe(params Func>[] steps) : IHostMonitorProbe + { + private int _calls; + + public string Name => "Fake"; + + public Task ProbeAsync(CancellationToken cancellationToken) + { + var call = _calls++; + + return call < steps.Length ? steps[call](cancellationToken) : WaitUntilCanceled(cancellationToken); + } + + private static async Task WaitUntilCanceled(CancellationToken cancellationToken) + { + await Task.Delay(Timeout.Infinite, cancellationToken); + + return null; + } + } + + private static Task Success(CancellationToken _) + { + // Another IP address instance: the monitor sets its own + return Task.FromResult(new PingInfo(DateTime.Now, IPAddress.Parse("10.0.0.1"), 0, 5, IPStatus.Success)); + } + + [Fact] + public async Task FailedCheckIsReportedAndTheMonitorKeepsChecking() + { + var probe = new FakeProbe(_ => throw new InvalidOperationException("No network"), Success); + var monitor = new HostMonitor(Address, "server", probe) { WaitTime = 1 }; + + using var cts = new CancellationTokenSource(); + var received = new List(); + var stopped = 0; + var hostnameResolved = false; + + monitor.PingReceived += (_, e) => + { + received.Add(e); + + if (received.Count == 2) + cts.Cancel(); + }; + monitor.Stopped += (_, _) => stopped++; + monitor.HostnameResolved += (_, _) => hostnameResolved = true; + + await monitor.RunAsync(cts.Token).WaitAsync(TimeSpan.FromSeconds(10)); + + Assert.Equal(2, received.Count); + + Assert.Equal(IPStatus.Unknown, received[0].Args.Status); + Assert.Equal("No network", received[0].ErrorMessage); + + Assert.Equal(IPStatus.Success, received[1].Args.Status); + Assert.Null(received[1].ErrorMessage); + + // IP address and hostname of the monitor (a known hostname: no PTR lookup) + Assert.All(received, x => Assert.Same(Address, x.Args.IPAddress)); + Assert.All(received, x => Assert.Equal("server", x.Args.Hostname)); + Assert.False(hostnameResolved); + + Assert.Equal(1, stopped); + Assert.Null(monitor.StopErrorMessage); + } + + [Fact] + public async Task CancelWhileCheckingStopsOnce() + { + var monitor = new HostMonitor(Address, "server", new FakeProbe()) { WaitTime = 1 }; + + using var cts = new CancellationTokenSource(); + var received = 0; + var stopped = 0; + + monitor.PingReceived += (_, _) => received++; + monitor.Stopped += (_, _) => stopped++; + + var run = monitor.RunAsync(cts.Token); + + await Task.Delay(50); + await cts.CancelAsync(); + await run.WaitAsync(TimeSpan.FromSeconds(10)); + + Assert.Equal(0, received); + Assert.Equal(1, stopped); + Assert.Null(monitor.StopErrorMessage); + } + + [Fact] + public async Task CanceledBeforeTheStartStopsOnce() + { + var monitor = new HostMonitor(Address, "server", new FakeProbe(Success)) { WaitTime = 1 }; + + using var cts = new CancellationTokenSource(); + await cts.CancelAsync(); + + var stopped = 0; + monitor.Stopped += (_, _) => stopped++; + + await monitor.RunAsync(cts.Token).WaitAsync(TimeSpan.FromSeconds(10)); + + Assert.Equal(1, stopped); + } +} diff --git a/Source/NETworkManager.Tests/Network/PingMonitorHostHelperTests.cs b/Source/NETworkManager.Tests/Network/PingMonitorHostHelperTests.cs index 06b1eb3462..3c6b30966b 100644 --- a/Source/NETworkManager.Tests/Network/PingMonitorHostHelperTests.cs +++ b/Source/NETworkManager.Tests/Network/PingMonitorHostHelperTests.cs @@ -40,6 +40,25 @@ public void IPv6IsComparedByValue() Assert.Single(alreadyMonitored); } + [Fact] + public void PortIsPartOfTheKey() + { + // TCP 443 is monitored, TCP 22 for the same IP address is added + var (hostsToAdd, alreadyMonitored) = + PingMonitorHostHelper.SplitAlreadyMonitored([(A, "server")], [22, 443], [(IPAddress.Parse("10.0.0.1"), 443)]); + + Assert.Equal([((A, "server"), 22)], hostsToAdd); + Assert.Equal([((A, "server"), 443)], alreadyMonitored); + } + + [Fact] + public void EveryHostWithEveryPortInTheOrderOfTheInput() + { + var (hostsToAdd, _) = PingMonitorHostHelper.SplitAlreadyMonitored([(A, null), (B, null)], [80, 443], []); + + Assert.Equal([(A, 80), (A, 443), (B, 80), (B, 443)], hostsToAdd.Select(x => (x.host.ipAddress, x.port))); + } + [Fact] public void EntriesOfTheInputForTheSameIPAddressAreKept() { diff --git a/Source/NETworkManager.Tests/Network/PingMonitorPortProfileTests.cs b/Source/NETworkManager.Tests/Network/PingMonitorPortProfileTests.cs new file mode 100644 index 0000000000..8b268bc4bf --- /dev/null +++ b/Source/NETworkManager.Tests/Network/PingMonitorPortProfileTests.cs @@ -0,0 +1,119 @@ +using System.Linq; +using NETworkManager.Models.Network; +using Xunit; + +namespace NETworkManager.Tests.Network; + +/// +/// Port of the TCP checks of the Ping Monitor: one port ("443" or "443/tcp") or the name of a port profile. +/// +public class PingMonitorPortProfileTests +{ + private static readonly PingMonitorPortProfileInfo Https = new("HTTPS", 443); + private static readonly PingMonitorPortProfileInfo Ssh = new("SSH", 22); + + [Theory] + [InlineData("443", 443)] + [InlineData("443/tcp", 443)] + [InlineData(" 22/TCP ", 22)] + [InlineData("443 /tcp", 443)] + [InlineData("65535", 65535)] + public void TryParsePort_Valid(string text, int expected) + { + Assert.True(PingMonitorPortProfile.TryParsePort(text, out var port)); + Assert.Equal(expected, port); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("0")] + [InlineData("65536")] + [InlineData("443/udp")] + [InlineData("22; 443")] + [InlineData("1-1024")] + [InlineData("HTTPS")] + public void TryParsePort_Invalid(string text) + { + Assert.False(PingMonitorPortProfile.TryParsePort(text, out _)); + } + + [Fact] + public void Format_PortWithProtocol() + { + Assert.Equal("443/tcp", PingMonitorPortProfile.Format(443)); + } + + [Theory] + [InlineData("HTTPS", true)] + [InlineData("WinRM (HTTPS)", true)] + [InlineData("443", false)] + [InlineData("443/tcp", false)] + [InlineData(" ", false)] + public void IsValidName(string name, bool expected) + { + // A name is entered instead of a port, so it must not be one + Assert.Equal(expected, PingMonitorPortProfile.IsValidName(name)); + } + + [Theory] + [InlineData("443", 443)] + [InlineData("3389/tcp", 3389)] + [InlineData("https", 443)] + [InlineData(" SSH ", 22)] + public void TryResolvePort_PortOrName(string input, int expected) + { + Assert.True(PingMonitorPortProfile.TryResolvePort(input, [Https, Ssh], out var port)); + Assert.Equal(expected, port); + } + + [Theory] + [InlineData("Webserver")] + [InlineData("80; 443")] + [InlineData("")] + public void TryResolvePort_Invalid(string input) + { + Assert.False(PingMonitorPortProfile.TryResolvePort(input, [Https, Ssh], out _)); + } + + [Fact] + public void Encode_PortProfileIsReferencedByItsId() + { + var (port, portInput) = PingMonitorPortProfile.Encode("https", [Https]); + + Assert.Equal(443, port); + Assert.Equal(Https.Id.ToString("B"), portInput); + } + + [Fact] + public void Encode_PortHasNoReference() + { + Assert.Equal((8443, null), PingMonitorPortProfile.Encode("8443/tcp", [Https])); + } + + [Fact] + public void Decode_CurrentNameOrSavedPort() + { + var (port, portInput) = PingMonitorPortProfile.Encode("HTTPS", [Https]); + var renamed = new PingMonitorPortProfileInfo { Id = Https.Id, Name = "Web (TLS)", Port = 443 }; + + Assert.Equal("Web (TLS)", PingMonitorPortProfile.Decode(port, portInput, [renamed], out var notFound)); + Assert.False(notFound); + + Assert.Equal("443", PingMonitorPortProfile.Decode(port, portInput, [], out notFound)); + Assert.True(notFound); + + Assert.Null(PingMonitorPortProfile.Decode(0, null, [], out _)); + } + + [Fact] + public void DefaultList_UniqueValidNamesAndPorts() + { + var list = PingMonitorPortProfile.GetDefaultList(); + + Assert.All(list, x => Assert.True(PingMonitorPortProfile.IsValidName(x.Name))); + Assert.Equal(list.Count, list.Select(x => x.Name.ToLowerInvariant()).Distinct().Count()); + Assert.Equal(list.Count, list.Select(x => x.Port).Distinct().Count()); + Assert.Contains(list, x => x is { Name: "HTTPS", Port: 443 }); + } +} diff --git a/Source/NETworkManager.Tests/Network/TCPHostMonitorProbeTests.cs b/Source/NETworkManager.Tests/Network/TCPHostMonitorProbeTests.cs new file mode 100644 index 0000000000..aa58ac736f --- /dev/null +++ b/Source/NETworkManager.Tests/Network/TCPHostMonitorProbeTests.cs @@ -0,0 +1,79 @@ +using System; +using System.Net; +using System.Net.NetworkInformation; +using System.Net.Sockets; +using System.Threading; +using System.Threading.Tasks; +using NETworkManager.Models.Network; +using Xunit; + +namespace NETworkManager.Tests.Network; + +public class TCPHostMonitorProbeTests +{ + [Fact] + public void Name_IsTCP() + { + var probe = new TCPHostMonitorProbe(IPAddress.Loopback, 443, 1000); + + Assert.Equal("TCP", probe.Name); + } + + [Fact] + public void Constructor_InvalidPort_Throws() + { + Assert.Throws(() => new TCPHostMonitorProbe(IPAddress.Loopback, 0, 1000)); + Assert.Throws(() => new TCPHostMonitorProbe(IPAddress.Loopback, 65536, 1000)); + } + + [Fact] + public async Task ProbeAsync_OpenPort_ReturnsSuccess() + { + var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + + try + { + var port = ((IPEndPoint)listener.LocalEndpoint).Port; + + var info = await new TCPHostMonitorProbe(IPAddress.Loopback, port, 2000).ProbeAsync(CancellationToken.None); + + Assert.Equal(IPStatus.Success, info.Status); + Assert.Equal(HostMonitorMethod.TCP, info.Method); + Assert.Equal(port, info.Port); + Assert.True(info.Time >= 0); + Assert.Equal(IPAddress.Loopback, info.IPAddress); + } + finally + { + listener.Stop(); + } + } + + [Fact] + public async Task ProbeAsync_ClosedPort_ReturnsDestinationPortUnreachable() + { + // Get a port that was free a moment ago: nothing listens on it anymore + var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var port = ((IPEndPoint)listener.LocalEndpoint).Port; + listener.Stop(); + + var info = await new TCPHostMonitorProbe(IPAddress.Loopback, port, 2000).ProbeAsync(CancellationToken.None); + + Assert.Equal(IPStatus.DestinationPortUnreachable, info.Status); + Assert.Equal(0, info.Time); + Assert.Equal(port, info.Port); + } + + [Fact] + public async Task ProbeAsync_CanceledToken_ThrowsOperationCanceledException() + { + var probe = new TCPHostMonitorProbe(IPAddress.Loopback, 443, 2000); + + using var cts = new CancellationTokenSource(); + await cts.CancelAsync(); + + await Assert.ThrowsAnyAsync(() => probe.ProbeAsync(cts.Token)); + } +} diff --git a/Source/NETworkManager.Tests/Profiles/PingMonitorProfileTests.cs b/Source/NETworkManager.Tests/Profiles/PingMonitorProfileTests.cs new file mode 100644 index 0000000000..f008283771 --- /dev/null +++ b/Source/NETworkManager.Tests/Profiles/PingMonitorProfileTests.cs @@ -0,0 +1,102 @@ +using NETworkManager.Models.Network; +using NETworkManager.Profiles; +using Xunit; +using PingMonitorProfile = NETworkManager.Profiles.Application.PingMonitor; + +namespace NETworkManager.Tests.Profiles; + +/// +/// Protocol and port of a profile in the Ping Monitor: profile, then group, otherwise the input; port profiles of +/// the Ping Monitor referenced by their ID like the ports of the Port Scanner. +/// +public class PingMonitorProfileTests +{ + private static readonly PingMonitorPortProfileInfo Https = new("HTTPS", 443); + + [Fact] + public void NoOverrideKeepsTheInput() + { + var result = PingMonitorProfile.GetMethodAndPort(new ProfileInfo(), new GroupInfo("Group"), [Https], + out var notFound); + + Assert.Equal((null, null), result); + Assert.False(notFound); + } + + [Fact] + public void ProfileWithoutGroupKeepsTheInput() + { + Assert.Equal((null, null), PingMonitorProfile.GetMethodAndPort(new ProfileInfo(), null, [Https], out _)); + } + + [Fact] + public void GroupOverride() + { + var group = new GroupInfo("Group") + { PingMonitor_OverrideMethod = true, PingMonitor_Method = HostMonitorMethod.TCP, PingMonitor_Port = 22 }; + + Assert.Equal((HostMonitorMethod.TCP, "22"), + PingMonitorProfile.GetMethodAndPort(new ProfileInfo(), group, [Https], out _)); + } + + [Fact] + public void ProfileOverridesTheGroup() + { + var profile = new ProfileInfo { PingMonitor_OverrideMethod = true, PingMonitor_Method = HostMonitorMethod.ICMP }; + var group = new GroupInfo("Group") + { PingMonitor_OverrideMethod = true, PingMonitor_Method = HostMonitorMethod.TCP, PingMonitor_Port = 22 }; + + // ICMP has no port + Assert.Equal((HostMonitorMethod.ICMP, null), + PingMonitorProfile.GetMethodAndPort(profile, group, [Https], out _)); + } + + [Fact] + public void PortProfileIsFoundAfterARename() + { + var profile = CreateTcpProfile("HTTPS"); + var renamed = new PingMonitorPortProfileInfo { Id = Https.Id, Name = "Web (TLS)", Port = 443 }; + + var (_, port) = PingMonitorProfile.GetMethodAndPort(profile, null, [renamed], out var notFound); + + Assert.Equal("Web (TLS)", port); + Assert.False(notFound); + } + + [Fact] + public void PortProfileNotFoundUsesTheSavedPort() + { + // E.g. a profile file from another computer: the port profiles are saved in the settings + var profile = CreateTcpProfile("HTTPS"); + + var (method, port) = PingMonitorProfile.GetMethodAndPort(profile, null, [], out var notFound); + + Assert.Equal(HostMonitorMethod.TCP, method); + Assert.Equal("443", port); + Assert.True(notFound); + } + + [Fact] + public void CheckText() + { + var group = new GroupInfo("Group") + { PingMonitor_OverrideMethod = true, PingMonitor_Method = HostMonitorMethod.TCP, PingMonitor_Port = 22 }; + var icmp = new ProfileInfo { PingMonitor_OverrideMethod = true, PingMonitor_Method = HostMonitorMethod.ICMP }; + + Assert.Null(PingMonitorProfile.GetCheckText(new ProfileInfo(), null, [Https])); + Assert.Equal("22/tcp", PingMonitorProfile.GetCheckText(new ProfileInfo(), group, [Https])); + Assert.Equal("icmp", PingMonitorProfile.GetCheckText(icmp, group, [Https])); + Assert.Equal("HTTPS · 443/tcp", PingMonitorProfile.GetCheckText(CreateTcpProfile("HTTPS"), group, [Https])); + } + + private static ProfileInfo CreateTcpProfile(string portInput) + { + var (port, input) = PingMonitorPortProfile.Encode(portInput, [Https]); + + return new ProfileInfo + { + PingMonitor_OverrideMethod = true, PingMonitor_Method = HostMonitorMethod.TCP, PingMonitor_Port = port, + PingMonitor_PortInput = input + }; + } +} diff --git a/Source/NETworkManager.Tests/RunCommand/RunCommandParserTests.cs b/Source/NETworkManager.Tests/RunCommand/RunCommandParserTests.cs index d5abed0059..046a8d233a 100644 --- a/Source/NETworkManager.Tests/RunCommand/RunCommandParserTests.cs +++ b/Source/NETworkManager.Tests/RunCommand/RunCommandParserTests.cs @@ -11,7 +11,13 @@ public class RunCommandParserTests new() { Type = RunCommandType.Application, Application = ApplicationName.PingMonitor, Command = "pingmonitor", - Aliases = ["ping"], SupportsTarget = true, SupportsProfile = true + Aliases = ["ping"], SupportsTarget = true, SupportsProfile = true, Argument = RunCommandArgument.Port, + SyntaxParts = + [ + RunCommandSyntaxPart.Required(RunCommandSyntaxPartKind.Target, "Hosts"), + RunCommandSyntaxPart.Optional(RunCommandSyntaxPartKind.Argument, "Port | Port profile"), + RunCommandSyntaxPart.Profile("Profile") + ] }, new() { @@ -321,7 +327,23 @@ public void TargetThatLooksLikeAType() } [Theory] - [InlineData("ping 10.0.0.1 foo", "foo")] + [InlineData("ping 10.0.0.1", "10.0.0.1", null)] + [InlineData("ping 10.0.0.1 443", "10.0.0.1", "443")] + [InlineData("ping 10.0.0.1 443/tcp", "10.0.0.1", "443/tcp")] + [InlineData("ping 10.0.0.1; 10.0.0.2 https", "10.0.0.1;10.0.0.2", "https")] + [InlineData("ping 10.0.0.1 \"WinRM (HTTPS)\"", "10.0.0.1", "WinRM (HTTPS)")] + public void PingWithPort(string input, string target, string port) + { + // Ping Monitor: a port or port profile after the hosts (TCP); optional (ICMP) + var result = Parse(input); + + Assert.Equal(RunCommandParseError.None, result.Error); + Assert.Equal(target, result.Target); + Assert.Equal(port, result.Argument); + } + + [Theory] + [InlineData("rdp 10.0.0.1 foo", "foo")] [InlineData("dns borntoberoot.net 1.1.1.1 8.8.8.8", "8.8.8.8")] [InlineData("dns borntoberoot.net a aaaa 1.1.1.1", "aaaa")] public void UnknownArgument(string input, string unknown) diff --git a/Source/NETworkManager.Validators/PingMonitorPortOrPortProfileValidator.cs b/Source/NETworkManager.Validators/PingMonitorPortOrPortProfileValidator.cs new file mode 100644 index 0000000000..037b058159 --- /dev/null +++ b/Source/NETworkManager.Validators/PingMonitorPortOrPortProfileValidator.cs @@ -0,0 +1,22 @@ +using System.Globalization; +using System.Windows.Controls; +using NETworkManager.Localization.Resources; +using NETworkManager.Models.Network; +using NETworkManager.Settings; + +namespace NETworkManager.Validators; + +/// +/// Validates the port of the TCP checks of the Ping Monitor: a port ("443" or "443/tcp") or the name of a port +/// profile of the Ping Monitor, see . +/// +public class PingMonitorPortOrPortProfileValidator : ValidationRule +{ + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + return PingMonitorPortProfile.TryResolvePort(value as string, SettingsManager.Current.PingMonitor_PortProfiles, + out _) + ? ValidationResult.ValidResult + : new ValidationResult(false, Strings.EnterValidPortOrPortProfile); + } +} diff --git a/Source/NETworkManager.Validators/PingMonitorPortProfileNameValidator.cs b/Source/NETworkManager.Validators/PingMonitorPortProfileNameValidator.cs new file mode 100644 index 0000000000..e5674c5836 --- /dev/null +++ b/Source/NETworkManager.Validators/PingMonitorPortProfileNameValidator.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 port profile of the Ping Monitor, see +/// (the name is entered instead of a port). +/// +public class PingMonitorPortProfileNameValidator : ValidationRule +{ + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + return PingMonitorPortProfile.IsValidName(value as string) + ? ValidationResult.ValidResult + : new ValidationResult(false, Strings.ErrorMessage_PingMonitorPortProfileNameInvalid); + } +} diff --git a/Source/NETworkManager/ApplicationRequest.cs b/Source/NETworkManager/ApplicationRequest.cs index 9842db29ca..520337803c 100644 --- a/Source/NETworkManager/ApplicationRequest.cs +++ b/Source/NETworkManager/ApplicationRequest.cs @@ -127,6 +127,14 @@ public sealed record LookupRequest() : ApplicationRequest(ApplicationName.Lookup /// Request to show a tab of a tool (e.g. the IP Scanner tab that sent a notification). Only the tool is shown if the /// tab was closed (or is in another window). /// +public sealed record PingMonitorRequest() : ApplicationRequest(ApplicationName.PingMonitor) +{ + /// + /// Port or port profile of a TCP check as entered (e.g. "443", "443/tcp" or "HTTPS"), null for ICMP. + /// + public string Port { get; init; } +} + public sealed record ShowTabRequest : ApplicationRequest { /// diff --git a/Source/NETworkManager/InputSuggestions.cs b/Source/NETworkManager/InputSuggestions.cs index d601875cb9..1e302e9caa 100644 --- a/Source/NETworkManager/InputSuggestions.cs +++ b/Source/NETworkManager/InputSuggestions.cs @@ -7,6 +7,7 @@ using System.Windows.Data; using NETworkManager.Controls; using NETworkManager.Localization.Resources; +using NETworkManager.Models.Network; using NETworkManager.Settings; namespace NETworkManager; @@ -81,6 +82,19 @@ public static InputSuggestions ForPortScannerPorts() Strings.PortProfiles, SettingsManager.Current.PortScanner_PortHistory); } + /// + /// Creates the list for the port of the TCP checks of the Ping Monitor: its port profiles (sorted by name, with + /// their port, e.g. "HTTPS" - "443/tcp") and the port history. + /// + public static InputSuggestions ForPingMonitorPort() + { + return new InputSuggestions(SettingsManager.Current.PingMonitor_PortProfiles, + () => SettingsManager.Current.PingMonitor_PortProfiles + .OrderBy(x => x.Name, StringComparer.OrdinalIgnoreCase) + .Select(x => (x.Name, PingMonitorPortProfile.Format(x.Port))), + Strings.PortProfiles, SettingsManager.Current.PingMonitor_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 diff --git a/Source/NETworkManager/MainWindow.xaml.cs b/Source/NETworkManager/MainWindow.xaml.cs index 8ef505c9e6..01d0f11454 100644 --- a/Source/NETworkManager/MainWindow.xaml.cs +++ b/Source/NETworkManager/MainWindow.xaml.cs @@ -513,6 +513,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.PingMonitor_PortProfiles = [.. PingMonitorPortProfile.GetDefaultList()]; SettingsManager.Current.MDNSDiscovery_ServiceTypeProfiles = [.. MDNSServiceTypeProfile.GetDefaultList()]; SettingsManager.Current.DNSLookup_DNSServers = [.. DNSServer.GetDefaultList()]; SettingsManager.Current.SNMP_OidProfiles = [.. SNMPOIDProfile.GetDefaultList()]; diff --git a/Source/NETworkManager/ProfileDialogManager.cs b/Source/NETworkManager/ProfileDialogManager.cs index eefaa6d701..a8ad81c71d 100644 --- a/Source/NETworkManager/ProfileDialogManager.cs +++ b/Source/NETworkManager/ProfileDialogManager.cs @@ -28,6 +28,8 @@ private static ProfileInfo ParseProfileInfo(ProfileViewModel instance) // are saved as well (used if one can't be found, e.g. a profile file from another computer) var (portScannerPorts, portScannerPortsInput) = PortProfile.Encode(instance.PortScanner_Ports, SettingsManager.Current.PortScanner_PortProfiles); + var (pingMonitorPort, pingMonitorPortInput) = PingMonitorPortProfile.Encode(instance.PingMonitor_Port, + SettingsManager.Current.PingMonitor_PortProfiles); var (dnsLookupDNSServer, dnsLookupDNSServerInput) = DNSServer.Encode(instance.DNSLookup_DNSServer, SettingsManager.Current.DNSLookup_DNSServers); @@ -88,6 +90,10 @@ private static ProfileInfo ParseProfileInfo(ProfileViewModel instance) // Ping Monitor PingMonitor_Enabled = instance.PingMonitor_Enabled, + PingMonitor_Method = instance.PingMonitor_Method, + PingMonitor_Port = pingMonitorPort, + PingMonitor_PortInput = pingMonitorPortInput, + PingMonitor_OverrideMethod = instance.PingMonitor_OverrideMethod, PingMonitor_InheritHost = instance.PingMonitor_InheritHost, PingMonitor_Host = instance.PingMonitor_InheritHost ? instance.Host?.Trim() @@ -320,6 +326,8 @@ private static GroupInfo ParseGroupInfo(GroupViewModel instance) // Like the profile (see ParseProfileInfo) var (portScannerPorts, portScannerPortsInput) = PortProfile.Encode(instance.PortScanner_Ports, SettingsManager.Current.PortScanner_PortProfiles); + var (pingMonitorPort, pingMonitorPortInput) = PingMonitorPortProfile.Encode(instance.PingMonitor_Port, + SettingsManager.Current.PingMonitor_PortProfiles); var (dnsLookupDNSServer, dnsLookupDNSServerInput) = DNSServer.Encode(instance.DNSLookup_DNSServer, SettingsManager.Current.DNSLookup_DNSServers); @@ -350,6 +358,12 @@ private static GroupInfo ParseGroupInfo(GroupViewModel instance) PortScanner_Ports = portScannerPorts, PortScanner_PortsInput = portScannerPortsInput, + // Ping Monitor + PingMonitor_OverrideMethod = instance.PingMonitor_OverrideMethod, + PingMonitor_Method = instance.PingMonitor_Method, + PingMonitor_Port = pingMonitorPort, + PingMonitor_PortInput = pingMonitorPortInput, + // DNS Lookup DNSLookup_OverrideDNSServer = instance.DNSLookup_OverrideDNSServer, DNSLookup_DNSServer = dnsLookupDNSServer, diff --git a/Source/NETworkManager/RunCommandManager.cs b/Source/NETworkManager/RunCommandManager.cs index 6373ec35f5..7a274cc86a 100644 --- a/Source/NETworkManager/RunCommandManager.cs +++ b/Source/NETworkManager/RunCommandManager.cs @@ -112,6 +112,15 @@ public static IEnumerable GetDNSServers() return SettingsManager.Current.DNSLookup_DNSServers.Select(x => x.Name); } + /// + /// Gets the port profiles of the Ping Monitor (e.g. "HTTPS"), which can be used instead of a port. + /// + /// Port profiles. + public static IEnumerable GetPingMonitorPortProfiles() + { + return SettingsManager.Current.PingMonitor_PortProfiles; + } + /// /// Gets the port profiles of the Port Scanner (e.g. "Webserver"), which can be used instead of ports. /// @@ -342,6 +351,7 @@ ApplicationName.Traceroute or ApplicationName.PowerShell or ApplicationName.PuTT ValidationRule argumentValidator = result.Command.Argument switch { RunCommandArgument.Ports => new PortsOrPortProfilesValidator(), + RunCommandArgument.Port => new PingMonitorPortOrPortProfileValidator(), RunCommandArgument.Broadcast => new IPv4AddressValidator(), _ => null }; @@ -451,6 +461,13 @@ private static ApplicationRequest CreateRequest(RunCommandParseResult result) Target = result.Target, Ports = result.Argument }, + // A port or port profile (e.g. "ping 10.0.0.1 443", "443/tcp" or "HTTPS"): a TCP check, resolved by the Ping + // Monitor (shown as entered) like the ports of the Port Scanner. Without it: ICMP. + ApplicationName.PingMonitor => new PingMonitorRequest + { + Target = result.Target, + Port = result.Argument + }, ApplicationName.WakeOnLAN => new WakeOnLANRequest { Target = result.Target, Broadcast = result.Argument }, ApplicationName.MDNSDiscovery => new MDNSDiscoveryRequest { @@ -496,7 +513,13 @@ static RunCommandSyntaxPart Argument(string name) => RunCommandSyntaxPart.Required(RunCommandSyntaxPartKind.Argument, $"{Strings.Ports} | {Strings.PortProfile}") ], RunCommandArgument.Ports), - ApplicationName.PingMonitor => Create(name, ["ping"], [Target(Strings.Hosts)]), + // A port or a port profile of the Ping Monitor (TCP check); without it ICMP + ApplicationName.PingMonitor => Create(name, ["ping"], + [ + Target(Strings.Hosts), + RunCommandSyntaxPart.Optional(RunCommandSyntaxPartKind.Argument, + $"{Strings.Port} | {Strings.PortProfile}") + ], RunCommandArgument.Port), ApplicationName.Traceroute => Create(name, ["trace", "tracert"], [Target(Strings.Host)]), ApplicationName.DNSLookup => Create(name, ["dns", "nslookup"], [Target(Strings.Hosts), Argument(Strings.DNSServer), type], RunCommandArgument.DNSServer, diff --git a/Source/NETworkManager/ViewModels/GroupViewModel.cs b/Source/NETworkManager/ViewModels/GroupViewModel.cs index a0214cd7a2..47e20de8cf 100644 --- a/Source/NETworkManager/ViewModels/GroupViewModel.cs +++ b/Source/NETworkManager/ViewModels/GroupViewModel.cs @@ -123,6 +123,77 @@ public string Description #endregion + #region Ping Monitor + + /// + /// Gets or sets whether the protocol and port override the input of the Ping Monitor for the profiles of the group. + /// + public bool PingMonitor_OverrideMethod + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + OnPropertyChanged(nameof(PingMonitor_IsPortEnabled)); + } + } + + public IReadOnlyList PingMonitor_MethodItems { get; } = + [HostMonitorMethod.ICMP, HostMonitorMethod.TCP]; + + public HostMonitorMethod PingMonitor_Method + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + OnPropertyChanged(nameof(PingMonitor_IsPortEnabled)); + } + } + + /// + /// Gets whether the port can be changed: the protocol is overridden and it is TCP (ICMP has no port). + /// + public bool PingMonitor_IsPortEnabled => PingMonitor_OverrideMethod && PingMonitor_Method == HostMonitorMethod.TCP; + + /// + /// Gets or sets the port input: a port ("443" or "443/tcp") or the name of a port profile of the Ping Monitor. + /// + public string PingMonitor_Port + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + private readonly InputSuggestions _pingMonitorPortSuggestions = InputSuggestions.ForPingMonitorPort(); + + /// + /// Gets the port profiles and the port history of the Ping Monitor for the port input (grouped). + /// + public ICollectionView PingMonitor_PortSuggestions => _pingMonitorPortSuggestions.View; + + /// + /// Gets the names of the port profiles for the Tab completion of the port input of the Ping Monitor. + /// + public IEnumerable PingMonitor_PortProfileNames => _pingMonitorPortSuggestions.ProfileNames; + + #endregion + #region Port Scanner public bool PortScanner_OverridePorts @@ -1459,6 +1530,11 @@ public GroupViewModel(Action saveCommand, Action groupInfo.IPScanner_WindowsPassword, IsProfileFileEncrypted); // Port Scanner + PingMonitor_OverrideMethod = groupInfo.PingMonitor_OverrideMethod; + PingMonitor_Method = groupInfo.PingMonitor_Method; + PingMonitor_Port = PingMonitorPortProfile.Decode(groupInfo.PingMonitor_Port, groupInfo.PingMonitor_PortInput, + SettingsManager.Current.PingMonitor_PortProfiles, out _); + PortScanner_OverridePorts = groupInfo.PortScanner_OverridePorts; PortScanner_Ports = PortProfile.Decode(groupInfo.PortScanner_Ports, groupInfo.PortScanner_PortsInput, SettingsManager.Current.PortScanner_PortProfiles, out _); diff --git a/Source/NETworkManager/ViewModels/PingMonitorHostViewModel.cs b/Source/NETworkManager/ViewModels/PingMonitorHostViewModel.cs index 30459c0677..9a86c496ce 100644 --- a/Source/NETworkManager/ViewModels/PingMonitorHostViewModel.cs +++ b/Source/NETworkManager/ViewModels/PingMonitorHostViewModel.cs @@ -12,6 +12,7 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Globalization; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; @@ -241,6 +242,70 @@ private set } } + /// + /// Gets the methods to check the hosts with (drop-down of the input). + /// + public IReadOnlyList HostMonitorMethods { get; } = + [HostMonitorMethod.ICMP, HostMonitorMethod.TCP]; + + /// + /// Gets or sets the method of the checks of the hosts to add. The method used to add the hosts is remembered + /// (setting), it is the default of the next input. + /// + public HostMonitorMethod Method + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + OnPropertyChanged(nameof(IsTcp)); + } + } = SettingsManager.Current.PingMonitor_Method; + + /// + /// Gets whether the hosts are checked with TCP (the ports input is enabled). + /// + public bool IsTcp => Method == HostMonitorMethod.TCP; + + private readonly InputSuggestions _portSuggestions = InputSuggestions.ForPingMonitorPort(); + + /// + /// Gets the port profiles and the port history for the port input (grouped). + /// + public ICollectionView PortSuggestions => _portSuggestions.View; + + /// + /// Gets the names of the port profiles for the Tab completion of the port input. + /// + public IEnumerable PortProfileNames => _portSuggestions.ProfileNames; + + /// + /// Gets or sets the port of the TCP checks: a port ("443" or "443/tcp") or the name of a port profile (e.g. + /// "HTTPS"). One port per host - the Ping Monitor is not a port scanner. Starts with the last port. + /// + public string Port + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = SettingsManager.Current.PingMonitor_PortHistory.FirstOrDefault() ?? GlobalStaticConfiguration.PingMonitor_Port; + + /// + /// Warning for the next start: the port profile of the profile was not found, its saved port is used. Only shown + /// while the port is unchanged. + /// + private (string Port, string Message)? _portWarning; + /// /// Gets or sets the host to ping. /// @@ -278,6 +343,7 @@ public bool IsRunning } } + /// /// Gets or sets a value indicating whether the ping monitor is canceling. /// @@ -618,7 +684,7 @@ private void SetHostViewsExpanded(string group, bool expanded) private bool MatchesFilter(PingMonitorViewModel host) { return PingMonitorHostFilter.Matches(host, ShowUp, ShowDown, ShowPaused, HostsSearch, host.Title, - host.IPAddress.ToString(), host.Hostname, host.Group); + host.IPAddress.ToString(), host.Hostname, host.Group, host.MethodText); } /// @@ -697,9 +763,20 @@ public void SetGroupExpanded(string group, bool expanded) /// /// Host(s) to ping. /// Starts the ping monitor. If false, the host is only filled in. - public void AddHost(string host, bool start = true) + /// Port or port profile of a TCP check (e.g. the run command "ping host 443"), null to keep the + /// method and port of the input. + public void AddHost(string host, bool start = true, string port = null) { - if (SetHost(host) && start) + if (!SetHost(host)) + return; + + if (!string.IsNullOrWhiteSpace(port)) + { + Method = HostMonitorMethod.TCP; + Port = port; + } + + if (start) _ = Start(); } @@ -710,7 +787,23 @@ public void AddHost(string host, bool start = true) /// Starts the ping monitor. If false, the host is only filled in. public void AddHost(ProfileInfo profile, bool start = true) { - if (SetHost(profile.PingMonitor_Host, profile.Group) && start) + if (!SetHost(profile.PingMonitor_Host, profile.Group)) + return; + + // Protocol and port of the profile or of its group (if overridden), otherwise the input is kept (like the DNS + // server of DNS Lookup) + var (method, port) = + NETworkManager.Profiles.Application.PingMonitor.GetMethodAndPort(profile, out var portProfileNotFound); + + if (method is { } profileMethod) + Method = profileMethod; + + if (port != null) + Port = port; + + _portWarning = portProfileNotFound ? (Port, Strings.PingMonitorPortProfileOfProfileNotFoundMessage) : null; + + if (start) _ = Start(); } @@ -762,6 +855,28 @@ public async Task Start() var input = Host; var group = _group != null && input == _groupHost ? _group : Strings.Hosts; + // The method and port when the start was requested (they can be changed while the hosts are resolved) + var method = Method; + var portInput = Port; + + // The warning of the profile applies to its port only + var portWarning = _portWarning is { } warning && warning.Port == portInput ? warning.Message : null; + _portWarning = null; + + // TCP: one port (a port profile is replaced by its port); ICMP has no port (0). The input is validated, but a + // port profile may have been renamed or deleted since. + var port = 0; + + if (method == HostMonitorMethod.TCP && + !PingMonitorPortProfile.TryResolvePort(portInput, SettingsManager.Current.PingMonitor_PortProfiles, out port)) + { + StatusMessage = Strings.EnterValidPortOrPortProfile; + StatusMessageLevel = StatusLevel.Error; + IsStatusMessageDisplayed = true; + + return; + } + // Refuse inputs that can't get below the limit (e.g. 10.0.0.0/8) before they are resolved (memory, time). The // limits of the Ping Monitor are checked after the exclusions and the already monitored hosts were removed // (see below), so e.g. a /16 with exclusions is still possible. @@ -794,6 +909,9 @@ public async Task Start() IsStatusMessageDisplayed = false; IsRunning = true; + if (portWarning != null) + AddStatusMessage(portWarning, StatusLevel.Warning); + _cancellationTokenSource?.Dispose(); _cancellationTokenSource = new CancellationTokenSource(); @@ -834,9 +952,11 @@ public async Task Start() return; } - // Hosts already monitored in the group are skipped (the same IP address in another group is added) - var (hostsToAdd, alreadyMonitored) = PingMonitorHostHelper.SplitAlreadyMonitored(hosts.hosts, - Hosts.Where(x => x.Group == group).Select(x => x.ViewModel.IPAddress)); + // Hosts already monitored in the group with the method and port are skipped (the same IP address in another + // group, with another method or port is added) + var (hostsToAdd, alreadyMonitored) = PingMonitorHostHelper.SplitAlreadyMonitored(hosts.hosts, [port], + Hosts.Where(x => x.Group == group && x.ViewModel.Method == method) + .Select(x => (x.ViewModel.IPAddress, x.ViewModel.Port))); // Every host is pinged continuously and has its own chart: refuse too many hosts (e.g. a /16) instead of // freezing the application and ask before adding many - counted without the exclusions and the already @@ -867,14 +987,23 @@ public async Task Start() ListHelper.Modify(SettingsManager.Current.PingMonitor_HostHistory, input, SettingsManager.Current.General_HistoryListEntries); + // Remember the method (default of the next input) and the port (history; a port profile is already in the list, + // like the ports of the Port Scanner) + SettingsManager.Current.PingMonitor_Method = method; + + if (method == HostMonitorMethod.TCP && + PingMonitorPortProfile.FindByName(SettingsManager.Current.PingMonitor_PortProfiles, portInput) == null) + ListHelper.Modify(SettingsManager.Current.PingMonitor_PortHistory, portInput.Trim(), + SettingsManager.Current.General_HistoryListEntries); + if (alreadyMonitored.Count > 0) AddStatusMessage( - $"{Strings.TheFollowingHostsAreAlreadyMonitoredInThisGroup} {string.Join(", ", alreadyMonitored.Select(x => NotificationLine.FormatHost(x.ipAddress, x.hostname)))}", + $"{Strings.TheFollowingHostsAreAlreadyMonitoredInThisGroup} {string.Join(", ", alreadyMonitored.Select(x => NotificationLine.JoinText(NotificationLine.FormatHost(x.host.ipAddress, x.host.hostname), method == HostMonitorMethod.TCP ? PingMonitorPortProfile.Format(x.port) : null)))}", StatusLevel.None); // Add host(s) to list and start the ping - foreach (var hostView in hostsToAdd.Select(currentHost => - new PingMonitorView(Guid.NewGuid(), RemoveHostByGuid, currentHost, group))) + foreach (var hostView in hostsToAdd.Select(x => + new PingMonitorView(Guid.NewGuid(), RemoveHostByGuid, x.host, group, method, x.port))) { // Check if the user has canceled the operation if (_cancellationTokenSource.IsCancellationRequested) @@ -1113,7 +1242,7 @@ private static void ShowStatusNotification(List<(PingMonitorViewModel Host, bool var (host, isUp) = changes[0]; notification = new NotificationInfo(ApplicationName.PingMonitor, status, host.NotificationHostDisplay, - [GetNotificationLine(host.NotificationIPAddress, isUp)], + [GetNotificationLine(JoinNotificationText(host.NotificationIPAddress, host.NotificationPort), isUp)], SettingsManager.Current.PingMonitor_NotificationCloseTime); } else @@ -1125,7 +1254,9 @@ private static void ShowStatusNotification(List<(PingMonitorViewModel Host, bool // "10.0.0.5 (server) · Down", the hosts that don't fit as "(+47 more) · Down" var lines = changes.Select(x => GetNotificationLine( - NotificationLine.FormatHost(x.Host.IPAddress, DNSClientHelper.SanitizeHostname(x.Host.Hostname)), + JoinNotificationText( + NotificationLine.FormatHost(x.Host.IPAddress, DNSClientHelper.SanitizeHostname(x.Host.Hostname)), + x.Host.NotificationPort), x.IsUp)).ToList(); // The group if all hosts are in the same group, otherwise the tool @@ -1142,6 +1273,16 @@ private static void ShowStatusNotification(List<(PingMonitorViewModel Host, bool /// /// Line of a notification with the status of the change (up / down). /// + /// + /// Joins the parts of a notification line ("10.0.0.5 (server) · 443/tcp"), null if all parts are empty. + /// + private static string JoinNotificationText(params string[] parts) + { + var text = NotificationLine.JoinText(parts); + + return text.Length > 0 ? text : null; + } + private static NotificationLine GetNotificationLine(string text, bool isUp) { return isUp diff --git a/Source/NETworkManager/ViewModels/PingMonitorPortProfileViewModel.cs b/Source/NETworkManager/ViewModels/PingMonitorPortProfileViewModel.cs new file mode 100644 index 0000000000..9499c871f8 --- /dev/null +++ b/Source/NETworkManager/ViewModels/PingMonitorPortProfileViewModel.cs @@ -0,0 +1,147 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Windows.Input; +using NETworkManager.Models.Network; +using NETworkManager.Settings; +using NETworkManager.Utilities; + +namespace NETworkManager.ViewModels; + +/// +/// ViewModel to add or edit a port profile of the Ping Monitor (a name and one port). +/// +public class PingMonitorPortProfileViewModel : ViewModelBase +{ + private readonly PingMonitorPortProfileInfo _info; + private readonly bool _isLoading; + + /// + /// Initializes a new instance of the class. + /// + /// The action to execute when saving. + /// The action to execute when cancelling. + /// Indicates whether the port profile is being edited. + /// The port profile to edit. + public PingMonitorPortProfileViewModel(Action saveCommand, + Action cancelHandler, bool isEdited = false, + PingMonitorPortProfileInfo info = null) + { + _isLoading = true; + + SaveCommand = new RelayCommand(_ => saveCommand(this)); + CancelCommand = new RelayCommand(_ => cancelHandler(this)); + + IsEdited = isEdited; + + _info = info ?? new PingMonitorPortProfileInfo(); + + // Names of the other port profiles - a name is entered instead of a port, it must be unique + UsedNames = [.. SettingsManager.Current.PingMonitor_PortProfiles.Where(x => !ReferenceEquals(x, info)) + .Select(x => x.Name)]; + + Name = _info.Name; + Port = info != null ? _info.Port.ToString(CultureInfo.InvariantCulture) : string.Empty; + + _isLoading = false; + } + + /// + /// Gets the names of the other port profiles (the name must be unique). + /// + public List UsedNames { get; } + + /// + /// Gets the command to save the port profile. + /// + public ICommand SaveCommand { get; } + + /// + /// Gets the command to cancel the operation. + /// + public ICommand CancelCommand { get; } + + /// + /// Gets or sets the name of the port profile. + /// + public string Name + { + get; + set + { + if (field == value) + return; + + field = value; + + if (!_isLoading) + Validate(); + + OnPropertyChanged(); + } + } + + /// + /// Gets or sets the port (validated in the view). + /// + public string Port + { + get; + set + { + if (field == value) + return; + + field = value; + + if (!_isLoading) + Validate(); + + OnPropertyChanged(); + } + } + + /// + /// Gets the port as number (the input is validated before it can be saved). + /// + public int PortNumber => int.Parse(Port.Trim(), NumberStyles.None, CultureInfo.InvariantCulture); + + /// + /// Gets or sets a value indicating whether the port profile has changed. + /// + public bool InfoChanged + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets or sets a value indicating whether the port profile is being edited. + /// + public bool IsEdited + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + private void Validate() + { + InfoChanged = _info.Name != Name || + _info.Port.ToString(CultureInfo.InvariantCulture) != Port?.Trim(); + } +} diff --git a/Source/NETworkManager/ViewModels/PingMonitorSettingsViewModel.cs b/Source/NETworkManager/ViewModels/PingMonitorSettingsViewModel.cs index f862d0f26b..75011299ea 100644 --- a/Source/NETworkManager/ViewModels/PingMonitorSettingsViewModel.cs +++ b/Source/NETworkManager/ViewModels/PingMonitorSettingsViewModel.cs @@ -1,4 +1,17 @@ +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; @@ -11,6 +24,43 @@ public class PingMonitorSettingsViewModel : ViewModelBase private readonly bool _isLoading; + /// + /// Gets the port profiles of the TCP checks (sorted by name). + /// + public ICollectionView PortProfiles { get; } + + /// + /// Gets or sets the selected port profile. + /// + public PingMonitorPortProfileInfo SelectedPortProfile + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets or sets the selected port profiles (several can be deleted at once). + /// + public IList SelectedPortProfiles + { + get; + set + { + if (Equals(value, field)) + return; + + field = value; + OnPropertyChanged(); + } + } = new ArrayList(); + /// /// Gets or sets the timeout in milliseconds. /// @@ -87,6 +137,44 @@ public bool DontFragment } } + /// + /// Gets or sets the timeout of TCP checks in milliseconds. + /// + public int TCPTimeout + { + get; + set + { + if (value == field) + return; + + if (!_isLoading) + SettingsManager.Current.PingMonitor_TCPTimeout = value; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets or sets the wait time between the TCP checks in milliseconds. + /// + public int TCPWaitTime + { + get; + set + { + if (value == field) + return; + + if (!_isLoading) + SettingsManager.Current.PingMonitor_TCPWaitTime = value; + + field = value; + OnPropertyChanged(); + } + } + /// /// Gets or sets the wait time between pings in milliseconds. /// @@ -269,6 +357,13 @@ public PingMonitorSettingsViewModel() { _isLoading = true; + // Own view (not the default view of the collection), sort and selection only apply to the settings + PortProfiles = new CollectionViewSource { Source = SettingsManager.Current.PingMonitor_PortProfiles }.View; + PortProfiles.SortDescriptions.Add( + new SortDescription(nameof(PingMonitorPortProfileInfo.Name), ListSortDirection.Ascending)); + + SelectFirstPortProfile(); + LoadSettings(); _isLoading = false; @@ -281,6 +376,8 @@ private void LoadSettings() TTL = SettingsManager.Current.PingMonitor_TTL; DontFragment = SettingsManager.Current.PingMonitor_DontFragment; WaitTime = SettingsManager.Current.PingMonitor_WaitTime; + TCPTimeout = SettingsManager.Current.PingMonitor_TCPTimeout; + TCPWaitTime = SettingsManager.Current.PingMonitor_TCPWaitTime; ExpandHostView = SettingsManager.Current.PingMonitor_ExpandHostView; ChartTime = SettingsManager.Current.PingMonitor_ChartTime; HistoryHours = SettingsManager.Current.PingMonitor_HistoryHours; @@ -292,4 +389,145 @@ private void LoadSettings() } #endregion -} \ No newline at end of file + + #region ICommand & Actions + + public ICommand AddPortProfileCommand => new RelayCommand(_ => AddPortProfileAction()); + + private void AddPortProfileAction() + { + _ = AddPortProfile(); + } + + public ICommand EditPortProfileCommand => + new RelayCommand(_ => EditPortProfileAction(), EditPortProfile_CanExecute); + + /// + /// Checks if exactly one port profile is selected (e.g. F2 without a selection or with several selected). + /// + private bool EditPortProfile_CanExecute(object parameter) + { + return SelectedPortProfile != null && SelectedPortProfiles.Count == 1; + } + + private void EditPortProfileAction() + { + _ = EditPortProfile(); + } + + public ICommand DeletePortProfileCommand => + new RelayCommand(_ => DeletePortProfileAction(), DeletePortProfile_CanExecute); + + /// + /// Checks if at least one port profile is selected (e.g. Del without a selection). + /// + private bool DeletePortProfile_CanExecute(object parameter) + { + return SelectedPortProfiles.Count > 0; + } + + private void DeletePortProfileAction() + { + _ = DeletePortProfile(); + } + + #endregion + + #region Methods + + private Task AddPortProfile() + { + var childWindow = new PingMonitorPortProfileChildWindow(); + + var childWindowViewModel = new PingMonitorPortProfileViewModel(instance => + { + childWindow.IsOpen = false; + ConfigurationManager.Current.IsChildWindowOpen = false; + + SettingsManager.Current.PingMonitor_PortProfiles.Add( + new PingMonitorPortProfileInfo(instance.Name.Trim(), instance.PortNumber)); + }, _ => + { + childWindow.IsOpen = false; + ConfigurationManager.Current.IsChildWindowOpen = false; + }); + + childWindow.Title = Strings.AddPortProfile; + + childWindow.DataContext = childWindowViewModel; + + ConfigurationManager.Current.IsChildWindowOpen = true; + + return Application.Current.MainWindow.ShowChildWindowAsync(childWindow); + } + + public Task EditPortProfile() + { + var childWindow = new PingMonitorPortProfileChildWindow(); + + var portProfile = SelectedPortProfile; + + var childWindowViewModel = new PingMonitorPortProfileViewModel(instance => + { + childWindow.IsOpen = false; + ConfigurationManager.Current.IsChildWindowOpen = false; + + // Same ID, profiles and groups that reference the port profile still find it (also with a new name) + var editedPortProfile = new PingMonitorPortProfileInfo(instance.Name.Trim(), instance.PortNumber); + + if (portProfile.Id != Guid.Empty) + editedPortProfile.Id = portProfile.Id; + + SettingsManager.Current.PingMonitor_PortProfiles.Remove(portProfile); + SettingsManager.Current.PingMonitor_PortProfiles.Add(editedPortProfile); + }, _ => + { + childWindow.IsOpen = false; + ConfigurationManager.Current.IsChildWindowOpen = false; + }, true, + portProfile); + + childWindow.Title = Strings.EditPortProfile; + + childWindow.DataContext = childWindowViewModel; + + ConfigurationManager.Current.IsChildWindowOpen = true; + + return Application.Current.MainWindow.ShowChildWindowAsync(childWindow); + } + + /// + /// Deletes the selected port profiles (after a confirmation that lists them). + /// + private async Task DeletePortProfile() + { + var portProfiles = SelectedPortProfiles.Cast().ToList(); + + var result = await DialogHelper.ShowConfirmationMessageAsync(Application.Current.MainWindow, + portProfiles.Count == 1 ? Strings.DeletePortProfile : Strings.DeletePortProfiles, + (portProfiles.Count == 1 ? Strings.DeletePortProfileMessage : Strings.DeletePortProfilesMessage) + + Environment.NewLine + Environment.NewLine + + DialogHelper.FormatItemList([.. portProfiles.Select(x => x.Name)]), + ChildWindowIcon.Info, + Strings.Delete); + + if (!result) + return; + + foreach (var portProfile in portProfiles) + SettingsManager.Current.PingMonitor_PortProfiles.Remove(portProfile); + + SelectFirstPortProfile(); + } + + /// + /// Selects the first port profile (also in the list of selected port profiles, which the grid applies). + /// + private void SelectFirstPortProfile() + { + SelectedPortProfile = PortProfiles.Cast().FirstOrDefault(); + SelectedPortProfiles = SelectedPortProfile != null ? new ArrayList { SelectedPortProfile } : new ArrayList(); + } + + #endregion +} diff --git a/Source/NETworkManager/ViewModels/PingMonitorViewModel.cs b/Source/NETworkManager/ViewModels/PingMonitorViewModel.cs index b464335f4a..795fef97bb 100644 --- a/Source/NETworkManager/ViewModels/PingMonitorViewModel.cs +++ b/Source/NETworkManager/ViewModels/PingMonitorViewModel.cs @@ -14,6 +14,7 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Globalization; using System.Linq; using System.Net; using System.Net.NetworkInformation; @@ -40,8 +41,11 @@ public class PingMonitorViewModel : ViewModelBase, IPingMonitorHostStatus /// Action to remove the host by its GUID. /// Tuple containing the IP address and hostname. /// The group name the host belongs to. + /// Method of the check (ICMP or TCP connect). + /// Port of a TCP check, ignored for ICMP. public PingMonitorViewModel(Guid hostId, Action removeHostByGuid, - (IPAddress ipAddress, string hostname) host, string group) + (IPAddress ipAddress, string hostname) host, string group, HostMonitorMethod method = HostMonitorMethod.ICMP, + int port = 0) { HostId = hostId; _removeHostByGuid = removeHostByGuid; @@ -51,6 +55,8 @@ public PingMonitorViewModel(Guid hostId, Action removeHostByGuid, IPAddress = host.ipAddress; Hostname = host.hostname; Group = group; + Method = method; + Port = port; InitialTimeChart(); @@ -87,6 +93,23 @@ public PingMonitorViewModel(Guid hostId, Action removeHostByGuid, // Wait time of the running pings (settings apply when the host is started) private int _waitTime = SettingsManager.Current.PingMonitor_WaitTime; + /// + /// Gets the method of the check (ICMP or TCP connect), fixed when the host is added. + /// + public HostMonitorMethod Method { get; } + + /// + /// Gets the port of a TCP check, 0 for ICMP. + /// + public int Port { get; } + + /// + /// Gets the tag shown next to the title, lowercase and technical: "icmp" or "443/tcp". + /// + public string MethodText => Method == HostMonitorMethod.TCP + ? PingMonitorPortProfile.Format(Port) + : HostMonitorMethod.ICMP.ToString().ToLowerInvariant(); + /// /// Gets the title of the monitor, typically "Hostname # IP". /// @@ -239,9 +262,45 @@ private set public string StatusTimeText => DateTimeHelper.DateTimeToTimeOrDateTimeString(StatusTime, DateTime.Now); /// - /// Gets the tooltip text for the connectivity icon, e.g. "Status change: 14:32:05". + /// Gets the tooltip text for the connectivity icon, e.g. "Status change: 14:32:05", with the status text of the last + /// check in a second line (e.g. "Port closed"). + /// + public string StatusTimeToolTip => StatusText == null + ? $"{Strings.StatusChange}: {StatusTimeText}" + : $"{Strings.StatusChange}: {StatusTimeText}{Environment.NewLine}{StatusText}"; + + /// + /// Gets the status text of the last check, null if there is none (e.g. "Port closed" for a TCP check of a closed + /// port). Shown in the tooltip, not an error. + /// + public string StatusText + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + OnPropertyChanged(nameof(StatusTimeToolTip)); + } + } + + /// + /// Gets the status text of a check (null if there is none). + /// + private static string GetStatusText(PingInfo info) + { + return info.Method == HostMonitorMethod.TCP && info.Status == IPStatus.DestinationPortUnreachable + ? Strings.PortClosed + : null; + } + + /// + /// Gets the port of a TCP check for the notification line ("443/tcp"), null for ICMP. /// - public string StatusTimeToolTip => $"{Strings.StatusChange}: {StatusTimeText}"; + public string NotificationPort => Method == HostMonitorMethod.TCP ? PingMonitorPortProfile.Format(Port) : null; /// /// Gets or sets the total number of ping packets transmitted. @@ -571,7 +630,10 @@ private void RedirectDataToApplicationAction(object name) ? hostname : IPAddress.ToString(); - NavigationManager.Open(new ApplicationRequest(applicationName) { Target = host }); + // A TCP host opens the Port Scanner with its port + NavigationManager.Open(applicationName == ApplicationName.PortScanner && Method == HostMonitorMethod.TCP + ? new PortScannerRequest { Target = host, Ports = Port.ToString(CultureInfo.InvariantCulture) } + : new ApplicationRequest(applicationName) { Target = host }); } /// @@ -622,6 +684,7 @@ public void Start() IsErrorMessageDisplayed = false; ErrorMessage = null; + StatusText = null; IsRunning = true; IsLiveMode = true; @@ -645,7 +708,9 @@ public void Start() IsReachable = false; // Settings of the ping apply when the host is (re)started - _waitTime = SettingsManager.Current.PingMonitor_WaitTime; + _waitTime = Method == HostMonitorMethod.TCP + ? SettingsManager.Current.PingMonitor_TCPWaitTime + : SettingsManager.Current.PingMonitor_WaitTime; // Reset chart _sessionStartTime = DateTime.Now; @@ -656,9 +721,11 @@ public void Start() UpdateMaxPingValues(); - var probe = new ICMPHostMonitorProbe(IPAddress, SettingsManager.Current.PingMonitor_Timeout, - GlobalStaticConfiguration.LimitICMPBuffer(SettingsManager.Current.PingMonitor_Buffer), - SettingsManager.Current.PingMonitor_TTL, SettingsManager.Current.PingMonitor_DontFragment); + IHostMonitorProbe probe = Method == HostMonitorMethod.TCP + ? new TCPHostMonitorProbe(IPAddress, Port, SettingsManager.Current.PingMonitor_TCPTimeout) + : new ICMPHostMonitorProbe(IPAddress, SettingsManager.Current.PingMonitor_Timeout, + GlobalStaticConfiguration.LimitICMPBuffer(SettingsManager.Current.PingMonitor_Buffer), + SettingsManager.Current.PingMonitor_TTL, SettingsManager.Current.PingMonitor_DontFragment); // The known hostname (typed, from DNS or resolved before) is kept, the PTR record is only resolved without one _hostMonitor = new HostMonitor(IPAddress, Hostname, probe) @@ -730,7 +797,7 @@ public Task Export() // Copied on the UI thread (the history is updated there while pinging), exported in the background var results = _pingInfoList.ToList(); - await Task.Run(() => ExportManager.Export(instance.FilePath, instance.FileType, results)); + await Task.Run(() => ExportManager.Export(instance.FilePath, instance.FileType, results, Method)); } catch (Exception ex) { @@ -845,6 +912,7 @@ private void OnPingReceived(PingReceivedArgs e) // A ping that failed with an error (e.g. no network) is counted as lost, the host keeps being pinged. The error // is shown (status icon tooltip) until a ping works again. + StatusText = GetStatusText(e.Args); ErrorMessage = e.ErrorMessage; IsErrorMessageDisplayed = e.ErrorMessage != null; diff --git a/Source/NETworkManager/ViewModels/ProfileViewModel.cs b/Source/NETworkManager/ViewModels/ProfileViewModel.cs index 41053f0d27..f14f6307ca 100644 --- a/Source/NETworkManager/ViewModels/ProfileViewModel.cs +++ b/Source/NETworkManager/ViewModels/ProfileViewModel.cs @@ -132,6 +132,10 @@ public ProfileViewModel(Action saveCommand, Action + /// Gets or sets whether the protocol and port override the ones of the group (or of the input of the Ping Monitor). + /// + public bool PingMonitor_OverrideMethod + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + OnPropertyChanged(nameof(PingMonitor_IsPortEnabled)); + } + } + + public IReadOnlyList PingMonitor_MethodItems { get; } = + [HostMonitorMethod.ICMP, HostMonitorMethod.TCP]; + + public HostMonitorMethod PingMonitor_Method + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + OnPropertyChanged(nameof(PingMonitor_IsPortEnabled)); + } + } + + /// + /// Gets whether the port can be changed: the protocol is overridden and it is TCP (ICMP has no port). + /// + public bool PingMonitor_IsPortEnabled => PingMonitor_OverrideMethod && PingMonitor_Method == HostMonitorMethod.TCP; + + /// + /// Gets or sets the port input: a port ("443" or "443/tcp") or the name of a port profile of the Ping Monitor. + /// + public string PingMonitor_Port + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + private readonly InputSuggestions _pingMonitorPortSuggestions = InputSuggestions.ForPingMonitorPort(); + + /// + /// Gets the port profiles and the port history of the Ping Monitor for the port input (grouped). + /// + public ICollectionView PingMonitor_PortSuggestions => _pingMonitorPortSuggestions.View; + + /// + /// Gets the names of the port profiles for the Tab completion of the port input of the Ping Monitor. + /// + public IEnumerable PingMonitor_PortProfileNames => _pingMonitorPortSuggestions.ProfileNames; + #endregion #region Traceroute diff --git a/Source/NETworkManager/ViewModels/RunCommandViewModel.cs b/Source/NETworkManager/ViewModels/RunCommandViewModel.cs index b60d6cf1e5..a53f370c37 100644 --- a/Source/NETworkManager/ViewModels/RunCommandViewModel.cs +++ b/Source/NETworkManager/ViewModels/RunCommandViewModel.cs @@ -1,5 +1,6 @@ using NETworkManager.Localization.Resources; using NETworkManager.Models; +using NETworkManager.Models.Network; using NETworkManager.Models.RunCommand; using NETworkManager.Controls; using NETworkManager.Profiles; @@ -669,6 +670,7 @@ .. GetProfileSuggestions().Take(MaxSuggestions) _ => [ .. GetDNSServerSuggestions().Take(MaxSuggestions), .. GetPortProfileSuggestions().Take(MaxSuggestions), + .. GetPingMonitorPortProfileSuggestions().Take(MaxSuggestions), .. GetDurationSuggestions().Take(MaxSuggestions), .. GetTypeSuggestions().Take(MaxSuggestions), .. GetHistorySuggestions().Take(MaxSuggestions) ] @@ -1152,6 +1154,17 @@ private IEnumerable GetPortProfileSuggestions() Strings.PortProfiles, isList: true); } + /// + /// Port profiles of the Ping Monitor (e.g. "HTTPS" - "443/tcp") that contain the typed word, if no port was + /// entered yet. One port per host, no list. + /// + private IEnumerable GetPingMonitorPortProfileSuggestions() + { + return GetArgumentValueSuggestions(RunCommandArgument.Port, + RunCommandManager.GetPingMonitorPortProfiles().Select(x => (x.Name, PingMonitorPortProfile.Format(x.Port))), + RunCommandSuggestionKind.PortProfile, Strings.PortProfiles); + } + /// /// DNS servers configured in the DNS lookup (e.g. "Cloudflare") that contain the typed word, if no DNS server was /// entered yet. Several DNS servers can be entered (e.g. "\"Google Public DNS\";cloudflare"), the entry after diff --git a/Source/NETworkManager/Views/GroupChildWindow.xaml b/Source/NETworkManager/Views/GroupChildWindow.xaml index 862201693c..694b4ded06 100644 --- a/Source/NETworkManager/Views/GroupChildWindow.xaml +++ b/Source/NETworkManager/Views/GroupChildWindow.xaml @@ -147,6 +147,29 @@ + + + + + + + @@ -482,6 +505,9 @@ + + + @@ -673,6 +699,66 @@ + + + + + + + + - - + + - + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Source/NETworkManager/Views/PingMonitorSettingsView.xaml.cs b/Source/NETworkManager/Views/PingMonitorSettingsView.xaml.cs index 547ebbf7fb..b764035eb7 100644 --- a/Source/NETworkManager/Views/PingMonitorSettingsView.xaml.cs +++ b/Source/NETworkManager/Views/PingMonitorSettingsView.xaml.cs @@ -1,4 +1,5 @@ -using NETworkManager.ViewModels; +using System.Windows.Input; +using NETworkManager.ViewModels; namespace NETworkManager.Views; @@ -11,4 +12,10 @@ public PingMonitorSettingsView() InitializeComponent(); DataContext = _viewModel; } -} \ No newline at end of file + + private void DataGridRow_MouseDoubleClick(object sender, MouseButtonEventArgs e) + { + if (_viewModel.EditPortProfileCommand.CanExecute(null)) + _viewModel.EditPortProfileCommand.Execute(null); + } +} diff --git a/Source/NETworkManager/Views/PingMonitorView.xaml b/Source/NETworkManager/Views/PingMonitorView.xaml index f0ba5aeff9..a90a96cc23 100644 --- a/Source/NETworkManager/Views/PingMonitorView.xaml +++ b/Source/NETworkManager/Views/PingMonitorView.xaml @@ -301,7 +301,7 @@ + Text="{Binding MethodText}" Style="{StaticResource TagTextBlock}" />