diff --git a/AGENTS.md b/AGENTS.md index 66a726bd65..9defa01725 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -562,7 +562,8 @@ SemiBold (section headers), `MessageTextBlock` 16 gray (messages in empty areas) - Inputs: radius 4, focus border gray (`Gray5`), hover border `Brushes.Control.Border.MouseOver`. - Drop-downs: `ComboBoxPopupBehavior` (rounded popup with shadow), implicit `ComboBoxItem` style in `DefaultComboBox`. - Progress: `DefaultMetroProgressBar` (accent on a subtle track) and `ProgressRingSmall` / `Medium` / `Large` - (16 inline / 24 dialogs / 48 centered, `ProgressBarStyles.xaml`); scanner progress via `SmoothProgress.Value`. + (16 inline / 24 dialogs / 48 centered, `ProgressBarStyles.xaml`); scanner progress and countdowns (status window, + notifications) via `SmoothProgress.Value`. - Dialogs: `DefaultChildWindow` (own template, radius 8, shadow, overlay, zoom animation) for all dialogs. - Status values in lists (e.g. firewall action, TCP / neighbor state): `StatusDot` (8 px `Ellipse` in front of the text, `Tag` = `StatusLevel` None / Success / Warning / Error via a `*ToStatusLevelConverter`), text in the normal color. diff --git a/Source/NETworkManager.Localization/ResourceIdentifier.cs b/Source/NETworkManager.Localization/ResourceIdentifier.cs index 03f97b2f4f..c812c623c9 100644 --- a/Source/NETworkManager.Localization/ResourceIdentifier.cs +++ b/Source/NETworkManager.Localization/ResourceIdentifier.cs @@ -6,6 +6,7 @@ public enum ResourceIdentifier AccentGlowIntensity, AnimationMode, ApplicationName, + ConnectionCheckReason, LLDPCDPProtocol, IPStatus, PortState, diff --git a/Source/NETworkManager.Localization/Resources/Strings.Designer.cs b/Source/NETworkManager.Localization/Resources/Strings.Designer.cs index 0f7c6c2a87..66834eb7fe 100644 --- a/Source/NETworkManager.Localization/Resources/Strings.Designer.cs +++ b/Source/NETworkManager.Localization/Resources/Strings.Designer.cs @@ -1005,6 +1005,15 @@ public static string AllSettingsCanBeChangedLaterInTheSettings { } } + /// + /// Looks up a localized string similar to All widgets are hidden. You can show them in the settings of the dashboard.. + /// + public static string AllWidgetsAreHiddenMessage { + get { + return ResourceManager.GetString("AllWidgetsAreHiddenMessage", resourceCulture); + } + } + /// /// Looks up a localized string similar to Always show icon in tray. /// @@ -2611,6 +2620,150 @@ public static string Connection { } } + /// + /// Looks up a localized string similar to Windows reports limited internet access (e.g. a hotspot / captive portal that requires a sign-in).. + /// + public static string ConnectionCheckReason_CaptivePortal { + get { + return ResourceManager.GetString("ConnectionCheckReason_CaptivePortal", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The DNS server did not answer or returned an error.. + /// + public static string ConnectionCheckReason_DNSError { + get { + return ResourceManager.GetString("ConnectionCheckReason_DNSError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The gateway did not reply to the ping. It may be offline or block ICMP.. + /// + public static string ConnectionCheckReason_GatewayNoReply { + get { + return ResourceManager.GetString("ConnectionCheckReason_GatewayNoReply", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No reply to the ping and no public IP address from the API, but Windows reports internet access. ICMP and the API may be blocked by a firewall or only reachable via a proxy.. + /// + public static string ConnectionCheckReason_InternetAccessReportedByWindows { + get { + return ResourceManager.GetString("ConnectionCheckReason_InternetAccessReportedByWindows", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The internet is not reachable (no reply to the ping of the public IP address and no answer from the public IP address API).. + /// + public static string ConnectionCheckReason_InternetNotReachable { + get { + return ResourceManager.GetString("ConnectionCheckReason_InternetNotReachable", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Link-local address (169.254.x.x): the network adapter did not get an IPv4 address from a DHCP server.. + /// + public static string ConnectionCheckReason_IPv4LinkLocal { + get { + return ResourceManager.GetString("ConnectionCheckReason_IPv4LinkLocal", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No IPv6 connection. The network or the internet provider may not support IPv6.. + /// + public static string ConnectionCheckReason_IPv6NotAvailable { + get { + return ResourceManager.GetString("ConnectionCheckReason_IPv6NotAvailable", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The name of the public IP address API could not be resolved. Check the DNS server.. + /// + public static string ConnectionCheckReason_NameResolutionFailed { + get { + return ResourceManager.GetString("ConnectionCheckReason_NameResolutionFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No default gateway found on the network adapter (e.g. a VPN connection without a gateway).. + /// + public static string ConnectionCheckReason_NoGateway { + get { + return ResourceManager.GetString("ConnectionCheckReason_NoGateway", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No IP address to resolve.. + /// + public static string ConnectionCheckReason_NoIPAddressToResolve { + get { + return ResourceManager.GetString("ConnectionCheckReason_NoIPAddressToResolve", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No IPv4 address.. + /// + public static string ConnectionCheckReason_NoIPv4Address { + get { + return ResourceManager.GetString("ConnectionCheckReason_NoIPv4Address", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No route to the internet (no default gateway). The address of the first active network adapter is shown.. + /// + public static string ConnectionCheckReason_NoRoute { + get { + return ResourceManager.GetString("ConnectionCheckReason_NoRoute", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No DNS record (PTR) found for the IP address. Many networks don't have one, this is not an error.. + /// + public static string ConnectionCheckReason_PTRNotFound { + get { + return ResourceManager.GetString("ConnectionCheckReason_PTRNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The public IP address is not requested (disabled in the settings).. + /// + public static string ConnectionCheckReason_PublicIPAddressCheckDisabled { + get { + return ResourceManager.GetString("ConnectionCheckReason_PublicIPAddressCheckDisabled", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The API returned a private IP address instead of the public one (e.g. the page of a hotspot / captive portal or a proxy).. + /// + public static string ConnectionCheckReason_PublicIPAddressPrivate { + get { + return ResourceManager.GetString("ConnectionCheckReason_PublicIPAddressPrivate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The public IP address could not be requested from the API (no answer, an error or no IP address in the answer).. + /// + public static string ConnectionCheckReason_PublicIPAddressRequestFailed { + get { + return ResourceManager.GetString("ConnectionCheckReason_PublicIPAddressRequestFailed", resourceCulture); + } + } + /// /// Looks up a localized string similar to Connections. /// @@ -2710,6 +2863,15 @@ public static string Copy { } } + /// + /// Looks up a localized string similar to Copy all. + /// + public static string CopyAll { + get { + return ResourceManager.GetString("CopyAll", resourceCulture); + } + } + /// /// Looks up a localized string similar to Copy as.... /// @@ -6192,7 +6354,9 @@ public static string HelpMessage_CheckIPGeolocation { /// /// Looks up a localized string similar to The public IP address is determined via ipify.org. /// - ///URL: https://api.ipify.org and https://api6.ipify.org. + ///URL: https://api.ipify.org and https://api6.ipify.org + /// + ///If disabled, the internet connection is only checked with a ping of the public IP address and the internet connectivity reported by Windows.. /// public static string HelpMessage_CheckPublicIPAddress { get { @@ -6228,7 +6392,7 @@ public static string HelpMessage_CustomCommandFilePath { } /// - /// Looks up a localized string similar to URL to a web service that can be reached via http or https and returns an IPv4 address e.g., "xx.xx.xx.xx" as response.. + /// Looks up a localized string similar to URL to a web service that can be reached via http or https and returns an IPv4 address e.g., "xx.xx.xx.xx" as response (plain text, or a JSON object with the address as a string value).. /// public static string HelpMessage_CustomPublicIPv4AddressAPI { get { @@ -6237,7 +6401,7 @@ public static string HelpMessage_CustomPublicIPv4AddressAPI { } /// - /// Looks up a localized string similar to URL to a web service that can be reached via http or https and returns an IPv6 address e.g., "xxxx:xx:xxx::xx" as response.. + /// Looks up a localized string similar to URL to a web service that can be reached via http or https and returns an IPv6 address e.g., "xxxx:xx:xxx::xx" as response (plain text, or a JSON object with the address as a string value).. /// public static string HelpMessage_CustomPublicIPv6AddressAPI { get { @@ -6390,7 +6554,7 @@ public static string HelpMessage_ProfileHostPlaceholder { } /// - /// Looks up a localized string similar to Public IPv4 address reachable via ICMP.. + /// Looks up a localized string similar to Public IPv4 address that is pinged to check the internet connection. The route to it is used to detect the local IPv4 address (of the network adapter that is used for the internet).. /// public static string HelpMessage_PublicIPv4Address { get { @@ -6399,7 +6563,7 @@ public static string HelpMessage_PublicIPv4Address { } /// - /// Looks up a localized string similar to Public IPv6 address reachable via ICMP.. + /// Looks up a localized string similar to Public IPv6 address that is pinged to check the internet connection. The route to it is used to detect the local IPv6 address (of the network adapter that is used for the internet).. /// public static string HelpMessage_PublicIPv6Address { get { @@ -16133,6 +16297,15 @@ public static string WideSubnet { } } + /// + /// Looks up a localized string similar to Widgets. + /// + public static string Widgets { + get { + return ResourceManager.GetString("Widgets", resourceCulture); + } + } + /// /// Looks up a localized string similar to Width. /// diff --git a/Source/NETworkManager.Localization/Resources/Strings.resx b/Source/NETworkManager.Localization/Resources/Strings.resx index 1dbc1ebe6c..632c9159d6 100644 --- a/Source/NETworkManager.Localization/Resources/Strings.resx +++ b/Source/NETworkManager.Localization/Resources/Strings.resx @@ -2092,7 +2092,9 @@ URL: https://api.github.com/ The public IP address is determined via ipify.org. -URL: https://api.ipify.org and https://api6.ipify.org +URL: https://api.ipify.org and https://api6.ipify.org + +If disabled, the internet connection is only checked with a ping of the public IP address and the internet connectivity reported by Windows. Privacy @@ -2183,7 +2185,7 @@ is disabled! Use custom IPv4 address API - URL to a web service that can be reached via http or https and returns an IPv4 address e.g., "xx.xx.xx.xx" as response. + URL to a web service that can be reached via http or https and returns an IPv4 address e.g., "xx.xx.xx.xx" as response (plain text, or a JSON object with the address as a string value). Could not parse public ip address from "{0}"! Try another service or use the default... @@ -3091,10 +3093,10 @@ Enable profile file encryption in Settings>Profile to store credentials secur Enter a valid IPv6 address! - Public IPv4 address reachable via ICMP. + Public IPv4 address that is pinged to check the internet connection. The route to it is used to detect the local IPv4 address (of the network adapter that is used for the internet). - Public IPv6 address reachable via ICMP. + Public IPv6 address that is pinged to check the internet connection. The route to it is used to detect the local IPv6 address (of the network adapter that is used for the internet). Public IPv4 address @@ -3325,7 +3327,7 @@ If the option is disabled again, the values are no longer modified. However, the SNTP server(s) - URL to a web service that can be reached via http or https and returns an IPv6 address e.g., "xxxx:xx:xxx::xx" as response. + URL to a web service that can be reached via http or https and returns an IPv6 address e.g., "xxxx:xx:xxx::xx" as response (plain text, or a JSON object with the address as a string value). IP endpoint @@ -5699,4 +5701,61 @@ Do you want to start the scan? Searching for network adapters... + + No IPv4 address. + + + Link-local address (169.254.x.x): the network adapter did not get an IPv4 address from a DHCP server. + + + No route to the internet (no default gateway). The address of the first active network adapter is shown. + + + No IPv6 connection. The network or the internet provider may not support IPv6. + + + No IP address to resolve. + + + No DNS record (PTR) found for the IP address. Many networks don't have one, this is not an error. + + + The DNS server did not answer or returned an error. + + + No default gateway found on the network adapter (e.g. a VPN connection without a gateway). + + + The gateway did not reply to the ping. It may be offline or block ICMP. + + + The API returned a private IP address instead of the public one (e.g. the page of a hotspot / captive portal or a proxy). + + + The public IP address could not be requested from the API (no answer, an error or no IP address in the answer). + + + The name of the public IP address API could not be resolved. Check the DNS server. + + + Windows reports limited internet access (e.g. a hotspot / captive portal that requires a sign-in). + + + No reply to the ping and no public IP address from the API, but Windows reports internet access. ICMP and the API may be blocked by a firewall or only reachable via a proxy. + + + The internet is not reachable (no reply to the ping of the public IP address and no answer from the public IP address API). + + + The public IP address is not requested (disabled in the settings). + + + Copy all + + + Widgets + + + All widgets are hidden. You can show them in the settings of the dashboard. + \ No newline at end of file diff --git a/Source/NETworkManager.Models/Network/ConnectionCheckReason.cs b/Source/NETworkManager.Models/Network/ConnectionCheckReason.cs new file mode 100644 index 0000000000..9b34c2f460 --- /dev/null +++ b/Source/NETworkManager.Models/Network/ConnectionCheckReason.cs @@ -0,0 +1,95 @@ +namespace NETworkManager.Models.Network; + +/// +/// Reason of the state of a network connection check (e.g. Computer > IPv4), shown as tooltip of the state icon. +/// Localized via ResourceIdentifier.ConnectionCheckReason. +/// +public enum ConnectionCheckReason +{ + /// + /// No reason (e.g. the check was successful). + /// + None, + + /// + /// The computer has no IPv4 address. + /// + NoIPv4Address, + + /// + /// The computer has only a link-local IPv4 address (169.254.x.x): no address from a DHCP server. + /// + IPv4LinkLocal, + + /// + /// There is no route to the public IP address (no default gateway); the address of the first active network + /// adapter is shown. + /// + NoRoute, + + /// + /// The computer has no routed IPv6 address (only link-local or none), e.g. the network doesn't support IPv6. + /// + IPv6NotAvailable, + + /// + /// There is no IP address to resolve the DNS name (PTR) for. + /// + NoIPAddressToResolve, + + /// + /// The DNS server answered, but there is no DNS record (PTR) for the IP address (common for private addresses). + /// + PTRNotFound, + + /// + /// The DNS server did not answer or returned an error. + /// + DNSError, + + /// + /// No default gateway was found on the network adapter of the local IP address (e.g. a VPN connection). + /// + NoGateway, + + /// + /// The gateway did not reply to the ping (it may be offline or block ICMP). + /// + GatewayNoReply, + + /// + /// The API returned a private IP address (e.g. the page of a captive portal or a proxy). + /// + PublicIPAddressPrivate, + + /// + /// The public IP address could not be requested from the API (no answer, an error or no IP address). + /// + PublicIPAddressRequestFailed, + + /// + /// The host name of the public IP address API could not be resolved (DNS). + /// + NameResolutionFailed, + + /// + /// Windows reports limited internet access (e.g. a hotspot / captive portal that requires a sign-in). + /// + CaptivePortal, + + /// + /// The ping and the public IP address API failed, but Windows reports internet access (e.g. ICMP and the API are + /// blocked by a firewall or only reachable via a proxy). + /// + InternetAccessReportedByWindows, + + /// + /// The internet is not reachable (no reply to the ping, no answer from the API). + /// + InternetNotReachable, + + /// + /// The public IP address is not requested (disabled in the settings). + /// + PublicIPAddressCheckDisabled +} diff --git a/Source/NETworkManager.Models/Network/InternetConnectivity.cs b/Source/NETworkManager.Models/Network/InternetConnectivity.cs new file mode 100644 index 0000000000..a7872a15b3 --- /dev/null +++ b/Source/NETworkManager.Models/Network/InternetConnectivity.cs @@ -0,0 +1,74 @@ +using System; +using log4net; +using Windows.Networking.Connectivity; + +namespace NETworkManager.Models.Network; + +/// +/// Internet connectivity as reported by Windows (Network Connectivity Status Indicator, NCSI). Windows checks it +/// itself with its own test server, so no request is sent by the application. +/// +public enum InternetConnectivityLevel +{ + /// + /// Unknown (e.g. the status could not be read). + /// + Unknown, + + /// + /// No connection. + /// + None, + + /// + /// Local network access only. + /// + LocalAccess, + + /// + /// Limited internet access, e.g. a hotspot / captive portal that requires a sign-in. + /// + ConstrainedInternetAccess, + + /// + /// Internet access. + /// + InternetAccess +} + +/// +/// Reads the internet connectivity reported by Windows. +/// +public static class InternetConnectivity +{ + private static readonly ILog Log = LogManager.GetLogger(typeof(InternetConnectivity)); + + /// + /// Gets the internet connectivity of the connection profile that Windows uses for the internet. + /// + /// Connectivity level, on error. + public static InternetConnectivityLevel GetLevel() + { + try + { + var profile = NetworkInformation.GetInternetConnectionProfile(); + + if (profile == null) + return InternetConnectivityLevel.None; + + return profile.GetNetworkConnectivityLevel() switch + { + NetworkConnectivityLevel.None => InternetConnectivityLevel.None, + NetworkConnectivityLevel.LocalAccess => InternetConnectivityLevel.LocalAccess, + NetworkConnectivityLevel.ConstrainedInternetAccess => InternetConnectivityLevel.ConstrainedInternetAccess, + NetworkConnectivityLevel.InternetAccess => InternetConnectivityLevel.InternetAccess, + _ => InternetConnectivityLevel.Unknown + }; + } + catch (Exception ex) + { + Log.Warn("Could not get the internet connectivity reported by Windows.", ex); + return InternetConnectivityLevel.Unknown; + } + } +} diff --git a/Source/NETworkManager.Models/Network/NetworkConnectionCheck.cs b/Source/NETworkManager.Models/Network/NetworkConnectionCheck.cs new file mode 100644 index 0000000000..3a0964e655 --- /dev/null +++ b/Source/NETworkManager.Models/Network/NetworkConnectionCheck.cs @@ -0,0 +1,169 @@ +using System.Net; +using System.Net.Sockets; +using NETworkManager.Utilities; + +namespace NETworkManager.Models.Network; + +/// +/// Result of a network connection check (e.g. Computer > IPv4): the state and its reason. +/// +/// State of the check. +/// Reason of the state (shown as tooltip), if OK. +public sealed record ConnectionCheckResult(ConnectionState State, ConnectionCheckReason Reason = ConnectionCheckReason.None); + +/// +/// Decisions of the network connection check (dashboard widget and status window): which state a detected value +/// gets. The detection itself is done by the view model. +/// +public static class NetworkConnectionCheck +{ + /// + /// State of the local IP address of the computer. + /// + /// + /// IPv4: missing → critical; link-local (no DHCP server) or not routed (taken from the first active network + /// adapter) → warning. IPv6: missing, link-local only or not routed → info (the network or the internet provider + /// may not support IPv6, which is not an error). + /// + /// Local IP address, or null if none was detected. + /// IPv4 or IPv6. + /// The address was detected via the route to the public IP address (not the fallback). + /// State and reason. + public static ConnectionCheckResult GetLocalIPAddressResult(IPAddress ipAddress, AddressFamily addressFamily, + bool isRouted) + { + if (addressFamily == AddressFamily.InterNetworkV6) + return ipAddress == null || !isRouted || NetworkInterface.IsLinkLocal(ipAddress) + ? new ConnectionCheckResult(ConnectionState.Info, ConnectionCheckReason.IPv6NotAvailable) + : new ConnectionCheckResult(ConnectionState.OK); + + if (ipAddress == null) + return new ConnectionCheckResult(ConnectionState.Critical, ConnectionCheckReason.NoIPv4Address); + + if (NetworkInterface.IsLinkLocal(ipAddress)) + return new ConnectionCheckResult(ConnectionState.Warning, ConnectionCheckReason.IPv4LinkLocal); + + return isRouted + ? new ConnectionCheckResult(ConnectionState.OK) + : new ConnectionCheckResult(ConnectionState.Warning, ConnectionCheckReason.NoRoute); + } + + /// + /// Decides whether the DNS name (PTR) is also resolved for the IPv6 address: if the IPv4 address was not resolved + /// or has no record. Not after a DNS server error, the same server would fail again (and the timeout doubles). + /// + /// Result of the IPv4 lookup, or null if there was no IPv4 address. + /// if the IPv6 address should be resolved. + public static bool ShouldResolveIPv6(DNSClientResultString ipv4Result) + { + return ipv4Result is null or { HasError: true, IsNotFound: true }; + } + + /// + /// State of the DNS name (PTR) of the IPv4 / IPv6 address: a resolved name of either address is OK. Otherwise a + /// clean "not found" of either address is info (many networks have no reverse DNS), not a broken DNS setup. + /// + /// Result of the IPv4 lookup, or null if not resolved. + /// Result of the IPv6 lookup, or null if not resolved. + /// State and reason, and the resolved name (null if none). + public static (ConnectionCheckResult Result, string Hostname) GetDNSResult(DNSClientResultString ipv4Result, + DNSClientResultString ipv6Result) + { + if (ipv4Result == null && ipv6Result == null) + return (new ConnectionCheckResult(ConnectionState.Info, ConnectionCheckReason.NoIPAddressToResolve), null); + + var resolved = ipv4Result is { HasError: false } ? ipv4Result : + ipv6Result is { HasError: false } ? ipv6Result : null; + + if (resolved != null) + return (new ConnectionCheckResult(ConnectionState.OK), resolved.Value); + + return ipv4Result is { IsNotFound: true } || ipv6Result is { IsNotFound: true } + ? (new ConnectionCheckResult(ConnectionState.Info, ConnectionCheckReason.PTRNotFound), null) + : (new ConnectionCheckResult(ConnectionState.Critical, ConnectionCheckReason.DNSError), null); + } + + /// + /// State of the gateway (router): found and replies to the ping → OK; no reply → warning (some routers block + /// ICMP). Not found → warning if the local IP address is routed anyway (e.g. a VPN adapter without a gateway), + /// otherwise critical. + /// + /// Gateway, or null if none was found. + /// The local IP address was detected via the route to the public IP address. + /// The gateway replied to the ping. + /// State and reason. + public static ConnectionCheckResult GetGatewayResult(IPAddress gateway, bool isRouted, bool isReachable) + { + if (gateway == null) + return new ConnectionCheckResult(isRouted ? ConnectionState.Warning : ConnectionState.Critical, + ConnectionCheckReason.NoGateway); + + return isReachable + ? new ConnectionCheckResult(ConnectionState.OK) + : new ConnectionCheckResult(ConnectionState.Warning, ConnectionCheckReason.GatewayNoReply); + } + + /// + /// State of the public IP address requested from the API: a public IP address is OK, a private one a warning + /// (e.g. captive portal or proxy), everything else critical. + /// + /// Result of the request. + /// State and reason. + public static ConnectionCheckResult GetPublicIPAddressResult(PublicIPAddressCheckResult result) + { + return result.Status switch + { + PublicIPAddressCheckStatus.Success => new ConnectionCheckResult(ConnectionState.OK), + PublicIPAddressCheckStatus.PrivateIPAddress => new ConnectionCheckResult(ConnectionState.Warning, + ConnectionCheckReason.PublicIPAddressPrivate), + PublicIPAddressCheckStatus.NameResolutionFailed => new ConnectionCheckResult(ConnectionState.Critical, + ConnectionCheckReason.NameResolutionFailed), + _ => new ConnectionCheckResult(ConnectionState.Critical, ConnectionCheckReason.PublicIPAddressRequestFailed) + }; + } + + /// + /// State of the internet connection (IPv4 or IPv6) from three sources: the ping of the public IP address + /// (setting), the public IP address API (if enabled) and the connectivity reported by Windows. + /// + /// + /// A public IP address from the API is OK (the HTTPS request reached the internet), even if Windows reports a + /// captive portal (e.g. a proxy or web filter intercepts the probe of Windows). Otherwise a captive portal + /// (Windows, only used for IPv4) is a warning, also if the ping works (a captive portal may let ICMP through); a reply to the ping is OK; a private IP address from the API is a warning, as is a + /// failed API when the ping works (e.g. the API is blocked). If both fail but Windows reports internet access (only used for IPv4, Windows doesn't report it per + /// address family), ICMP and the API may be blocked: warning. Otherwise critical. + /// + /// IPv4 or IPv6. + /// The public IP address (setting) replied to the ping. + /// Result of the API, or null if disabled. + /// Internet connectivity reported by Windows. + /// State and reason. + public static ConnectionCheckResult GetInternetResult(AddressFamily addressFamily, bool isPingSuccessful, + PublicIPAddressCheckResult publicIPAddress, InternetConnectivityLevel connectivityLevel) + { + if (publicIPAddress is { Status: PublicIPAddressCheckStatus.Success }) + return new ConnectionCheckResult(ConnectionState.OK); + + // Windows doesn't report the connectivity per address family (a captive portal is IPv4 in practice) + if (addressFamily == AddressFamily.InterNetwork && + connectivityLevel == InternetConnectivityLevel.ConstrainedInternetAccess) + return new ConnectionCheckResult(ConnectionState.Warning, ConnectionCheckReason.CaptivePortal); + + if (publicIPAddress is { Status: PublicIPAddressCheckStatus.PrivateIPAddress }) + return GetPublicIPAddressResult(publicIPAddress); + + if (isPingSuccessful) + return publicIPAddress == null + ? new ConnectionCheckResult(ConnectionState.OK) + : new ConnectionCheckResult(ConnectionState.Warning, GetPublicIPAddressResult(publicIPAddress).Reason); + + if (addressFamily == AddressFamily.InterNetwork && + connectivityLevel == InternetConnectivityLevel.InternetAccess) + return new ConnectionCheckResult(ConnectionState.Warning, + ConnectionCheckReason.InternetAccessReportedByWindows); + + return publicIPAddress is { Status: PublicIPAddressCheckStatus.NameResolutionFailed } + ? new ConnectionCheckResult(ConnectionState.Critical, ConnectionCheckReason.NameResolutionFailed) + : new ConnectionCheckResult(ConnectionState.Critical, ConnectionCheckReason.InternetNotReachable); + } +} diff --git a/Source/NETworkManager.Models/Network/NetworkInterface.cs b/Source/NETworkManager.Models/Network/NetworkInterface.cs index 2aced18d56..ed8c09d3b7 100644 --- a/Source/NETworkManager.Models/Network/NetworkInterface.cs +++ b/Source/NETworkManager.Models/Network/NetworkInterface.cs @@ -109,19 +109,7 @@ public static List GetNetworkInterfaces() foreach (var networkInterface in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()) { - // NetworkInterfaceType 53 is proprietary virtual/internal interface - // https://docs.microsoft.com/en-us/windows-hardware/drivers/network/ndis-interface-types - if (networkInterface.NetworkInterfaceType != NetworkInterfaceType.Ethernet && - networkInterface.NetworkInterfaceType != NetworkInterfaceType.Wireless80211 && - (int)networkInterface.NetworkInterfaceType != 53) - continue; - - // Filter out virtual/filter adapters introduced in .NET 9/10 - // Check if the adapter name or description contains any filtered pattern - // See: https://github.com/dotnet/runtime/issues/122751 - if (NetworkInterfaceFilteredPatterns.Any(pattern => - networkInterface.Name.Contains(pattern) || - networkInterface.Description.Contains(pattern))) + if (!IsSupportedNetworkInterface(networkInterface)) continue; var listIPv4Address = new List>(); @@ -233,6 +221,29 @@ public static List GetNetworkInterfaces() return listNetworkInterfaceInfo; } + /// + /// Network interfaces shown and used by the application: Ethernet, Wireless80211 and proprietary virtual/internal + /// interfaces, without the virtual/filter adapters listed in . + /// + /// Network interface of the .NET API. + /// if the network interface is supported. + private static bool IsSupportedNetworkInterface(System.Net.NetworkInformation.NetworkInterface networkInterface) + { + // NetworkInterfaceType 53 is proprietary virtual/internal interface + // https://docs.microsoft.com/en-us/windows-hardware/drivers/network/ndis-interface-types + if (networkInterface.NetworkInterfaceType != NetworkInterfaceType.Ethernet && + networkInterface.NetworkInterfaceType != NetworkInterfaceType.Wireless80211 && + (int)networkInterface.NetworkInterfaceType != 53) + return false; + + // Filter out virtual/filter adapters introduced in .NET 9/10 + // Check if the adapter name or description contains any filtered pattern + // See: https://github.com/dotnet/runtime/issues/122751 + return !NetworkInterfaceFilteredPatterns.Any(pattern => + networkInterface.Name.Contains(pattern) || + networkInterface.Description.Contains(pattern)); + } + /// /// Finds a network interface by its ID (GUID, unique per computer; the name is not). /// @@ -363,69 +374,55 @@ public static Task DetectLocalIPAddressFromNetworkInterfaceAsync(Addr /// /// Detects and returns the first local IP address assigned to an operational network interface that matches the - /// specified address family. + /// specified address family, see . /// - /// For IPv4, the method prefers non-link-local addresses but will return a link-local address if - /// no other is available. For IPv6, the method returns the first global or unique local address if present; - /// otherwise, it returns a link-local address if available. The returned address is selected from operational - /// network interfaces only. + /// Only reads the addresses (no PowerShell / registry like ), the + /// network interfaces are filtered the same way. /// The address family to search for. Specify for IPv4 addresses or for IPv6 addresses. /// An representing the first detected local IP address for the specified address family, or /// if no suitable address is found. public static IPAddress DetectLocalIPAddressFromNetworkInterface(AddressFamily addressFamily) { - // Filter operational network interfaces - var networkInterfaces = GetNetworkInterfaces() - .Where(x => x.IsOperational) - .ToList(); - - var candidates = new List(); + var addresses = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces() + .Where(x => x.OperationalStatus == OperationalStatus.Up && IsSupportedNetworkInterface(x)) + .Select(x => x.GetIPProperties().UnicastAddresses.Select(y => y.Address).ToArray()); - switch (addressFamily) - { - // IPv4 - case AddressFamily.InterNetwork: - { - foreach (var networkInterface in networkInterfaces) - { - foreach (var ipAddress in networkInterface.IPv4Address) - candidates.Add(ipAddress.Item1); - } - - // Prefer non-link-local addresses - var nonLinkLocal = candidates.FirstOrDefault(x => - { - var bytes = x.GetAddressBytes(); - - return !(bytes[0] == 169 && bytes[1] == 254); - }); + return SelectLocalIPAddress(addresses, addressFamily); + } - // Return first non-link-local or first candidate if none found (might be null - no addresses at all) - return nonLinkLocal ?? candidates.FirstOrDefault(); - } - // IPv6 - case AddressFamily.InterNetworkV6: - { - // First try to get global or unique local addresses - foreach (var networkInterface in networkInterfaces) - candidates.AddRange(networkInterface.IPv6Address); + /// + /// Selects the local IP address of the address family from the addresses of the network interfaces (in their + /// order). For IPv4, the first address that is not link-local (169.254.x.x, no DHCP server) is preferred; for IPv6, + /// the first global or unique local address. Otherwise, the first link-local address is returned. + /// + /// Unicast addresses of each network interface. + /// The address family to search for. + /// The selected IP address, or if there is no address of the family. + public static IPAddress SelectLocalIPAddress(IEnumerable addressesPerNetworkInterface, + AddressFamily addressFamily) + { + var candidates = addressesPerNetworkInterface + .SelectMany(x => x) + .Where(x => x.AddressFamily == addressFamily) + .ToList(); - // Return first candidate if any found - if (candidates.Count != 0) - return candidates.First(); + return candidates.FirstOrDefault(x => !IsLinkLocal(x)) ?? candidates.FirstOrDefault(); + } - // Fallback to link-local addresses - var firstWithLinkLocal = networkInterfaces - .FirstOrDefault(ni => ni.IPv6AddressLinkLocal.Length != 0); + /// + /// Checks if the IP address is a link-local address (IPv4 169.254.0.0/16, IPv6 fe80::/10). + /// + /// IP address. + /// if the IP address is link-local. + public static bool IsLinkLocal(IPAddress ipAddress) + { + if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6) + return ipAddress.IsIPv6LinkLocal; - if (firstWithLinkLocal != null) - return firstWithLinkLocal.IPv6AddressLinkLocal.First(); - break; - } - } + var bytes = ipAddress.GetAddressBytes(); - return null; + return bytes[0] == 169 && bytes[1] == 254; } /// @@ -442,26 +439,41 @@ public static Task DetectGatewayFromLocalIPAddressAsync(IPAddress loc /// /// Attempts to determine the default gateway address associated with the specified local IP address. /// - /// This method searches all available network interfaces to find one that has the specified - /// local IP address assigned. If found, it returns the first associated gateway address for that interface and - /// address family. Returns null if the local IP address is not assigned to any interface or if no gateway is - /// configured. + /// All network interfaces are searched (also VPN adapters, e.g. PPP or tunnel, which are not shown in the + /// application) and only their addresses are read (no PowerShell / registry like ). + /// See . /// The local IP address for which to detect the corresponding gateway. Must be either an IPv4 or IPv6 address. /// An IPAddress representing the default gateway for the specified local IP address, or null if no matching gateway /// is found. private static IPAddress DetectGatewayFromLocalIPAddress(IPAddress localIPAddress) { - foreach (var networkInterface in GetNetworkInterfaces()) + var networkInterfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces() + .Select(x => x.GetIPProperties()) + .Select(x => (x.UnicastAddresses.Select(y => y.Address).ToArray(), + x.GatewayAddresses.Select(y => y.Address).ToArray())); + + return SelectGateway(networkInterfaces, localIPAddress); + } + + /// + /// Selects the gateway of the first network interface that has the local IP address assigned. The scope id of IPv6 + /// addresses is ignored. Unspecified gateways (0.0.0.0 / ::, e.g. some VPN adapters) are skipped. + /// + /// Unicast and gateway addresses of each network interface. + /// The local IP address (IPv4 or IPv6). + /// The first gateway of the same address family, or if there is none. + public static IPAddress SelectGateway(IEnumerable<(IPAddress[] Addresses, IPAddress[] Gateways)> networkInterfaces, + IPAddress localIPAddress) + { + var local = IPAddressHelper.WithoutScopeId(localIPAddress); + + foreach (var (addresses, gateways) in networkInterfaces) { - switch (localIPAddress.AddressFamily) - { - // IPv4 - case AddressFamily.InterNetwork when networkInterface.IPv4Address.Any(x => x.Item1.Equals(localIPAddress)): - return networkInterface.IPv4Gateway.FirstOrDefault(); - // IPv6 - case AddressFamily.InterNetworkV6 when networkInterface.IPv6Address.Contains(localIPAddress): - return networkInterface.IPv6Gateway.FirstOrDefault(); - } + if (!addresses.Any(x => IPAddressHelper.WithoutScopeId(x).Equals(local))) + continue; + + return gateways.FirstOrDefault(x => x.AddressFamily == localIPAddress.AddressFamily && + !x.Equals(IPAddress.Any) && !x.Equals(IPAddress.IPv6Any)); } return null; diff --git a/Source/NETworkManager.Models/Network/PingProbe.cs b/Source/NETworkManager.Models/Network/PingProbe.cs index cc109803bf..f9a6c17441 100644 --- a/Source/NETworkManager.Models/Network/PingProbe.cs +++ b/Source/NETworkManager.Models/Network/PingProbe.cs @@ -7,9 +7,10 @@ namespace NETworkManager.Models.Network; /// -/// Provides a shared ICMP echo (ping) probe used by and . +/// Provides a shared ICMP echo (ping) probe used by , and the +/// network connection check (dashboard). /// -internal static class PingProbe +public static class PingProbe { /// /// Pings the host. Another echo request is only sent if the previous one timed out (e.g. a lost packet), diff --git a/Source/NETworkManager.Models/Network/PublicIPAddressCheck.cs b/Source/NETworkManager.Models/Network/PublicIPAddressCheck.cs new file mode 100644 index 0000000000..c6f220a357 --- /dev/null +++ b/Source/NETworkManager.Models/Network/PublicIPAddressCheck.cs @@ -0,0 +1,188 @@ +using System; +using System.Net; +using System.Net.Http; +using System.Net.Sockets; +using System.Text.RegularExpressions; +using NETworkManager.Utilities; + +namespace NETworkManager.Models.Network; + +/// +/// Status of the request of the public IP address from an API (e.g. api.ipify.org). +/// +public enum PublicIPAddressCheckStatus +{ + /// + /// The API returned a public IP address. + /// + Success, + + /// + /// The API returned a private, link-local or loopback IP address (e.g. the page of a captive portal or a proxy). + /// + PrivateIPAddress, + + /// + /// The API answered, but not with a success status code or without an IP address of the address family. + /// + InvalidResponse, + + /// + /// The host name of the API could not be resolved (DNS). + /// + NameResolutionFailed, + + /// + /// The request failed (e.g. no connection, timeout). + /// + RequestFailed +} + +/// +/// Result of the request of the public IP address. +/// +/// Status of the request. +/// IP address returned by the API (also if private), otherwise null. +public sealed record PublicIPAddressCheckResult(PublicIPAddressCheckStatus Status, IPAddress IPAddress = null); + +/// +/// Evaluates the answer of a public IP address API. +/// +public static partial class PublicIPAddressCheck +{ + /// + /// Parses the answer of the API: the IP address as plain text, or (custom APIs) the first string value of a JSON + /// object that is an IP address of the address family (e.g. {"ip":"203.0.113.10"}). Other text (e.g. the + /// HTML page of a captive portal with a link to an IP address) is no valid answer. + /// + /// The HTTP status code is 2xx. + /// Content of the answer. + /// IPv4 or IPv6. + /// Result of the request. + public static PublicIPAddressCheckResult ParseResponse(bool isSuccessStatusCode, string content, + AddressFamily addressFamily) + { + if (!isSuccessStatusCode) + return new PublicIPAddressCheckResult(PublicIPAddressCheckStatus.InvalidResponse); + + var text = content?.Trim() ?? string.Empty; + + if (!TryParseIPAddress(text, addressFamily, out var ipAddress) && + !TryParseJsonStringValue(text, addressFamily, out ipAddress)) + return new PublicIPAddressCheckResult(PublicIPAddressCheckStatus.InvalidResponse); + + return GetStatus(ipAddress) switch + { + PublicIPAddressCheckStatus.InvalidResponse => new PublicIPAddressCheckResult( + PublicIPAddressCheckStatus.InvalidResponse), + var status => new PublicIPAddressCheckResult(status, ipAddress) + }; + } + + /// + /// Gets the first string value of a JSON object ("...") that is an IP address of the address family. + /// + /// Answer of the API. + /// IPv4 or IPv6. + /// Parsed IP address. + /// if an IP address was found. + private static bool TryParseJsonStringValue(string text, AddressFamily addressFamily, out IPAddress ipAddress) + { + ipAddress = null; + + if (!text.StartsWith('{')) + return false; + + foreach (Match match in JsonStringRegex().Matches(text)) + { + if (TryParseIPAddress(match.Groups[1].Value, addressFamily, out ipAddress)) + return true; + } + + return false; + } + + /// + /// A short JSON string without whitespace, e.g. "203.0.113.10" (the value without the quotes in group 1). + /// + [GeneratedRegex("\"([^\"\\s]{2,45})\"")] + private static partial Regex JsonStringRegex(); + + /// + /// Parses an IP address in its normal notation only: IPv4 as four decimal numbers ( + /// also accepts e.g. "429" as 0.0.1.173 - an HTTP status code in the answer), IPv6 without a scope id. + /// + /// Text to parse. + /// IPv4 or IPv6. + /// Parsed IP address. + /// if the text is an IP address of the address family. + private static bool TryParseIPAddress(string text, AddressFamily addressFamily, out IPAddress ipAddress) + { + ipAddress = null; + + var isValidNotation = addressFamily == AddressFamily.InterNetwork + ? RegexHelper.IPv4AddressRegex().IsMatch(text) + : text.Contains(':') && !text.Contains('%'); + + return isValidNotation && IPAddress.TryParse(text, out ipAddress) && ipAddress.AddressFamily == addressFamily; + } + + /// + /// Status of an IP address returned by the API: a private, shared (carrier-grade NAT), link-local or loopback + /// address (IPv6 also site-local) is not the public IP address (e.g. the answer of a captive portal or a proxy); + /// an unspecified, multicast, reserved or IPv4-mapped IPv6 address is no valid answer. + /// + /// IP address returned by the API. + /// , + /// or . + public static PublicIPAddressCheckStatus GetStatus(IPAddress ipAddress) + { + var bytes = ipAddress.GetAddressBytes(); + + if (ipAddress.AddressFamily == AddressFamily.InterNetwork) + { + // 0.0.0.0/8 (this network), 224.0.0.0/4 (multicast), 240.0.0.0/4 (reserved, broadcast) + if (bytes[0] == 0 || bytes[0] >= 224) + return PublicIPAddressCheckStatus.InvalidResponse; + + // 100.64.0.0/10 (shared address space, carrier-grade NAT) + if (bytes[0] == 100 && bytes[1] is >= 64 and <= 127) + return PublicIPAddressCheckStatus.PrivateIPAddress; + } + else + { + // Unspecified, multicast, IPv4-mapped (e.g. ::ffff:10.1.2.3, no IPv6 address) + if (ipAddress.Equals(IPAddress.IPv6Any) || ipAddress.IsIPv6Multicast || ipAddress.IsIPv4MappedToIPv6) + return PublicIPAddressCheckStatus.InvalidResponse; + + // Site-local (fec0::/10, deprecated) + if (ipAddress.IsIPv6SiteLocal) + return PublicIPAddressCheckStatus.PrivateIPAddress; + } + + return IPAddressHelper.IsPrivateIPAddress(ipAddress) || NetworkInterface.IsLinkLocal(ipAddress) || + IPAddress.IsLoopback(ipAddress) + ? PublicIPAddressCheckStatus.PrivateIPAddress + : PublicIPAddressCheckStatus.Success; + } + + /// + /// Result of a failed request: a DNS error (the host name of the API could not be resolved) or another error. + /// + /// Exception of the request. + /// Result of the request. + public static PublicIPAddressCheckResult FromException(Exception exception) + { + var isNameResolutionError = exception is HttpRequestException + { + InnerException: SocketException + { + SocketErrorCode: SocketError.HostNotFound or SocketError.NoData or SocketError.TryAgain + } + }; + + return new PublicIPAddressCheckResult(isNameResolutionError + ? PublicIPAddressCheckStatus.NameResolutionFailed + : PublicIPAddressCheckStatus.RequestFailed); + } +} diff --git a/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs b/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs index 869ca70bd8..814d213686 100644 --- a/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs +++ b/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs @@ -139,6 +139,21 @@ public static class GlobalStaticConfiguration public static string Dashboard_PublicIPv6AddressAPI => "https://api6.ipify.org"; public static bool Dashboard_CheckIPApiIPGeolocation => false; public static bool Dashboard_CheckIPApiDNSResolver => false; + public static bool Dashboard_ShowNetworkConnectionWidget => true; + public static bool Dashboard_ShowSpeedTestWidget => true; + public static bool Dashboard_ShowIPGeolocationWidget => true; + public static bool Dashboard_ShowDNSResolverWidget => true; + + /// + /// Minimum time between two network connection checks when switching back to the dashboard (the public IP address + /// may have changed, but no requests on every switch). A refresh and a network change always check. + /// + public static TimeSpan Dashboard_RecheckInterval => TimeSpan.FromSeconds(60); + + // Ping of the gateway and the public IP address + public static int Dashboard_PingTimeout => 2000; + public static int Dashboard_PingAttempts => 2; + public static int Dashboard_PingBuffer => 32; // Application: Network Interface public static ExportFileType NetworkInterface_ExportFileType => ExportFileType.Csv; diff --git a/Source/NETworkManager.Settings/SettingsInfo.cs b/Source/NETworkManager.Settings/SettingsInfo.cs index 9e8eca8dc2..db63590ddc 100644 --- a/Source/NETworkManager.Settings/SettingsInfo.cs +++ b/Source/NETworkManager.Settings/SettingsInfo.cs @@ -1063,6 +1063,58 @@ public bool Dashboard_CheckIPApiDNSResolver } } = GlobalStaticConfiguration.Dashboard_CheckIPApiDNSResolver; + public bool Dashboard_ShowNetworkConnectionWidget + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = GlobalStaticConfiguration.Dashboard_ShowNetworkConnectionWidget; + + public bool Dashboard_ShowSpeedTestWidget + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = GlobalStaticConfiguration.Dashboard_ShowSpeedTestWidget; + + public bool Dashboard_ShowIPGeolocationWidget + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = GlobalStaticConfiguration.Dashboard_ShowIPGeolocationWidget; + + public bool Dashboard_ShowDNSResolverWidget + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = GlobalStaticConfiguration.Dashboard_ShowDNSResolverWidget; + #endregion #region Network Interface diff --git a/Source/NETworkManager.Tests/Network/NetworkConnectionCheckTests.cs b/Source/NETworkManager.Tests/Network/NetworkConnectionCheckTests.cs new file mode 100644 index 0000000000..db6905a3eb --- /dev/null +++ b/Source/NETworkManager.Tests/Network/NetworkConnectionCheckTests.cs @@ -0,0 +1,184 @@ +using System.Net; +using System.Net.Sockets; +using NETworkManager.Models.Network; +using NETworkManager.Utilities; +using Xunit; + +namespace NETworkManager.Tests.Network; + +public class NetworkConnectionCheckTests +{ + private static IPAddress Ip(string ipAddress) => ipAddress == null ? null : IPAddress.Parse(ipAddress); + + [Theory] + [InlineData("192.168.1.10", true, ConnectionState.OK, ConnectionCheckReason.None)] + [InlineData(null, false, ConnectionState.Critical, ConnectionCheckReason.NoIPv4Address)] + // DHCP failed (#3288: the address is still shown) + [InlineData("169.254.10.20", false, ConnectionState.Warning, ConnectionCheckReason.IPv4LinkLocal)] + [InlineData("169.254.10.20", true, ConnectionState.Warning, ConnectionCheckReason.IPv4LinkLocal)] + // No route: address of the first active network adapter (fallback) + [InlineData("192.168.1.10", false, ConnectionState.Warning, ConnectionCheckReason.NoRoute)] + public void GetLocalIPAddressResult_IPv4(string ipAddress, bool isRouted, ConnectionState state, + ConnectionCheckReason reason) + { + Assert.Equal(new ConnectionCheckResult(state, reason), + NetworkConnectionCheck.GetLocalIPAddressResult(Ip(ipAddress), AddressFamily.InterNetwork, isRouted)); + } + + [Theory] + [InlineData("2001:db8::10", true, ConnectionState.OK, ConnectionCheckReason.None)] + [InlineData("fd00::10", true, ConnectionState.OK, ConnectionCheckReason.None)] + // IPv4-only network: not an error + [InlineData(null, false, ConnectionState.Info, ConnectionCheckReason.IPv6NotAvailable)] + [InlineData("fe80::10", false, ConnectionState.Info, ConnectionCheckReason.IPv6NotAvailable)] + // Unique local address without a route to the internet (e.g. some routers) + [InlineData("fd00::10", false, ConnectionState.Info, ConnectionCheckReason.IPv6NotAvailable)] + public void GetLocalIPAddressResult_IPv6(string ipAddress, bool isRouted, ConnectionState state, + ConnectionCheckReason reason) + { + Assert.Equal(new ConnectionCheckResult(state, reason), + NetworkConnectionCheck.GetLocalIPAddressResult(Ip(ipAddress), AddressFamily.InterNetworkV6, isRouted)); + } + + private static DNSClientResultString Resolved(string hostname) => new(hostname, "192.168.1.1:53"); + + private static DNSClientResultString NotFound() => new(true, "Non-Existent Domain", "192.168.1.1:53") + { IsNotFound = true }; + + private static DNSClientResultString Error() => new(true, "Timeout"); + + [Fact] + public void ShouldResolveIPv6() + { + Assert.True(NetworkConnectionCheck.ShouldResolveIPv6(null)); + Assert.True(NetworkConnectionCheck.ShouldResolveIPv6(NotFound())); + Assert.False(NetworkConnectionCheck.ShouldResolveIPv6(Resolved("pc.example.com"))); + // The same DNS server would time out again + Assert.False(NetworkConnectionCheck.ShouldResolveIPv6(Error())); + } + + [Fact] + public void GetDNSResult_ResolvedIPv4() + { + var (result, hostname) = NetworkConnectionCheck.GetDNSResult(Resolved("pc.example.com"), null); + + Assert.Equal(new ConnectionCheckResult(ConnectionState.OK), result); + Assert.Equal("pc.example.com", hostname); + } + + [Fact] + public void GetDNSResult_ResolvedIPv6AfterIPv4NotFound() + { + var (result, hostname) = NetworkConnectionCheck.GetDNSResult(NotFound(), Resolved("pc6.example.com")); + + Assert.Equal(ConnectionState.OK, result.State); + Assert.Equal("pc6.example.com", hostname); + } + + [Fact] + public void GetDNSResult_NotFoundWinsOverError() + { + // e.g. IPv4 has no PTR while IPv6 times out: no record, not a broken DNS setup + var (result, hostname) = NetworkConnectionCheck.GetDNSResult(NotFound(), Error()); + + Assert.Equal(new ConnectionCheckResult(ConnectionState.Info, ConnectionCheckReason.PTRNotFound), result); + Assert.Null(hostname); + } + + [Fact] + public void GetDNSResult_Error() + { + Assert.Equal(new ConnectionCheckResult(ConnectionState.Critical, ConnectionCheckReason.DNSError), + NetworkConnectionCheck.GetDNSResult(Error(), null).Result); + } + + [Fact] + public void GetDNSResult_NothingToResolve() + { + Assert.Equal(new ConnectionCheckResult(ConnectionState.Info, ConnectionCheckReason.NoIPAddressToResolve), + NetworkConnectionCheck.GetDNSResult(null, null).Result); + } + + [Theory] + [InlineData("192.168.1.1", true, true, ConnectionState.OK, ConnectionCheckReason.None)] + // Some routers block ICMP + [InlineData("192.168.1.1", true, false, ConnectionState.Warning, ConnectionCheckReason.GatewayNoReply)] + // Routed via an adapter without a gateway (e.g. VPN) + [InlineData(null, true, false, ConnectionState.Warning, ConnectionCheckReason.NoGateway)] + // No route and no gateway + [InlineData(null, false, false, ConnectionState.Critical, ConnectionCheckReason.NoGateway)] + public void GetGatewayResult(string gateway, bool isRouted, bool isReachable, ConnectionState state, + ConnectionCheckReason reason) + { + Assert.Equal(new ConnectionCheckResult(state, reason), + NetworkConnectionCheck.GetGatewayResult(Ip(gateway), isRouted, isReachable)); + } + + [Theory] + [InlineData(PublicIPAddressCheckStatus.Success, ConnectionState.OK, ConnectionCheckReason.None)] + [InlineData(PublicIPAddressCheckStatus.PrivateIPAddress, ConnectionState.Warning, ConnectionCheckReason.PublicIPAddressPrivate)] + [InlineData(PublicIPAddressCheckStatus.InvalidResponse, ConnectionState.Critical, ConnectionCheckReason.PublicIPAddressRequestFailed)] + [InlineData(PublicIPAddressCheckStatus.RequestFailed, ConnectionState.Critical, ConnectionCheckReason.PublicIPAddressRequestFailed)] + [InlineData(PublicIPAddressCheckStatus.NameResolutionFailed, ConnectionState.Critical, ConnectionCheckReason.NameResolutionFailed)] + public void GetPublicIPAddressResult(PublicIPAddressCheckStatus status, ConnectionState state, + ConnectionCheckReason reason) + { + Assert.Equal(new ConnectionCheckResult(state, reason), + NetworkConnectionCheck.GetPublicIPAddressResult(new PublicIPAddressCheckResult(status))); + } + + private static PublicIPAddressCheckResult Api(PublicIPAddressCheckStatus? status) => + status == null ? null : new PublicIPAddressCheckResult(status.Value); + + [Theory] + // API returned the public IP address + [InlineData(true, PublicIPAddressCheckStatus.Success, InternetConnectivityLevel.InternetAccess, ConnectionState.OK, ConnectionCheckReason.None)] + [InlineData(false, PublicIPAddressCheckStatus.Success, InternetConnectivityLevel.InternetAccess, ConnectionState.OK, ConnectionCheckReason.None)] + // API disabled: ping decides + [InlineData(true, null, InternetConnectivityLevel.InternetAccess, ConnectionState.OK, ConnectionCheckReason.None)] + [InlineData(false, null, InternetConnectivityLevel.LocalAccess, ConnectionState.Critical, ConnectionCheckReason.InternetNotReachable)] + // Captive portal (Windows), unless the API returned a public IP address (e.g. a web filter intercepts the probe + // of Windows, the internet works) + [InlineData(true, PublicIPAddressCheckStatus.Success, InternetConnectivityLevel.ConstrainedInternetAccess, ConnectionState.OK, ConnectionCheckReason.None)] + [InlineData(true, null, InternetConnectivityLevel.ConstrainedInternetAccess, ConnectionState.Warning, ConnectionCheckReason.CaptivePortal)] + [InlineData(false, null, InternetConnectivityLevel.ConstrainedInternetAccess, ConnectionState.Warning, ConnectionCheckReason.CaptivePortal)] + [InlineData(false, PublicIPAddressCheckStatus.PrivateIPAddress, InternetConnectivityLevel.ConstrainedInternetAccess, ConnectionState.Warning, ConnectionCheckReason.CaptivePortal)] + // Private IP address from the API (e.g. proxy) + [InlineData(true, PublicIPAddressCheckStatus.PrivateIPAddress, InternetConnectivityLevel.InternetAccess, ConnectionState.Warning, ConnectionCheckReason.PublicIPAddressPrivate)] + // Ping works, API blocked / DNS broken + [InlineData(true, PublicIPAddressCheckStatus.RequestFailed, InternetConnectivityLevel.InternetAccess, ConnectionState.Warning, ConnectionCheckReason.PublicIPAddressRequestFailed)] + [InlineData(true, PublicIPAddressCheckStatus.NameResolutionFailed, InternetConnectivityLevel.InternetAccess, ConnectionState.Warning, ConnectionCheckReason.NameResolutionFailed)] + // Ping and API failed, but Windows reports internet access (ICMP and API blocked, e.g. proxy) + [InlineData(false, PublicIPAddressCheckStatus.RequestFailed, InternetConnectivityLevel.InternetAccess, ConnectionState.Warning, ConnectionCheckReason.InternetAccessReportedByWindows)] + [InlineData(false, null, InternetConnectivityLevel.InternetAccess, ConnectionState.Warning, ConnectionCheckReason.InternetAccessReportedByWindows)] + // Everything failed + [InlineData(false, PublicIPAddressCheckStatus.RequestFailed, InternetConnectivityLevel.LocalAccess, ConnectionState.Critical, ConnectionCheckReason.InternetNotReachable)] + [InlineData(false, PublicIPAddressCheckStatus.InvalidResponse, InternetConnectivityLevel.Unknown, ConnectionState.Critical, ConnectionCheckReason.InternetNotReachable)] + [InlineData(false, PublicIPAddressCheckStatus.NameResolutionFailed, InternetConnectivityLevel.None, ConnectionState.Critical, ConnectionCheckReason.NameResolutionFailed)] + public void GetInternetResult_IPv4(bool isPingSuccessful, PublicIPAddressCheckStatus? apiStatus, + InternetConnectivityLevel level, ConnectionState state, ConnectionCheckReason reason) + { + Assert.Equal(new ConnectionCheckResult(state, reason), + NetworkConnectionCheck.GetInternetResult(AddressFamily.InterNetwork, isPingSuccessful, Api(apiStatus), level)); + } + + [Theory] + [InlineData(true, ConnectionState.OK, ConnectionCheckReason.None)] + [InlineData(false, ConnectionState.Critical, ConnectionCheckReason.InternetNotReachable)] + public void GetInternetResult_IPv6_CaptivePortalOfWindowsIsNotUsed(bool isPingSuccessful, ConnectionState state, + ConnectionCheckReason reason) + { + Assert.Equal(new ConnectionCheckResult(state, reason), + NetworkConnectionCheck.GetInternetResult(AddressFamily.InterNetworkV6, isPingSuccessful, null, + InternetConnectivityLevel.ConstrainedInternetAccess)); + } + + [Fact] + public void GetInternetResult_IPv6_WindowsInternetAccessIsNotUsed() + { + // Windows doesn't report the connectivity per address family (internet access may be IPv4 only) + Assert.Equal(new ConnectionCheckResult(ConnectionState.Critical, ConnectionCheckReason.InternetNotReachable), + NetworkConnectionCheck.GetInternetResult(AddressFamily.InterNetworkV6, false, + Api(PublicIPAddressCheckStatus.RequestFailed), InternetConnectivityLevel.InternetAccess)); + } +} diff --git a/Source/NETworkManager.Tests/Network/NetworkInterfaceDetectionTests.cs b/Source/NETworkManager.Tests/Network/NetworkInterfaceDetectionTests.cs new file mode 100644 index 0000000000..42ba33f902 --- /dev/null +++ b/Source/NETworkManager.Tests/Network/NetworkInterfaceDetectionTests.cs @@ -0,0 +1,119 @@ +using System.Net; +using System.Net.Sockets; +using NETworkManager.Models.Network; +using Xunit; + +namespace NETworkManager.Tests.Network; + +public class NetworkInterfaceDetectionTests +{ + private static IPAddress[] Addresses(params string[] addresses) => + [.. System.Linq.Enumerable.Select(addresses, IPAddress.Parse)]; + + [Fact] + public void SelectLocalIPAddress_IPv4_PrefersNonLinkLocal() + { + // e.g. a disconnected adapter without DHCP (169.254.x.x) before the connected one + var result = NetworkInterface.SelectLocalIPAddress( + [Addresses("169.254.10.20", "fe80::1"), Addresses("192.168.1.10")], AddressFamily.InterNetwork); + + Assert.Equal(IPAddress.Parse("192.168.1.10"), result); + } + + [Fact] + public void SelectLocalIPAddress_IPv4_OnlyLinkLocal() + { + var result = NetworkInterface.SelectLocalIPAddress([Addresses("169.254.10.20")], AddressFamily.InterNetwork); + + Assert.Equal(IPAddress.Parse("169.254.10.20"), result); + } + + [Fact] + public void SelectLocalIPAddress_IPv6_PrefersGlobalOrUniqueLocal() + { + var result = NetworkInterface.SelectLocalIPAddress( + [Addresses("192.168.1.10", "fe80::1"), Addresses("fe80::2", "fd00::10")], AddressFamily.InterNetworkV6); + + Assert.Equal(IPAddress.Parse("fd00::10"), result); + } + + [Fact] + public void SelectLocalIPAddress_IPv6_FallbackLinkLocal() + { + var result = NetworkInterface.SelectLocalIPAddress([Addresses("192.168.1.10", "fe80::1")], + AddressFamily.InterNetworkV6); + + Assert.Equal(IPAddress.Parse("fe80::1"), result); + } + + [Fact] + public void SelectLocalIPAddress_NoAddressOfFamily() + { + Assert.Null(NetworkInterface.SelectLocalIPAddress([Addresses("fe80::1")], AddressFamily.InterNetwork)); + Assert.Null(NetworkInterface.SelectLocalIPAddress([], AddressFamily.InterNetworkV6)); + } + + [Theory] + [InlineData("169.254.0.1", true)] + [InlineData("169.253.0.1", false)] + [InlineData("192.168.1.1", false)] + [InlineData("fe80::1", true)] + [InlineData("2001:db8::1", false)] + [InlineData("fd00::1", false)] + public void IsLinkLocal(string ipAddress, bool expected) + { + Assert.Equal(expected, NetworkInterface.IsLinkLocal(IPAddress.Parse(ipAddress))); + } + + [Fact] + public void SelectGateway_GatewayOfTheInterfaceWithTheLocalAddress() + { + var result = NetworkInterface.SelectGateway( + [ + (Addresses("10.0.0.5"), Addresses("10.0.0.1")), + (Addresses("192.168.1.10", "fe80::10"), Addresses("fe80::1", "192.168.1.1")) + ], IPAddress.Parse("192.168.1.10")); + + Assert.Equal(IPAddress.Parse("192.168.1.1"), result); + } + + [Fact] + public void SelectGateway_IPv6() + { + var result = NetworkInterface.SelectGateway( + [(Addresses("192.168.1.10", "2001:db8::10"), Addresses("192.168.1.1", "fe80::1"))], + IPAddress.Parse("2001:db8::10")); + + Assert.Equal(IPAddress.Parse("fe80::1"), result); + } + + [Fact] + public void SelectGateway_IgnoresScopeId() + { + var local = IPAddress.Parse("fe80::10"); + local.ScopeId = 12; + + var result = NetworkInterface.SelectGateway([(Addresses("fe80::10"), Addresses("fe80::1"))], local); + + Assert.Equal(IPAddress.Parse("fe80::1"), result); + } + + [Fact] + public void SelectGateway_SkipsUnspecifiedGateway() + { + // e.g. a VPN adapter (on-link default route) + var result = NetworkInterface.SelectGateway([(Addresses("10.8.0.2"), Addresses("0.0.0.0"))], + IPAddress.Parse("10.8.0.2")); + + Assert.Null(result); + } + + [Fact] + public void SelectGateway_LocalAddressNotFound() + { + var result = NetworkInterface.SelectGateway([(Addresses("192.168.1.10"), Addresses("192.168.1.1"))], + IPAddress.Parse("10.0.0.5")); + + Assert.Null(result); + } +} diff --git a/Source/NETworkManager.Tests/Network/PublicIPAddressCheckTests.cs b/Source/NETworkManager.Tests/Network/PublicIPAddressCheckTests.cs new file mode 100644 index 0000000000..2216aadeb4 --- /dev/null +++ b/Source/NETworkManager.Tests/Network/PublicIPAddressCheckTests.cs @@ -0,0 +1,164 @@ +using System; +using System.Threading.Tasks; +using System.Net; +using System.Net.Http; +using System.Net.Sockets; +using NETworkManager.Models.Network; +using Xunit; + +namespace NETworkManager.Tests.Network; + +public class PublicIPAddressCheckTests +{ + [Theory] + [InlineData("203.0.113.10", "203.0.113.10")] + [InlineData("203.0.113.10\n", "203.0.113.10")] + [InlineData(" 203.0.113.10 ", "203.0.113.10")] + // Custom API with the address in a JSON object + [InlineData("{\"ip\":\"203.0.113.10\"}", "203.0.113.10")] + [InlineData("{ \"country\": \"DE\", \"ip\": \"203.0.113.10\" }", "203.0.113.10")] + public void ParseResponse_IPv4_Success(string content, string expected) + { + var result = PublicIPAddressCheck.ParseResponse(true, content, AddressFamily.InterNetwork); + + Assert.Equal(PublicIPAddressCheckStatus.Success, result.Status); + Assert.Equal(IPAddress.Parse(expected), result.IPAddress); + } + + [Theory] + [InlineData("2001:db8:1234::10")] + [InlineData("2001:db8:1234::10\n")] + [InlineData("{\"ip\":\"2001:db8:1234::10\"}")] + public void ParseResponse_IPv6_Success(string content) + { + var result = PublicIPAddressCheck.ParseResponse(true, content, AddressFamily.InterNetworkV6); + + Assert.Equal(PublicIPAddressCheckStatus.Success, result.Status); + Assert.Equal(IPAddress.Parse("2001:db8:1234::10"), result.IPAddress); + } + + [Theory] + // e.g. the answer of a captive portal or a proxy + [InlineData("10.1.0.1", AddressFamily.InterNetwork)] + [InlineData("{\"ip\":\"192.168.1.1\"}", AddressFamily.InterNetwork)] + [InlineData("169.254.1.1", AddressFamily.InterNetwork)] + [InlineData("127.0.0.1", AddressFamily.InterNetwork)] + [InlineData("fd00::1", AddressFamily.InterNetworkV6)] + public void ParseResponse_PrivateIPAddress(string content, AddressFamily addressFamily) + { + Assert.Equal(PublicIPAddressCheckStatus.PrivateIPAddress, + PublicIPAddressCheck.ParseResponse(true, content, addressFamily).Status); + } + + [Theory] + [InlineData(false, "203.0.113.10", AddressFamily.InterNetwork)] + [InlineData(true, "", AddressFamily.InterNetwork)] + [InlineData(true, null, AddressFamily.InterNetwork)] + [InlineData(true, "Forbidden", AddressFamily.InterNetwork)] + // HTML page of a captive portal with a link to its (public) login server + [InlineData(true, "Sign in", AddressFamily.InterNetwork)] + [InlineData(true, "Sign in: http://192.168.1.1/login", AddressFamily.InterNetwork)] + [InlineData(true, "Your IP: 203.0.113.10", AddressFamily.InterNetwork)] + // JSON without an address of the family + [InlineData(true, "{\"ip\":\"2001:db8::10\"}", AddressFamily.InterNetwork)] + // Address of the other address family + [InlineData(true, "2001:db8::10", AddressFamily.InterNetwork)] + [InlineData(true, "203.0.113.10", AddressFamily.InterNetworkV6)] + public void ParseResponse_InvalidResponse(bool isSuccessStatusCode, string content, AddressFamily addressFamily) + { + var result = PublicIPAddressCheck.ParseResponse(isSuccessStatusCode, content, addressFamily); + + Assert.Equal(PublicIPAddressCheckStatus.InvalidResponse, result.Status); + Assert.Null(result.IPAddress); + } + + [Theory] + // IPAddress.TryParse accepts these as IPv4 (e.g. an HTTP status code as answer) + [InlineData("429", AddressFamily.InterNetwork)] + [InlineData("1", AddressFamily.InterNetwork)] + [InlineData("10.1", AddressFamily.InterNetwork)] + [InlineData("0x7f000001", AddressFamily.InterNetwork)] + // Unspecified, multicast, reserved / broadcast + [InlineData("0.0.0.0", AddressFamily.InterNetwork)] + [InlineData("224.0.0.1", AddressFamily.InterNetwork)] + [InlineData("255.255.255.255", AddressFamily.InterNetwork)] + [InlineData("::", AddressFamily.InterNetworkV6)] + [InlineData("ff02::1", AddressFamily.InterNetworkV6)] + // Scope id + [InlineData("fe80::1%12", AddressFamily.InterNetworkV6)] + public void ParseResponse_NotAnIPAddressOrReserved_InvalidResponse(string content, AddressFamily addressFamily) + { + var result = PublicIPAddressCheck.ParseResponse(true, content, addressFamily); + + Assert.Equal(PublicIPAddressCheckStatus.InvalidResponse, result.Status); + Assert.Null(result.IPAddress); + } + + [Theory] + [InlineData("203.0.113.10", PublicIPAddressCheckStatus.Success)] + [InlineData("2001:db8::10", PublicIPAddressCheckStatus.Success)] + [InlineData("100.64.0.1", PublicIPAddressCheckStatus.PrivateIPAddress)] + [InlineData("100.127.255.254", PublicIPAddressCheckStatus.PrivateIPAddress)] + [InlineData("100.128.0.1", PublicIPAddressCheckStatus.Success)] + [InlineData("172.16.0.1", PublicIPAddressCheckStatus.PrivateIPAddress)] + [InlineData("::1", PublicIPAddressCheckStatus.PrivateIPAddress)] + [InlineData("fe80::1", PublicIPAddressCheckStatus.PrivateIPAddress)] + [InlineData("0.1.2.3", PublicIPAddressCheckStatus.InvalidResponse)] + [InlineData("::ffff:10.1.2.3", PublicIPAddressCheckStatus.InvalidResponse)] + [InlineData("::ffff:203.0.113.10", PublicIPAddressCheckStatus.InvalidResponse)] + [InlineData("fec0::1", PublicIPAddressCheckStatus.PrivateIPAddress)] + [InlineData("240.0.0.1", PublicIPAddressCheckStatus.InvalidResponse)] + public void GetStatus(string ipAddress, PublicIPAddressCheckStatus expected) + { + Assert.Equal(expected, PublicIPAddressCheck.GetStatus(IPAddress.Parse(ipAddress))); + } + + // Answer formats of public IP address APIs (examples in the documentation and other common ones), with + // documentation addresses. checkip.amazonaws.com: real answer (line break at the end). + [Theory] + [InlineData("api.ipify.org, ip4.seeip.org, ifconfig.me/ip", "203.0.113.10", AddressFamily.InterNetwork, "203.0.113.10")] + [InlineData("icanhazip.com, ifconfig.co/ip, ipinfo.io/ip, ident.me, checkip.amazonaws.com", "203.0.113.10\n", AddressFamily.InterNetwork, "203.0.113.10")] + [InlineData("ip-api.com/line/?fields=query", "203.0.113.10\n", AddressFamily.InterNetwork, "203.0.113.10")] + [InlineData("api.ipify.org?format=json, api.seeip.org/jsonip", "{\"ip\":\"203.0.113.10\"}", AddressFamily.InterNetwork, "203.0.113.10")] + [InlineData("JSON with other values (e.g. success, type)", "{\"success\":true,\"ip\":\"203.0.113.10\",\"type\":\"IPv4\"}", AddressFamily.InterNetwork, "203.0.113.10")] + [InlineData("ip-api.com/json", "{\"status\":\"success\",\"country\":\"Germany\",\"countryCode\":\"DE\",\"region\":\"BE\",\"regionName\":\"Land Berlin\",\"city\":\"Berlin\",\"zip\":\"10115\",\"lat\":52.5,\"lon\":13.4,\"timezone\":\"Europe/Berlin\",\"isp\":\"Example ISP\",\"org\":\"\",\"as\":\"AS64496 Example\",\"query\":\"203.0.113.10\"}", AddressFamily.InterNetwork, "203.0.113.10")] + [InlineData("ipinfo.io/json", "{\n \"ip\": \"203.0.113.10\",\n \"hostname\": \"host.example.com\",\n \"city\": \"Berlin\",\n \"loc\": \"52.5244,13.4105\",\n \"readme\": \"https://ipinfo.io/missingauth\"\n}", AddressFamily.InterNetwork, "203.0.113.10")] + [InlineData("ifconfig.co/json", "{\n \"ip\": \"203.0.113.10\",\n \"ip_decimal\": 3405803786,\n \"country\": \"Germany\"\n}", AddressFamily.InterNetwork, "203.0.113.10")] + [InlineData("api6.ipify.org, v6.ident.me", "2001:db8:85a3::8a2e:370:7334", AddressFamily.InterNetworkV6, "2001:db8:85a3::8a2e:370:7334")] + [InlineData("ipv6.icanhazip.com", "2001:db8:85a3::8a2e:370:7334\n", AddressFamily.InterNetworkV6, "2001:db8:85a3::8a2e:370:7334")] + [InlineData("api64.ipify.org?format=json", "{\"ip\":\"2001:db8:85a3::8a2e:370:7334\"}", AddressFamily.InterNetworkV6, "2001:db8:85a3::8a2e:370:7334")] + [InlineData("JSON with other values (IPv6)", "{\"success\":true,\"ip\":\"2001:db8:85a3::8a2e:370:7334\",\"type\":\"IPv6\"}", AddressFamily.InterNetworkV6, "2001:db8:85a3::8a2e:370:7334")] + // A dual-stack API answering with IPv6 to the IPv4 request: no valid answer for IPv4 + [InlineData("api64.ipify.org (IPv6 answer)", "2001:db8:85a3::8a2e:370:7334", AddressFamily.InterNetwork, null)] + // Cloudflare trace (key=value lines, h= is the host, not the client): not supported + [InlineData("1.1.1.1/cdn-cgi/trace", "fl=123f45\nh=1.1.1.1\nip=203.0.113.10\nts=1700000000.123\n", AddressFamily.InterNetwork, null)] + public void ParseResponse_KnownAPIs(string api, string content, AddressFamily addressFamily, string expected) + { + var result = PublicIPAddressCheck.ParseResponse(true, content, addressFamily); + + Assert.True(expected == null + ? result.Status == PublicIPAddressCheckStatus.InvalidResponse + : result.Status == PublicIPAddressCheckStatus.Success && result.IPAddress.Equals(IPAddress.Parse(expected)), + $"{api}: {result.Status} {result.IPAddress}"); + } + + [Fact] + public void FromException_NameResolutionFailed() + { + var exception = new HttpRequestException("No such host is known.", + new SocketException((int)SocketError.HostNotFound)); + + Assert.Equal(PublicIPAddressCheckStatus.NameResolutionFailed, + PublicIPAddressCheck.FromException(exception).Status); + } + + [Fact] + public void FromException_RequestFailed() + { + Assert.Equal(PublicIPAddressCheckStatus.RequestFailed, + PublicIPAddressCheck.FromException(new HttpRequestException("Connection refused", + new SocketException((int)SocketError.ConnectionRefused))).Status); + Assert.Equal(PublicIPAddressCheckStatus.RequestFailed, + PublicIPAddressCheck.FromException(new TaskCanceledException("Timeout")).Status); + } +} diff --git a/Source/NETworkManager/MainWindow.xaml.cs b/Source/NETworkManager/MainWindow.xaml.cs index da3f478990..d3ea6275e2 100644 --- a/Source/NETworkManager/MainWindow.xaml.cs +++ b/Source/NETworkManager/MainWindow.xaml.cs @@ -123,11 +123,23 @@ private void OnPropertyChanged([CallerMemberName] string propertyName = null) /// private readonly DispatcherTimer _configureDNSServerDispatcherTimer = new(); + /// + /// Timer to handle a network change once the network has settled: Windows raises several events per change (e.g. + /// link up, then the DHCP address), every event restarts the timer. + /// + private readonly DispatcherTimer _networkChangeDispatcherTimer = new(); + + /// + /// First network change event since the last handled change. The timer is not restarted anymore after 3 times + /// , so a network that keeps changing (e.g. + /// flapping Wi-Fi, VPN reconnects) is still handled. + /// + private DateTime _firstNetworkChange; + private readonly bool _isLoading; private bool _isProfileFilesLoading; private bool _isProfileFileUpdating; private bool _isApplicationViewLoading; - private bool _isNetworkChanging; private bool _isInTray; private bool _isClosing; @@ -566,6 +578,10 @@ private void Load() _statusWindow = new StatusWindow(this); // Detect network changes... + _networkChangeDispatcherTimer.Interval = + TimeSpan.FromMilliseconds(GlobalStaticConfiguration.NetworkChangeDetectionDelay); + _networkChangeDispatcherTimer.Tick += NetworkChangeDispatcherTimer_Tick; + NetworkChange.NetworkAvailabilityChanged += (_, _) => OnNetworkHasChanged(); NetworkChange.NetworkAddressChanged += (_, _) => OnNetworkHasChanged(); @@ -1080,6 +1096,9 @@ private void ListViewApplication_OnSelectionChanged(object sender, private async void NavigationManager_ApplicationRequested(object sender, ApplicationRequest request) { + // Requested from another window (e.g. the status window): show the main window, also for the error message below + ShowWindow(); + // Clear the search, otherwise the application may be filtered out ApplicationSearch = string.Empty; @@ -1589,7 +1608,11 @@ private void MetroWindowMain_StateChanged(object sender, EventArgs e) } if (WindowState != WindowState.Minimized) + { + // Restored: the dashboard may be outdated (e.g. a network change while minimized) + _dashboardView?.OnMainWindowShown(); return; + } if (SettingsManager.Current.Window_MinimizeToTrayInsteadOfTaskbar) HideWindowToTray(); @@ -1790,6 +1813,9 @@ private void ShowWindowFromTray() Show(); + // The dashboard may be outdated (e.g. a network change while in the tray) + _dashboardView?.OnMainWindowShown(); + _notifyIcon.Visible = SettingsManager.Current.TrayIcon_AlwaysShowIcon; } @@ -1852,33 +1878,55 @@ private void OpenStatusWindow(bool enableCloseTimer = false) _statusWindow.ShowWindow(enableCloseTimer); } - private async void OnNetworkHasChanged() + /// + /// Called by the events (thread pool, several times per change). (Re)starts the + /// timer on the UI thread, so the change is handled once, when the network has settled. + /// + private void OnNetworkHasChanged() { - if (_isNetworkChanging) - return; + Dispatcher.InvokeAsync(() => + { + if (!_networkChangeDispatcherTimer.IsEnabled) + { + _firstNetworkChange = DateTime.Now; + } + else if (DateTime.Now - _firstNetworkChange >= + TimeSpan.FromMilliseconds(GlobalStaticConfiguration.NetworkChangeDetectionDelay * 3)) + { + // Waited long enough: let the running timer handle the change + return; + } - _isNetworkChanging = true; + _networkChangeDispatcherTimer.Stop(); + _networkChangeDispatcherTimer.Start(); + }); + } - // Wait, because the event may be triggered several times. - await Task.Delay(GlobalStaticConfiguration.NetworkChangeDetectionDelay); + private void NetworkChangeDispatcherTimer_Tick(object sender, EventArgs e) + { + _networkChangeDispatcherTimer.Stop(); Log.Info("Network availability or address has changed!"); // Reconfigure the DNS client if network changed - re-detects the Windows default DNS servers // and, if enabled, the auto-detected DNS suffix (both of which can differ on the new network). - Log.Info("Update DNS server configuration..."); - ConfigureDNSServer(); - - // Show status window on network change - if (SettingsManager.Current.Status_ShowWindowOnNetworkChange) + // On the UI thread like after a change of the DNS settings, so both can't overlap (the last one wins). + try { - await Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate - { - OpenStatusWindow(true); - })); + Log.Info("Update DNS server configuration..."); + ConfigureDNSServer(); + } + catch (Exception ex) + { + Log.Error("Could not update the DNS server configuration after the network has changed.", ex); } - _isNetworkChanging = false; + // Check the network connection on the dashboard again + _dashboardView?.OnNetworkChanged(!_isInTray && WindowState != WindowState.Minimized); + + // Show status window on network change + if (SettingsManager.Current.Status_ShowWindowOnNetworkChange) + OpenStatusWindow(true); } #endregion diff --git a/Source/NETworkManager/NotificationWindow.xaml b/Source/NETworkManager/NotificationWindow.xaml index 2fec098aa4..6e112f7cc5 100644 --- a/Source/NETworkManager/NotificationWindow.xaml +++ b/Source/NETworkManager/NotificationWindow.xaml @@ -135,7 +135,7 @@ diff --git a/Source/NETworkManager/StatusWindow.xaml b/Source/NETworkManager/StatusWindow.xaml index d32b907e58..14b60eecc1 100644 --- a/Source/NETworkManager/StatusWindow.xaml +++ b/Source/NETworkManager/StatusWindow.xaml @@ -11,6 +11,7 @@ mc:Ignorable="d" d:DataContext="{d:DesignInstance networkManager:StatusWindow}" TitleAlignment="Left" Style="{DynamicResource ResourceKey=FrameWindow}" + Activated="MetroWindow_Activated" Deactivated="MetroWindow_Deactivated" Topmost="True" ShowInTaskbar="False" @@ -57,7 +58,7 @@ Margin="0" Minimum="0" Maximum="{Binding TimeMax, Mode=OneWay}" - Value="{Binding Time, Mode=OneWay}" + networkManager:SmoothProgress.Value="{Binding Time, Mode=OneWay}" Visibility="{Binding ShowTime, Converter={StaticResource BooleanToVisibilityCollapsedConverter}}" BorderThickness="0" Padding="0" /> diff --git a/Source/NETworkManager/StatusWindow.xaml.cs b/Source/NETworkManager/StatusWindow.xaml.cs index 8da7006ba6..fcbc68a959 100644 --- a/Source/NETworkManager/StatusWindow.xaml.cs +++ b/Source/NETworkManager/StatusWindow.xaml.cs @@ -54,6 +54,12 @@ private void OnPropertyChanged([CallerMemberName] string propertyName = null) private readonly DispatcherTimer _dispatcherTimerClose = new(DispatcherPriority.Render); private readonly Stopwatch _stopwatch = new(); + /// + /// Incremented whenever the close timer is started or stopped. The expired timer only hides the window if it is + /// still the same run (the user may have opened the window again while the timer waited before hiding it). + /// + private int _closeTimerRun; + private readonly MainWindow _mainWindow; private readonly NetworkConnectionWidgetView _networkConnectionView; @@ -106,7 +112,7 @@ public double Time private void ShowMainWindowAction() { - Hide(); + HideWindow(); if (_mainWindow.ShowWindowCommand.CanExecute(null)) _mainWindow.ShowWindowCommand.Execute(null); @@ -116,7 +122,7 @@ private void ShowMainWindowAction() private void CloseAction() { - Hide(); + HideWindow(); } #endregion @@ -134,27 +140,37 @@ private void Check() /// Automatically close the window after a certain time. public void ShowWindow(bool enableCloseTimer = false) { + // A network change while the user has the window open (no countdown): keep it open, only check again + if (enableCloseTimer && IsVisible && !ShowTime) + { + Check(); + return; + } + // Position bottom-right on the primary screen. With SizeToContent="Height" the final // height is only known after layout, so this is refined again in SizeChanged. UpdatePosition(); + // Opened on a network change: don't take the focus from the application the user is working in (the window + // closes itself, see the close timer). Clicking into it stops the close timer (Activated). + ShowActivated = !enableCloseTimer; + + // Close the window after a certain time. Before Show(), so the countdown is part of the first layout (the + // window doesn't grow and move right after it was shown). + if (enableCloseTimer) + SetupCloseTimer(); + // Show the window Show(); // Check the network connection Check(); - // Close the window after a certain time if (enableCloseTimer) - { - SetupCloseTimer(); return; - } // Opened by the user, cancel a running close timer (e.g. if the window was opened on a network change) - _dispatcherTimerClose.Stop(); - _stopwatch.Stop(); - ShowTime = false; + StopCloseTimer(); // Focus the window Activate(); @@ -172,13 +188,21 @@ private void UpdatePosition() return; var scaleFactor = System.Windows.Media.VisualTreeHelper.GetDpi(this).DpiScaleX; + var workingArea = Screen.PrimaryScreen.WorkingArea; + + // Not wider than the working area (e.g. 1280 x 720 with 150 % scaling is 853 px wide), otherwise the window + // would start outside the screen on the left + MaxWidth = Math.Max(0, workingArea.Width / scaleFactor - 20); - Left = Screen.PrimaryScreen.WorkingArea.Right / scaleFactor - Width - 10; - Top = Screen.PrimaryScreen.WorkingArea.Bottom / scaleFactor - ActualHeight - 10; + Left = Math.Max(workingArea.Left / scaleFactor + 10, + workingArea.Right / scaleFactor - Math.Min(Width, MaxWidth) - 10); + Top = workingArea.Bottom / scaleFactor - ActualHeight - 10; } private void SetupCloseTimer() { + _closeTimerRun++; + TimeMax = SettingsManager.Current.Status_WindowCloseTime; Time = TimeMax; @@ -187,20 +211,51 @@ private void SetupCloseTimer() _dispatcherTimerClose.Start(); } + /// + /// Stops the close timer (e.g. the window is opened by the user or hidden). A pending close of the expired timer + /// is canceled, see . + /// + private void StopCloseTimer() + { + _closeTimerRun++; + + _dispatcherTimerClose.Stop(); + _stopwatch.Stop(); + ShowTime = false; + } + + /// + /// Hides the window and stops the close timer, so it doesn't keep running in the background. + /// + private void HideWindow() + { + StopCloseTimer(); + + Hide(); + } + #endregion #region Events + private void MetroWindow_Activated(object sender, EventArgs e) + { + // The user clicked into the window that was opened on a network change: keep it open (like opened by the user). + // ShowTime: the countdown is running or has just ended (the window is hidden after a short delay). + if (ShowTime) + StopCloseTimer(); + } + private void MetroWindow_Deactivated(object sender, EventArgs e) { - Hide(); + HideWindow(); } private void MetroWindow_Closing(object sender, CancelEventArgs e) { e.Cancel = true; - Hide(); + HideWindow(); } private async void DispatcherTimerTime_Tick(object sender, EventArgs e) @@ -216,11 +271,15 @@ private async void DispatcherTimerTime_Tick(object sender, EventArgs e) _dispatcherTimerClose.Stop(); _stopwatch.Stop(); + var run = _closeTimerRun; + await Task.Delay(250); - ShowTime = false; + // Opened again (by the user or another network change) in the meantime + if (run != _closeTimerRun) + return; - Hide(); + HideWindow(); } #endregion diff --git a/Source/NETworkManager/ViewModels/ConnectionCheckItem.cs b/Source/NETworkManager/ViewModels/ConnectionCheckItem.cs index 202b832fc3..051705a8db 100644 --- a/Source/NETworkManager/ViewModels/ConnectionCheckItem.cs +++ b/Source/NETworkManager/ViewModels/ConnectionCheckItem.cs @@ -1,14 +1,81 @@ +using System.Linq; +using System.Net; +using System.Windows.Input; +using NETworkManager.Localization; +using NETworkManager.Models; using NETworkManager.Models.Network; using NETworkManager.Utilities; namespace NETworkManager.ViewModels; +/// +/// Kind of a : decides which other tools can be opened with its value. +/// +public enum ConnectionCheckItemKind +{ + /// + /// IP address of the computer. + /// + ComputerIPAddress, + + /// + /// IP address of the gateway / router. + /// + RouterIPAddress, + + /// + /// Public IP address (internet). + /// + PublicIPAddress, + + /// + /// DNS name (PTR). + /// + DNSName +} + /// /// Represents a single "is checking / value / state" row (e.g. Computer IPv4, Router DNS, ...) /// shown by . /// public class ConnectionCheckItem : PropertyChangedBase { + /// + /// Initializes a new instance of the class. + /// + /// Kind of the item (which tools can be opened with its value). + public ConnectionCheckItem(ConnectionCheckItemKind kind) + { + Kind = kind; + } + + /// + /// Gets the kind of the item. + /// + public ConnectionCheckItemKind Kind { get; } + + /// + /// Gets a value indicating whether the value is an IP address (not a DNS name). + /// + public bool IsIPAddress => Kind != ConnectionCheckItemKind.DNSName; + + /// + /// Gets a value indicating whether the value is the IP address of the gateway / router (e.g. web interface). + /// + public bool IsRouterIPAddress => Kind == ConnectionCheckItemKind.RouterIPAddress; + + /// + /// Gets a value indicating whether the target can be opened in the Web Console: the gateway / router, but not a + /// link-local IPv6 address (the scope id, e.g. fe80::1%12, is not valid in a URL). + /// + public bool IsWebConsoleAvailable => IsRouterIPAddress && + !(IPAddress.TryParse(Target, out var ipAddress) && ipAddress.IsIPv6LinkLocal); + + /// + /// Gets a value indicating whether the value is the public IP address (e.g. IP geolocation, RDAP). + /// + public bool IsPublicIPAddress => Kind == ConnectionCheckItemKind.PublicIPAddress; + /// /// Gets or sets a value indicating whether this item is currently being checked. /// @@ -57,6 +124,41 @@ public ConnectionState State } } = ConnectionState.None; + /// + /// Gets or sets the reason of the state (e.g. why it is a warning), shown as tooltip of the state icon. null + /// if there is nothing to explain. + /// + public string Message + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets or sets the IP address or DNS name that is opened in other tools (e.g. without the round-trip time of the + /// value), null if there is none. + /// + public string Target + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + OnPropertyChanged(nameof(IsWebConsoleAvailable)); + } + } + /// /// Resets the item to its initial "checking" state. /// @@ -64,16 +166,67 @@ public void Reset() { IsChecking = true; Value = ""; + Target = null; State = ConnectionState.None; + Message = null; } /// /// Completes the check with the given value and state. /// - public void Complete(string value, ConnectionState state) + /// Value shown (-/- if there is none). + /// State of the check. + /// Reason of the state (tooltip), null if none. + /// IP address or DNS name for other tools, by default the value (if there is one), an empty + /// string for none. + public void Complete(string value, ConnectionState state, string message = null, string target = null) { Value = value; + Target = target != null + ? target.Length == 0 ? null : target + : string.IsNullOrEmpty(value) || value == "-/-" ? null : value; State = state; + Message = message; IsChecking = false; } + + /// + /// Completes the check with the given value and the state and (localized) reason of the result. + /// + /// Value shown (-/- if there is none). + /// State and reason. + /// IP address or DNS name for other tools, by default the value (if there is one), an empty + /// string for none. + public void Complete(string value, ConnectionCheckResult result, string target = null) + { + Complete(value, result.State, result.Reason == ConnectionCheckReason.None + ? null + : ResourceTranslator.Translate(ResourceIdentifier.ConnectionCheckReason, result.Reason), target); + } + + /// + /// Gets the command to copy the value. + /// + public ICommand CopyValueCommand => new RelayCommand(_ => ClipboardHelper.SetClipboard(Value), + _ => !string.IsNullOrEmpty(Value) && Value != "-/-"); + + /// + /// Gets the command to open the target in another tool (parameter: ). + /// + public ICommand OpenApplicationCommand => new RelayCommand(OpenApplicationAction, _ => Target != null); + + private void OpenApplicationAction(object parameter) + { + if (parameter is not ApplicationName applicationName || Target == null) + return; + + NavigationManager.Open(applicationName switch + { + ApplicationName.DNSLookup => new DNSLookupRequest { Target = Target }, + ApplicationName.RDAP => new RDAPRequest { Target = Target }, + ApplicationName.WebConsole => new ApplicationRequest(applicationName) + { Target = WebConsoleUrlHelper.CreateUrl(Target, Enumerable.Empty()) }, + _ => new ApplicationRequest(applicationName) { Target = Target } + }); + } } diff --git a/Source/NETworkManager/ViewModels/DashboardSettingsViewModel.cs b/Source/NETworkManager/ViewModels/DashboardSettingsViewModel.cs index 5d843accac..d5aa014d4b 100644 --- a/Source/NETworkManager/ViewModels/DashboardSettingsViewModel.cs +++ b/Source/NETworkManager/ViewModels/DashboardSettingsViewModel.cs @@ -185,6 +185,82 @@ public bool CheckIPApiDNSResolverEnabled } } + /// + /// Gets or sets a value indicating whether the network connection widget is shown on the dashboard. + /// + public bool ShowNetworkConnectionWidget + { + get; + set + { + if (value == field) + return; + + if (!_isLoading) + SettingsManager.Current.Dashboard_ShowNetworkConnectionWidget = value; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets or sets a value indicating whether the speed test widget is shown on the dashboard. + /// + public bool ShowSpeedTestWidget + { + get; + set + { + if (value == field) + return; + + if (!_isLoading) + SettingsManager.Current.Dashboard_ShowSpeedTestWidget = value; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets or sets a value indicating whether the IP geolocation widget is shown on the dashboard. + /// + public bool ShowIPGeolocationWidget + { + get; + set + { + if (value == field) + return; + + if (!_isLoading) + SettingsManager.Current.Dashboard_ShowIPGeolocationWidget = value; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets or sets a value indicating whether the DNS resolver widget is shown on the dashboard. + /// + public bool ShowDNSResolverWidget + { + get; + set + { + if (value == field) + return; + + if (!_isLoading) + SettingsManager.Current.Dashboard_ShowDNSResolverWidget = value; + + field = value; + OnPropertyChanged(); + } + } + #endregion #region Contructor, load settings @@ -215,6 +291,10 @@ private void LoadSettings() CustomPublicIPv6AddressAPI = SettingsManager.Current.Dashboard_CustomPublicIPv6AddressAPI; CheckIPApiIPGeolocationEnabled = SettingsManager.Current.Dashboard_CheckIPApiIPGeolocation; CheckIPApiDNSResolverEnabled = SettingsManager.Current.Dashboard_CheckIPApiDNSResolver; + ShowNetworkConnectionWidget = SettingsManager.Current.Dashboard_ShowNetworkConnectionWidget; + ShowSpeedTestWidget = SettingsManager.Current.Dashboard_ShowSpeedTestWidget; + ShowIPGeolocationWidget = SettingsManager.Current.Dashboard_ShowIPGeolocationWidget; + ShowDNSResolverWidget = SettingsManager.Current.Dashboard_ShowDNSResolverWidget; } #endregion diff --git a/Source/NETworkManager/ViewModels/NetworkConnectionWidgetViewModel.cs b/Source/NETworkManager/ViewModels/NetworkConnectionWidgetViewModel.cs index f68e6e5194..20fe336a18 100644 --- a/Source/NETworkManager/ViewModels/NetworkConnectionWidgetViewModel.cs +++ b/Source/NETworkManager/ViewModels/NetworkConnectionWidgetViewModel.cs @@ -2,15 +2,18 @@ using NETworkManager.Settings; using NETworkManager.Utilities; using System; +using System.Linq; using System.Net; using System.Net.Http; -using System.Text.RegularExpressions; using System.Threading; +using System.Net.NetworkInformation; using System.Threading.Tasks; using System.Windows.Input; using log4net; using NetworkInterface = NETworkManager.Models.Network.NetworkInterface; using System.Net.Sockets; +using System.Text; +using NETworkManager.Localization.Resources; namespace NETworkManager.ViewModels; @@ -31,22 +34,27 @@ public class NetworkConnectionWidgetViewModel : ViewModelBase /// private static readonly HttpClient PublicIPHttpClient = new() { Timeout = TimeSpan.FromSeconds(10) }; + /// + /// Data sent with the ping of the gateway and the public IP address. + /// + private static readonly byte[] PingBuffer = new byte[GlobalStaticConfiguration.Dashboard_PingBuffer]; + #region Computer /// /// Gets the computer IPv4 check (is checking / value / state). /// - public ConnectionCheckItem ComputerIPv4 { get; } = new(); + public ConnectionCheckItem ComputerIPv4 { get; } = new(ConnectionCheckItemKind.ComputerIPAddress); /// /// Gets the computer IPv6 check (is checking / value / state). /// - public ConnectionCheckItem ComputerIPv6 { get; } = new(); + public ConnectionCheckItem ComputerIPv6 { get; } = new(ConnectionCheckItemKind.ComputerIPAddress); /// /// Gets the computer DNS check (is checking / value / state). /// - public ConnectionCheckItem ComputerDNS { get; } = new(); + public ConnectionCheckItem ComputerDNS { get; } = new(ConnectionCheckItemKind.DNSName); #endregion @@ -55,17 +63,17 @@ public class NetworkConnectionWidgetViewModel : ViewModelBase /// /// Gets the router IPv4 check (is checking / value / state). /// - public ConnectionCheckItem RouterIPv4 { get; } = new(); + public ConnectionCheckItem RouterIPv4 { get; } = new(ConnectionCheckItemKind.RouterIPAddress); /// /// Gets the router IPv6 check (is checking / value / state). /// - public ConnectionCheckItem RouterIPv6 { get; } = new(); + public ConnectionCheckItem RouterIPv6 { get; } = new(ConnectionCheckItemKind.RouterIPAddress); /// /// Gets the router DNS check (is checking / value / state). /// - public ConnectionCheckItem RouterDNS { get; } = new(); + public ConnectionCheckItem RouterDNS { get; } = new(ConnectionCheckItemKind.DNSName); #endregion @@ -74,24 +82,35 @@ public class NetworkConnectionWidgetViewModel : ViewModelBase /// /// Gets the internet IPv4 check (is checking / value / state). /// - public ConnectionCheckItem InternetIPv4 { get; } = new(); + public ConnectionCheckItem InternetIPv4 { get; } = new(ConnectionCheckItemKind.PublicIPAddress); /// /// Gets the internet IPv6 check (is checking / value / state). /// - public ConnectionCheckItem InternetIPv6 { get; } = new(); + public ConnectionCheckItem InternetIPv6 { get; } = new(ConnectionCheckItemKind.PublicIPAddress); /// /// Gets the internet DNS check (is checking / value / state). /// - public ConnectionCheckItem InternetDNS { get; } = new(); + public ConnectionCheckItem InternetDNS { get; } = new(ConnectionCheckItemKind.DNSName); #endregion /// - /// Gets a value indicating whether checking the public IP address is enabled. + /// Gets the time of the last check, null before the first one. /// - public bool CheckPublicIPAddressEnabled => SettingsManager.Current.Dashboard_CheckPublicIPAddress; + public DateTime? LastCheckTime + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } /// /// Gets or sets a value indicating whether a check is currently running. @@ -116,14 +135,44 @@ private set /// /// Gets the command to check connections. /// - public ICommand CheckCommand => new RelayCommand(_ => Check()); + public ICommand CheckCommand => new RelayCommand(_ => Check(), _ => !IsChecking); + + /// + /// Gets the command to copy all values (with the reasons of the states), e.g. for a support request. + /// + public ICommand CopyAllCommand => new RelayCommand(_ => CopyAllAction(), _ => !IsChecking && LastCheckTime != null); + + private void CopyAllAction() + { + var text = new StringBuilder(); + + foreach (var (title, ipv4, ipv6, dns) in new[] + { + (Strings.Computer, ComputerIPv4, ComputerIPv6, ComputerDNS), + (Strings.GatewayRouter, RouterIPv4, RouterIPv6, RouterDNS), + (Strings.Internet, InternetIPv4, InternetIPv6, InternetDNS) + }) + { + if (text.Length > 0) + text.AppendLine(); + + text.AppendLine(title); + + foreach (var (label, item) in new[] { (Strings.IPv4, ipv4), (Strings.IPv6, ipv6), (Strings.DNS, dns) }) + text.AppendLine(item.Message == null + ? $"{label}: {item.Value}" + : $"{label}: {item.Value} ({item.Message})"); + } + + ClipboardHelper.SetClipboard(text.ToString().TrimEnd()); + } #endregion #region Methods /// - /// Checks the network connections. + /// Checks the network connections. If a check is already running, it is repeated once it has finished. /// public void Check() { @@ -131,155 +180,135 @@ public void Check() } /// - /// The cancellation token source. - /// - private CancellationTokenSource _cancellationTokenSource; - - /// - /// The check task. + /// A check was requested while another one was running (e.g. a network change during a check). The running check + /// is repeated once it has finished, so the result shows the latest state. Only used on the UI thread. /// - private Task _checkTask = Task.CompletedTask; - - /// - /// Monotonically increasing id of the current check run. None of the underlying detection/DNS - /// calls support real mid-flight cancellation (see ), so a superseded run - /// can still be executing in the background after a newer run has started. Every write to a - /// is guarded by comparing against this field, so a superseded - /// run's results are silently discarded instead of racing with the current run's writes. - /// - private long _generation; + private bool _recheckPending; /// /// Checks the network connections asynchronously. /// private async Task CheckAsync() { - Log.Info("Checking network connection..."); - - // Bump the generation immediately so a still-running previous check stops writing - // its results as soon as possible, even before it notices the cancellation below. - var generation = Interlocked.Increment(ref _generation); - - // Cancel previous checks if running - if (!_checkTask.IsCompleted) + if (IsChecking) { - Log.Info("Cancelling previous checks..."); - await _cancellationTokenSource.CancelAsync(); - - try - { - await _checkTask; - } - catch (OperationCanceledException) - { - Log.Info("Task was cancelled from previous checks."); - } - finally - { - _cancellationTokenSource.Dispose(); - } + _recheckPending = true; + return; } - _cancellationTokenSource = new CancellationTokenSource(); - var wasCanceled = false; - IsChecking = true; try { - _checkTask = RunTask(_cancellationTokenSource.Token, generation); - await _checkTask; - } - catch (OperationCanceledException) - { - wasCanceled = true; - Log.Info("Task was cancelled from current checks."); + do + { + _recheckPending = false; + + try + { + Log.Info("Checking network connection..."); + + // Takes at least the refresh interval, so the reload animation is visible and the check can't be + // spammed - the checks run at the same time + await TaskHelper.WithMinimumDurationAsync(RunTask, + GlobalStaticConfiguration.ApplicationUIRefreshInterval); + + Log.Info("Network connection check completed."); + } + catch (Exception ex) + { + Log.Error("Network connection check failed.", ex); + + // Don't leave the remaining rows loading until the next check + foreach (var item in GetAllItems().Where(x => x.IsChecking)) + item.Complete("-/-", ConnectionState.Critical); + } + + LastCheckTime = DateTime.Now; + + // A check requested in the meantime (e.g. a network change) runs also after an error + } while (_recheckPending); } finally { IsChecking = false; - _cancellationTokenSource.Dispose(); - if (!wasCanceled) - Log.Info("Network connection check completed."); + // Enable the refresh / copy all buttons (CanExecute is otherwise only evaluated on the next input, e.g. not + // in the status window opened on a network change without the focus) + CommandManager.InvalidateRequerySuggested(); } } /// /// Runs the check tasks. /// - /// The cancellation token. - /// The id of this check run, see . /// A task representing the asynchronous operation. - private async Task RunTask(CancellationToken ct, long generation) + private async Task RunTask() { ResetAllItems(); if (ScreenshotData.IsEnabled) { - // Wait like a real check, so the loading animation is visible - await Task.Delay(GlobalStaticConfiguration.ApplicationUIRefreshInterval, ct); - - SetScreenshotData(generation); + SetScreenshotData(); return; } - // Detect the local IPv4/IPv6 address once and share it between the Computer and Router - // checks below, instead of each of them redetecting it independently (both used to - // trigger their own, potentially PowerShell-backed, network interface lookup). - var localIPv4Task = DetectLocalIPv4Async(); - var localIPv6Task = DetectLocalIPv6Async(); + // Detect the local IPv4/IPv6 address once and share it between the Computer, Router and Internet checks below + var localIPv4Task = DetectLocalIPAddressAsync(SettingsManager.Current.Dashboard_PublicIPv4Address, + AddressFamily.InterNetwork); + var localIPv6Task = DetectLocalIPAddressAsync(SettingsManager.Current.Dashboard_PublicIPv6Address, + AddressFamily.InterNetworkV6); await Task.WhenAll(localIPv4Task, localIPv6Task); - if (ct.IsCancellationRequested) - ct.ThrowIfCancellationRequested(); + var (localIPv4, isIPv4Routed) = localIPv4Task.Result; + var (localIPv6, isIPv6Routed) = localIPv6Task.Result; + + var computerIPv4Result = NetworkConnectionCheck.GetLocalIPAddressResult(localIPv4, AddressFamily.InterNetwork, isIPv4Routed); + var computerIPv6Result = NetworkConnectionCheck.GetLocalIPAddressResult(localIPv6, AddressFamily.InterNetworkV6, isIPv6Routed); - var localIPv4 = localIPv4Task.Result; - var localIPv6 = localIPv6Task.Result; + ComputerIPv4.Complete(localIPv4?.ToString() ?? "-/-", computerIPv4Result); + ComputerIPv6.Complete(localIPv6?.ToString() ?? "-/-", computerIPv6Result); - SetAddressResult(ComputerIPv4, localIPv4, generation); - SetAddressResult(ComputerIPv6, localIPv6, generation); + // Without a routed IPv6 address, the IPv6 checks of the router and the internet are not available + var isIPv6Available = computerIPv6Result.State == ConnectionState.OK; + + // No DNS name of a link-local IPv4 address (no DHCP server): the lookup fails and would point to the DNS server + var resolveIPv4 = localIPv4 != null && !NetworkInterface.IsLinkLocal(localIPv4) ? localIPv4 : null; await Task.WhenAll( - CheckConnectionComputerDnsAsync(ct, generation), - CheckConnectionRouterAsync(localIPv4, localIPv6, ct, generation), - CheckConnectionInternetAsync(ct, generation) + CheckConnectionComputerDnsAsync(resolveIPv4, isIPv6Available ? localIPv6 : null), + CheckConnectionRouterAsync(localIPv4, isIPv4Routed, isIPv6Available ? localIPv6 : null), + CheckConnectionInternetAsync(isIPv6Available) ); } /// - /// Resets all connection check items to their initial "checking" state. The Internet items are - /// only reset when the public IP address check is enabled, so they stay untouched (not stuck - /// "checking") when it is disabled. + /// Resets all connection check items to their initial "checking" state. /// private void ResetAllItems() { - ComputerIPv4.Reset(); - ComputerIPv6.Reset(); - ComputerDNS.Reset(); - - RouterIPv4.Reset(); - RouterIPv6.Reset(); - RouterDNS.Reset(); - - if (!CheckPublicIPAddressEnabled) - return; - - InternetIPv4.Reset(); - InternetIPv6.Reset(); - InternetDNS.Reset(); + foreach (var item in GetAllItems()) + item.Reset(); } /// - /// Sets the sample data of instead of the real (personal) addresses, unless a newer - /// check has started in the meantime. + /// Gets all connection check items. /// - private void SetScreenshotData(long generation) + private ConnectionCheckItem[] GetAllItems() { - if (generation != _generation) - return; + return + [ + ComputerIPv4, ComputerIPv6, ComputerDNS, RouterIPv4, RouterIPv6, RouterDNS, InternetIPv4, InternetIPv6, + InternetDNS + ]; + } + /// + /// Sets the sample data of instead of the real (personal) addresses. + /// + private void SetScreenshotData() + { ComputerIPv4.Complete(ScreenshotData.ComputerIPv4, ConnectionState.OK); ComputerIPv6.Complete(ScreenshotData.ComputerIPv6, ConnectionState.OK); ComputerDNS.Complete(ScreenshotData.ComputerDNS, ConnectionState.OK); @@ -288,310 +317,302 @@ private void SetScreenshotData(long generation) RouterIPv6.Complete(ScreenshotData.RouterIPv6, ConnectionState.OK); RouterDNS.Complete(ScreenshotData.RouterDNS, ConnectionState.OK); - if (!CheckPublicIPAddressEnabled) - return; - InternetIPv4.Complete(ScreenshotData.InternetIPv4, ConnectionState.OK); InternetIPv6.Complete(ScreenshotData.InternetIPv6, ConnectionState.OK); InternetDNS.Complete(ScreenshotData.InternetDNS, ConnectionState.OK); } /// - /// Detects the local IPv4 address, based on routing to the configured public IPv4 address, with - /// a fallback to detection based on the network interfaces. + /// Detects the local IP address, based on routing to the configured public IP address (setting), with a fallback + /// to detection based on the network interfaces. /// - private static async Task DetectLocalIPv4Async() + /// Public IPv4 or IPv6 address (setting) used to find the route. + /// IPv4 or IPv6. + /// Local IP address (null if none was found) and whether it was detected via the route. + private static async Task<(IPAddress Address, bool IsRouted)> DetectLocalIPAddressAsync(string remoteIPAddress, + AddressFamily addressFamily) { - Log.Debug($"{nameof(DetectLocalIPv4Async)} - Detecting local IPv4 address..."); + Log.Debug($"{nameof(DetectLocalIPAddressAsync)} - Detecting local {addressFamily} address..."); - IPAddress remoteIPv4 = null; + IPAddress detected = null; - try - { - remoteIPv4 = IPAddress.Parse(SettingsManager.Current.Dashboard_PublicIPv4Address); - } - catch (Exception ex) - { - Log.Warn($"{nameof(DetectLocalIPv4Async)} - Invalid Dashboard_PublicIPv4Address setting, skipping routing based detection.", ex); - } + if (IPAddress.TryParse(remoteIPAddress, out var remote) && remote.AddressFamily == addressFamily) + detected = await NetworkInterface.DetectLocalIPAddressBasedOnRoutingAsync(remote); + else + Log.Warn($"{nameof(DetectLocalIPAddressAsync)} - Invalid public {addressFamily} address \"{remoteIPAddress}\" in the settings, skipping routing based detection."); - var detected = remoteIPv4 != null - ? await NetworkInterface.DetectLocalIPAddressBasedOnRoutingAsync(remoteIPv4) - : null; + var isRouted = detected != null; - if (detected == null) + if (!isRouted) { - Log.Debug($"{nameof(DetectLocalIPv4Async)} - Local IPv4 address detection via routing failed, trying network interfaces..."); - detected = await NetworkInterface.DetectLocalIPAddressFromNetworkInterfaceAsync(AddressFamily.InterNetwork); + Log.Debug($"{nameof(DetectLocalIPAddressAsync)} - Local {addressFamily} address detection via routing failed, trying network interfaces..."); + detected = await NetworkInterface.DetectLocalIPAddressFromNetworkInterfaceAsync(addressFamily); } Log.Debug(detected != null - ? $"{nameof(DetectLocalIPv4Async)} - Local IPv4 address detected: " + detected - : $"{nameof(DetectLocalIPv4Async)} - Local IPv4 address not detected."); + ? $"{nameof(DetectLocalIPAddressAsync)} - Local {addressFamily} address detected: {detected} (routed: {isRouted})" + : $"{nameof(DetectLocalIPAddressAsync)} - Local {addressFamily} address not detected."); - return detected; + return (detected, isRouted); } /// - /// Detects the local IPv6 address, based on routing to the configured public IPv6 address, with - /// a fallback to detection based on the network interfaces. + /// Detects the gateway of the local IP address and pings it, see . /// - private static async Task DetectLocalIPv6Async() + /// Item of the router check (IPv4 or IPv6). + /// Local IP address, or null (IPv4 only, IPv6 is not checked without one). + /// The local IP address was detected via the route to the public IP address. + /// The gateway, or null if none was found. + private static async Task CheckGatewayAsync(ConnectionCheckItem item, IPAddress localIPAddress, + bool isRouted) { - Log.Debug($"{nameof(DetectLocalIPv6Async)} - Detecting local IPv6 address..."); - - IPAddress remoteIPv6 = null; - - try - { - remoteIPv6 = IPAddress.Parse(SettingsManager.Current.Dashboard_PublicIPv6Address); - } - catch (Exception ex) + // No local IP address (shown as error on the computer): no gateway to detect + if (localIPAddress == null) { - Log.Warn($"{nameof(DetectLocalIPv6Async)} - Invalid Dashboard_PublicIPv6Address setting, skipping routing based detection.", ex); + item.Complete("-/-", new ConnectionCheckResult(ConnectionState.Info, ConnectionCheckReason.NoIPv4Address)); + return null; } - var detected = remoteIPv6 != null - ? await NetworkInterface.DetectLocalIPAddressBasedOnRoutingAsync(remoteIPv6) - : null; + var gateway = await NetworkInterface.DetectGatewayFromLocalIPAddressAsync(localIPAddress); - if (detected == null) + var isReachable = false; + + if (gateway != null) { - Log.Debug($"{nameof(DetectLocalIPv6Async)} - Local IPv6 address detection via routing failed, trying network interfaces..."); - detected = await NetworkInterface.DetectLocalIPAddressFromNetworkInterfaceAsync(AddressFamily.InterNetworkV6); + var pingInfo = await PingProbe.PingAsync(gateway, GlobalStaticConfiguration.Dashboard_PingTimeout, + GlobalStaticConfiguration.Dashboard_PingAttempts, PingBuffer, CancellationToken.None); + + isReachable = pingInfo.Status == IPStatus.Success; + + Log.Debug($"{nameof(CheckGatewayAsync)} - Ping {gateway}: {pingInfo.Status}"); } - Log.Debug(detected != null - ? $"{nameof(DetectLocalIPv6Async)} - Local IPv6 address detected: " + detected - : $"{nameof(DetectLocalIPv6Async)} - Local IPv6 address not detected."); + item.Complete(gateway?.ToString() ?? "-/-", + NetworkConnectionCheck.GetGatewayResult(gateway, isRouted, isReachable)); - return detected; + return gateway; } /// - /// Applies a detected address to a , unless a newer check has - /// started in the meantime. + /// Marks an IPv6 check as not available (the computer has no routed IPv6 address). /// - private void SetAddressResult(ConnectionCheckItem item, IPAddress detected, long generation) + private static void SetIPv6NotAvailable(ConnectionCheckItem item) { - if (generation != _generation) - return; - - item.Complete(detected?.ToString() ?? "-/-", detected != null ? ConnectionState.OK : ConnectionState.Critical); + item.Complete("-/-", new ConnectionCheckResult(ConnectionState.Info, ConnectionCheckReason.IPv6NotAvailable)); } /// - /// Resolves the DNS (PTR) name for an address item, trying IPv4 first and falling back to IPv6, - /// unless a newer check has started in the meantime. + /// Resolves the DNS (PTR) name of the IPv4 address, and of the IPv6 address if needed (see + /// / ). /// - /// - /// A PTR lookup that completes without a server error but simply has no record (e.g. most home - /// routers and many ISPs don't configure reverse DNS) is reported as - /// rather than - it's not a sign of a broken DNS setup. - /// - private async Task ResolveDnsAsync(ConnectionCheckItem dnsItem, ConnectionCheckItem addressIPv4, ConnectionCheckItem addressIPv6, long generation, string context) + private static async Task ResolveDnsAsync(ConnectionCheckItem dnsItem, IPAddress ipv4Address, IPAddress ipv6Address, + string context) { DNSClientResultString ipv4Result = null; DNSClientResultString ipv6Result = null; - if (addressIPv4.State == ConnectionState.OK) + if (ipv4Address != null) { Log.Debug($"{context} > {nameof(ResolveDnsAsync)} - Resolving DNS based on IPv4..."); - ipv4Result = await DNSClient.GetInstance().ResolvePtrAsync(IPAddress.Parse(addressIPv4.Value)); + ipv4Result = await DNSClient.GetInstance().ResolvePtrAsync(ipv4Address); } - if (ipv4Result is not { HasError: false } && addressIPv6.State == ConnectionState.OK) + if (ipv6Address != null && NetworkConnectionCheck.ShouldResolveIPv6(ipv4Result)) { Log.Debug($"{context} > {nameof(ResolveDnsAsync)} - Resolving DNS based on IPv6..."); - ipv6Result = await DNSClient.GetInstance().ResolvePtrAsync(IPAddress.Parse(addressIPv6.Value)); + ipv6Result = await DNSClient.GetInstance().ResolvePtrAsync(ipv6Address); } - if (generation != _generation) - return; + var (result, hostname) = NetworkConnectionCheck.GetDNSResult(ipv4Result, ipv6Result); - // Prefer a successful resolution from either family. If neither succeeded, a clean - // "not found" from either family still wins over a hard failure from the other - e.g. - // IPv4 has no PTR (NXDOMAIN) while IPv6 times out should show as "no record", not as a - // broken DNS setup. - var resolved = ipv4Result is { HasError: false } ? ipv4Result : ipv6Result is { HasError: false } ? ipv6Result : null; - var notFound = ipv4Result is { IsNotFound: true } || ipv6Result is { IsNotFound: true }; + Log.Debug($"{context} > {nameof(ResolveDnsAsync)} - {result.State} ({result.Reason}): {hostname}. IPv4: {ipv4Result?.ErrorMessage ?? "n/a"} | IPv6: {ipv6Result?.ErrorMessage ?? "n/a"}"); - if (resolved != null) - { - Log.Debug($"{context} > {nameof(ResolveDnsAsync)} - DNS resolved: " + resolved.Value); - dnsItem.Complete(resolved.Value, ConnectionState.OK); - } - else if (notFound) - { - Log.Debug($"{context} > {nameof(ResolveDnsAsync)} - DNS not resolved (no record found)."); - dnsItem.Complete("-/-", ConnectionState.Info); - } - else - { - Log.Debug($"{context} > {nameof(ResolveDnsAsync)} - DNS not resolved due to error. IPv4: {ipv4Result?.ErrorMessage ?? "n/a"} | IPv6: {ipv6Result?.ErrorMessage ?? "n/a"}"); - dnsItem.Complete("-/-", ConnectionState.Critical); - } + dnsItem.Complete(hostname ?? "-/-", result); } /// /// Resolves the computer's DNS (PTR) name. /// - private Task CheckConnectionComputerDnsAsync(CancellationToken ct, long generation) + /// The local IPv4 address, or null. + /// The local IPv6 address, or null (also if IPv6 is not available). + private Task CheckConnectionComputerDnsAsync(IPAddress localIPv4, IPAddress localIPv6) { return Task.Run(async () => { Log.Debug($"{nameof(CheckConnectionComputerDnsAsync)} - Checking computer DNS..."); - await ResolveDnsAsync(ComputerDNS, ComputerIPv4, ComputerIPv6, generation, nameof(CheckConnectionComputerDnsAsync)); + await ResolveDnsAsync(ComputerDNS, localIPv4, localIPv6, nameof(CheckConnectionComputerDnsAsync)); Log.Debug($"{nameof(CheckConnectionComputerDnsAsync)} - Computer DNS check completed."); - }, ct); + }); } /// - /// Checks the router connection asynchronously. + /// Checks the router connection asynchronously: detects the IPv4 / IPv6 gateway, pings both at the same time, then + /// resolves the DNS name. /// /// The already-detected local IPv4 address, or null. - /// The already-detected local IPv6 address, or null. - /// The cancellation token. - /// The id of this check run, see . + /// The local IPv4 address was detected via the route to the public IP address. + /// The already-detected local IPv6 address, or null if IPv6 is not available. /// A task representing the asynchronous operation. - private Task CheckConnectionRouterAsync(IPAddress localIPv4, IPAddress localIPv6, CancellationToken ct, long generation) + private Task CheckConnectionRouterAsync(IPAddress localIPv4, bool isIPv4Routed, IPAddress localIPv6) { return Task.Run(async () => { Log.Debug($"{nameof(CheckConnectionRouterAsync)} - Checking router connection..."); - // Detect router IPv4 gateway - Log.Debug($"{nameof(CheckConnectionRouterAsync)} - Detecting router IPv4 address..."); + var routerIPv4Task = CheckGatewayAsync(RouterIPv4, localIPv4, isIPv4Routed); + var routerIPv6Task = Task.FromResult(null); - var routerIPv4 = localIPv4 != null - ? await NetworkInterface.DetectGatewayFromLocalIPAddressAsync(localIPv4) - : null; + if (localIPv6 != null) + routerIPv6Task = CheckGatewayAsync(RouterIPv6, localIPv6, true); + else + SetIPv6NotAvailable(RouterIPv6); - SetAddressResult(RouterIPv4, routerIPv4, generation); + await Task.WhenAll(routerIPv4Task, routerIPv6Task); - if (ct.IsCancellationRequested) - ct.ThrowIfCancellationRequested(); + // Resolve router DNS + await ResolveDnsAsync(RouterDNS, routerIPv4Task.Result, routerIPv6Task.Result, + nameof(CheckConnectionRouterAsync)); + + Log.Debug($"{nameof(CheckConnectionRouterAsync)} - Router connection check completed."); + }); + } + + /// + /// Requests the public IP address from the API (setting), see . + /// + /// IPv4 or IPv6. + /// Result of the request. + private static async Task RequestPublicIPAddressAsync(AddressFamily addressFamily) + { + var api = addressFamily == AddressFamily.InterNetwork + ? SettingsManager.Current.Dashboard_UseCustomPublicIPv4AddressAPI + ? SettingsManager.Current.Dashboard_CustomPublicIPv4AddressAPI + : GlobalStaticConfiguration.Dashboard_PublicIPv4AddressAPI + : SettingsManager.Current.Dashboard_UseCustomPublicIPv6AddressAPI + ? SettingsManager.Current.Dashboard_CustomPublicIPv6AddressAPI + : GlobalStaticConfiguration.Dashboard_PublicIPv6AddressAPI; - // Detect router IPv6 gateway - Log.Debug($"{nameof(CheckConnectionRouterAsync)} - Detecting router IPv6 address..."); + try + { + Log.Debug($"{nameof(RequestPublicIPAddressAsync)} - Checking public {addressFamily} address from: {api}"); - var routerIPv6 = localIPv6 != null - ? await NetworkInterface.DetectGatewayFromLocalIPAddressAsync(localIPv6) - : null; + using var httpResponse = await PublicIPHttpClient.GetAsync(api); + var content = await httpResponse.Content.ReadAsStringAsync(); - SetAddressResult(RouterIPv6, routerIPv6, generation); + var result = PublicIPAddressCheck.ParseResponse(httpResponse.IsSuccessStatusCode, content, addressFamily); - if (ct.IsCancellationRequested) - ct.ThrowIfCancellationRequested(); + Log.Debug($"{nameof(RequestPublicIPAddressAsync)} - HTTP {(int)httpResponse.StatusCode}: {result.Status} {result.IPAddress}"); - // Resolve router DNS - await ResolveDnsAsync(RouterDNS, RouterIPv4, RouterIPv6, generation, nameof(CheckConnectionRouterAsync)); + return result; + } + catch (Exception ex) + { + var result = PublicIPAddressCheck.FromException(ex); - Log.Debug($"{nameof(CheckConnectionRouterAsync)} - Router connection check completed."); - }, ct); + Log.Debug($"{nameof(RequestPublicIPAddressAsync)} - {result.Status}: {ex.Message}"); + + return result; + } } /// - /// Checks the internet connection asynchronously. + /// Pings the public IP address (setting) to check if the internet is reachable. /// - /// The cancellation token. - /// The id of this check run, see . - /// A task representing the asynchronous operation. - private Task CheckConnectionInternetAsync(CancellationToken ct, long generation) + /// Public IPv4 or IPv6 address (setting). + /// IPv4 or IPv6. + /// Result of the ping, or null if the address in the settings is invalid. + private static async Task PingPublicIPAddressAsync(string ipAddress, AddressFamily addressFamily) { - return Task.Run(async () => + if (!IPAddress.TryParse(ipAddress, out var target) || target.AddressFamily != addressFamily) { - // If public IP address check is disabled - if (!CheckPublicIPAddressEnabled) - return; + Log.Warn($"{nameof(PingPublicIPAddressAsync)} - Invalid public {addressFamily} address \"{ipAddress}\" in the settings, skipping the ping."); + return null; + } - Log.Debug($"{nameof(CheckConnectionInternetAsync)} - Checking internet connection..."); + var pingInfo = await PingProbe.PingAsync(target, GlobalStaticConfiguration.Dashboard_PingTimeout, + GlobalStaticConfiguration.Dashboard_PingAttempts, PingBuffer, CancellationToken.None); - // Detect public IPv4 and if it is reachable - Log.Debug($"{nameof(CheckConnectionInternetAsync)} - Detecting public IPv4 address..."); + Log.Debug($"{nameof(PingPublicIPAddressAsync)} - Ping {target}: {pingInfo.Status}"); - var publicIPv4AddressAPI = SettingsManager.Current.Dashboard_UseCustomPublicIPv4AddressAPI - ? SettingsManager.Current.Dashboard_CustomPublicIPv4AddressAPI - : GlobalStaticConfiguration.Dashboard_PublicIPv4AddressAPI; + return pingInfo; + } - try - { - Log.Debug($"{nameof(CheckConnectionInternetAsync)} - Checking public IPv4 address from: " + publicIPv4AddressAPI); + /// + /// Checks the internet connection of an address family: ping of the public IP address (setting) and the public IP + /// address API (if enabled) at the same time, see . + /// + /// Item of the internet check (IPv4 or IPv6). + /// IPv4 or IPv6. + /// Internet connectivity reported by Windows (read once per check). + /// The public IP address returned by the API, or null (also if the API returned a private one, e.g. + /// a captive portal - its DNS name is not the one of the internet connection). + private static async Task CheckInternetAsync(ConnectionCheckItem item, AddressFamily addressFamily, + Task connectivityLevelTask) + { + var pingTask = PingPublicIPAddressAsync(addressFamily == AddressFamily.InterNetwork + ? SettingsManager.Current.Dashboard_PublicIPv4Address + : SettingsManager.Current.Dashboard_PublicIPv6Address, addressFamily); - var httpResponse = await PublicIPHttpClient.GetAsync(publicIPv4AddressAPI, ct); - var result = await httpResponse.Content.ReadAsStringAsync(ct); - var match = RegexHelper.IPv4AddressExtractRegex().Match(result); + var publicIPAddressTask = SettingsManager.Current.Dashboard_CheckPublicIPAddress + ? RequestPublicIPAddressAsync(addressFamily) + : Task.FromResult(null); - if (generation != _generation) - return; + await Task.WhenAll(pingTask, publicIPAddressTask, connectivityLevelTask); - if (match.Success) - { - Log.Debug($"{nameof(CheckConnectionInternetAsync)} - Public IPv4 address detected: " + match.Value); - InternetIPv4.Complete(match.Value, ConnectionState.OK); - } - else - { - Log.Debug($"{nameof(CheckConnectionInternetAsync)} - Public IPv4 address not detected due to invalid format."); - InternetIPv4.Complete("-/-", ConnectionState.Critical); - } - } - catch (Exception ex) when (ex is not OperationCanceledException) - { - Log.Debug($"{nameof(CheckConnectionInternetAsync)} - Public IPv4 address not detected due to exception: " + ex.Message); + var pingInfo = pingTask.Result; + var publicIPAddress = publicIPAddressTask.Result; + var isPingSuccessful = pingInfo is { Status: IPStatus.Success }; - if (generation == _generation) - InternetIPv4.Complete("-/-", ConnectionState.Critical); - } + // Public IP address (API), otherwise the pinged address with the round-trip time + var value = publicIPAddress?.IPAddress?.ToString() ?? + (isPingSuccessful ? $"{pingInfo.IPAddress} ({pingInfo.Time} ms)" : "-/-"); - if (ct.IsCancellationRequested) - ct.ThrowIfCancellationRequested(); + // Only the public IP address is opened in other tools (e.g. RDAP, IP geolocation): not a private one (e.g. a + // captive portal) and not the pinged address (e.g. 1.1.1.1, it is not the IP address of the user) + var publicIP = publicIPAddress is { Status: PublicIPAddressCheckStatus.Success } ? publicIPAddress.IPAddress : null; - // Detect public IPv6 and if it is reachable - Log.Debug($"{nameof(CheckConnectionInternetAsync)} - Detecting public IPv6 address..."); + item.Complete(value, NetworkConnectionCheck.GetInternetResult(addressFamily, isPingSuccessful, + publicIPAddress, connectivityLevelTask.Result), publicIP?.ToString() ?? string.Empty); - var publicIPv6AddressAPI = SettingsManager.Current.Dashboard_UseCustomPublicIPv6AddressAPI - ? SettingsManager.Current.Dashboard_CustomPublicIPv6AddressAPI - : GlobalStaticConfiguration.Dashboard_PublicIPv6AddressAPI; + return publicIP; + } - try - { - Log.Debug($"{nameof(CheckConnectionInternetAsync)} - Checking public IPv6 address from: " + publicIPv6AddressAPI); + /// + /// Checks the internet connection asynchronously. + /// + /// The computer has a routed IPv6 address (otherwise IPv6 is not checked). + /// A task representing the asynchronous operation. + private Task CheckConnectionInternetAsync(bool isIPv6Available) + { + return Task.Run(async () => + { + Log.Debug($"{nameof(CheckConnectionInternetAsync)} - Checking internet connection..."); - var httpResponse = await PublicIPHttpClient.GetAsync(publicIPv6AddressAPI, ct); - var result = await httpResponse.Content.ReadAsStringAsync(ct); - var match = Regex.Match(result, RegexHelper.IPv6AddressRegex); + var connectivityLevelTask = Task.Run(InternetConnectivity.GetLevel); - if (generation != _generation) - return; + var publicIPv4Task = CheckInternetAsync(InternetIPv4, AddressFamily.InterNetwork, connectivityLevelTask); + var publicIPv6Task = Task.FromResult(null); - if (match.Success) - { - Log.Debug($"{nameof(CheckConnectionInternetAsync)} - Public IPv6 address detected: " + match.Value); - InternetIPv6.Complete(match.Value, ConnectionState.OK); - } - else - { - Log.Debug($"{nameof(CheckConnectionInternetAsync)} - Public IPv6 address not detected due to invalid format."); - InternetIPv6.Complete("-/-", ConnectionState.Critical); - } - } - catch (Exception ex) when (ex is not OperationCanceledException) - { - Log.Debug($"{nameof(CheckConnectionInternetAsync)} - Public IPv6 address not detected due to exception: " + ex.Message); + // Only if the computer has a routed IPv6 address + if (isIPv6Available) + publicIPv6Task = CheckInternetAsync(InternetIPv6, AddressFamily.InterNetworkV6, connectivityLevelTask); + else + SetIPv6NotAvailable(InternetIPv6); - if (generation == _generation) - InternetIPv6.Complete("-/-", ConnectionState.Critical); - } + await Task.WhenAll(publicIPv4Task, publicIPv6Task); - if (ct.IsCancellationRequested) - ct.ThrowIfCancellationRequested(); + Log.Debug($"{nameof(CheckConnectionInternetAsync)} - Windows reports: {connectivityLevelTask.Result}"); - // Resolve internet DNS - await ResolveDnsAsync(InternetDNS, InternetIPv4, InternetIPv6, generation, nameof(CheckConnectionInternetAsync)); + // Resolve internet DNS (of the public IP address) + if (SettingsManager.Current.Dashboard_CheckPublicIPAddress) + await ResolveDnsAsync(InternetDNS, publicIPv4Task.Result, publicIPv6Task.Result, + nameof(CheckConnectionInternetAsync)); + else + InternetDNS.Complete("-/-", new ConnectionCheckResult(ConnectionState.Info, + ConnectionCheckReason.PublicIPAddressCheckDisabled)); Log.Debug($"{nameof(CheckConnectionInternetAsync)} - Internet connection check completed."); - }, ct); + }); } #endregion diff --git a/Source/NETworkManager/Views/DashboardSettingsView.xaml b/Source/NETworkManager/Views/DashboardSettingsView.xaml index 467652114d..bde05ddeb6 100644 --- a/Source/NETworkManager/Views/DashboardSettingsView.xaml +++ b/Source/NETworkManager/Views/DashboardSettingsView.xaml @@ -156,7 +156,7 @@ - + + + + + + \ No newline at end of file diff --git a/Source/NETworkManager/Views/DashboardView.xaml b/Source/NETworkManager/Views/DashboardView.xaml index b4d0f0a276..02b35e8d64 100644 --- a/Source/NETworkManager/Views/DashboardView.xaml +++ b/Source/NETworkManager/Views/DashboardView.xaml @@ -5,37 +5,37 @@ xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:viewModels="clr-namespace:NETworkManager.ViewModels" + xmlns:icons="clr-namespace:NETworkManager.Controls;assembly=NETworkManager.Controls" mc:Ignorable="d" d:DataContext="{d:DesignInstance viewModels:DashboardViewModel}"> - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Source/NETworkManager/Views/DashboardView.xaml.cs b/Source/NETworkManager/Views/DashboardView.xaml.cs index 60a7f1611f..f14d2c0129 100644 --- a/Source/NETworkManager/Views/DashboardView.xaml.cs +++ b/Source/NETworkManager/Views/DashboardView.xaml.cs @@ -1,4 +1,11 @@ -using NETworkManager.ViewModels; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Windows; +using System.Windows.Controls; +using NETworkManager.Settings; +using NETworkManager.ViewModels; namespace NETworkManager.Views; @@ -6,37 +13,186 @@ public partial class DashboardView { private readonly DashboardViewModel _viewModel = new(); - private readonly NetworkConnectionWidgetView _networkConnectionWidgetView = new(); - private readonly IPApiIPGeolocationWidgetView _ipApiIPGeolocationWidgetView = new(); - private readonly IPApiDNSResolverWidgetView _ipApiDNSResolverWidgetView = new(); - private readonly SpeedTestWidgetView _speedTestWidgetView = new(); + // Widgets are created when they are shown the first time (e.g. a hidden IP API widget sends no request) + private NetworkConnectionWidgetView _networkConnectionWidgetView; + private IPApiIPGeolocationWidgetView _ipApiIPGeolocationWidgetView; + private IPApiDNSResolverWidgetView _ipApiDNSResolverWidgetView; + private SpeedTestWidgetView _speedTestWidgetView; + /// + /// The dashboard is the selected application (see / ). + /// + private bool _isViewVisible = true; + + /// + /// The network or a setting of the network connection check changed while the dashboard was hidden: check again + /// when it is shown. + /// + private bool _isOutdated; + + /// + /// Start of the last network connection check, see . + /// + private DateTime _lastCheck; public DashboardView() { InitializeComponent(); DataContext = _viewModel; - // Load views - ContentControlNetworkConnection.Content = _networkConnectionWidgetView; - ContentControlIPApiIPGeolocation.Content = _ipApiIPGeolocationWidgetView; - ContentControlIPApiDNSResolver.Content = _ipApiDNSResolverWidgetView; - ContentControlSpeedTest.Content = _speedTestWidgetView; + // Show the widgets + ApplyWidgetSettings(); + + // The settings are changed while the dashboard is hidden (settings view) - check again when it is shown + SettingsManager.Current.PropertyChanged += SettingsManager_PropertyChanged; // Check network connection on first open. Later re-opens are covered by OnViewVisible(). - _networkConnectionWidgetView.Check(); + CheckNetworkConnection(); } public void OnViewVisible() { + _isViewVisible = true; + _viewModel.OnViewVisible(); - // Check network connection - _networkConnectionWidgetView.Check(); + // The widgets may have been shown or hidden in the settings + ApplyWidgetSettings(); + + CheckNetworkConnectionIfOutdated(); + } + + /// + /// Called by the main window when it is shown again (from the tray or minimized). + /// + public void OnMainWindowShown() + { + if (_isViewVisible) + CheckNetworkConnectionIfOutdated(); } public void OnViewHide() { + _isViewVisible = false; + _viewModel.OnViewHide(); } -} + + /// + /// Called by the main window when the network has changed (addresses, adapter connected or disconnected). + /// + /// The main window is shown (not in the tray or minimized). Otherwise the check runs + /// when the window is shown again (the status window checks the network connection meanwhile). + public void OnNetworkChanged(bool isMainWindowShown) + { + if (_isViewVisible && isMainWindowShown) + CheckNetworkConnection(); + else + _isOutdated = true; + } + + /// + /// Checks the network connection again if something changed, or if the last check is older than the recheck + /// interval (e.g. the public IP address may have changed) - not on every switch between the applications. + /// + private void CheckNetworkConnectionIfOutdated() + { + if (_isOutdated || DateTime.Now - _lastCheck >= GlobalStaticConfiguration.Dashboard_RecheckInterval) + CheckNetworkConnection(); + } + + private void CheckNetworkConnection() + { + // Hidden or not created yet: checked when it is shown (a changed setting marks the data as outdated, the widget + // is created in OnViewVisible) + if (!SettingsManager.Current.Dashboard_ShowNetworkConnectionWidget || _networkConnectionWidgetView == null) + return; + + _isOutdated = false; + _lastCheck = DateTime.Now; + + _networkConnectionWidgetView.Check(); + } + + /// + /// Shows / hides the widgets (settings Dashboard_Show*Widget) and creates them when they are shown the + /// first time. + /// + private void ApplyWidgetSettings() + { + var settings = SettingsManager.Current; + + _networkConnectionWidgetView = ShowWidget(ContentControlNetworkConnection, + settings.Dashboard_ShowNetworkConnectionWidget, _networkConnectionWidgetView); + _speedTestWidgetView = ShowWidget(ContentControlSpeedTest, settings.Dashboard_ShowSpeedTestWidget, + _speedTestWidgetView); + _ipApiIPGeolocationWidgetView = ShowWidget(ContentControlIPApiIPGeolocation, + settings.Dashboard_ShowIPGeolocationWidget, _ipApiIPGeolocationWidgetView); + _ipApiDNSResolverWidgetView = ShowWidget(ContentControlIPApiDNSResolver, + settings.Dashboard_ShowDNSResolverWidget, _ipApiDNSResolverWidgetView); + + // IP geolocation (2/3) and DNS resolver (1/3) in one row, the remaining one spans the row + var showIPGeolocation = settings.Dashboard_ShowIPGeolocationWidget; + var showDNSResolver = settings.Dashboard_ShowDNSResolverWidget; + + GridIPApi.Visibility = showIPGeolocation || showDNSResolver ? Visibility.Visible : Visibility.Collapsed; + + Grid.SetColumnSpan(ContentControlIPApiIPGeolocation, showDNSResolver ? 3 : 5); + Grid.SetColumn(ContentControlIPApiDNSResolver, showIPGeolocation ? 4 : 0); + Grid.SetColumnSpan(ContentControlIPApiDNSResolver, showIPGeolocation ? 1 : 5); + + // Gap of 10 between the visible widgets (not below the last one, the scroll viewer has a margin of 10) + var visibleWidgets = new FrameworkElement[] + { ContentControlNetworkConnection, ContentControlSpeedTest, GridIPApi } + .Where(x => x.Visibility == Visibility.Visible) + .ToList(); + + for (var i = 0; i < visibleWidgets.Count; i++) + visibleWidgets[i].Margin = new Thickness(0, 0, 0, i < visibleWidgets.Count - 1 ? 10 : 0); + + EmptyStateMessageNoWidgets.Visibility = visibleWidgets.Count == 0 ? Visibility.Visible : Visibility.Collapsed; + } + + /// + /// Shows or hides a widget. The view of the widget is created when it is shown the first time. + /// + /// Content control of the widget. + /// Show the widget. + /// View of the widget, null if not created yet. + /// Type of the view. + /// View of the widget, null if it was never shown. + private static T ShowWidget(ContentControl contentControl, bool show, T view) where T : UserControl, new() + { + contentControl.Visibility = show ? Visibility.Visible : Visibility.Collapsed; + + if (!show || view != null) + return view; + + view = new T(); + contentControl.Content = view; + + return view; + } + + /// + /// Settings used by the network connection check: a change marks it as outdated (checked when the dashboard is + /// shown again). Other dashboard settings (e.g. the other widgets) keep the recheck interval. + /// + private static readonly HashSet NetworkConnectionSettings = + [ + nameof(SettingsInfo.Dashboard_PublicIPv4Address), + nameof(SettingsInfo.Dashboard_PublicIPv6Address), + nameof(SettingsInfo.Dashboard_CheckPublicIPAddress), + nameof(SettingsInfo.Dashboard_UseCustomPublicIPv4AddressAPI), + nameof(SettingsInfo.Dashboard_CustomPublicIPv4AddressAPI), + nameof(SettingsInfo.Dashboard_UseCustomPublicIPv6AddressAPI), + nameof(SettingsInfo.Dashboard_CustomPublicIPv6AddressAPI), + nameof(SettingsInfo.Dashboard_ShowNetworkConnectionWidget) + ]; + + private void SettingsManager_PropertyChanged(object sender, PropertyChangedEventArgs e) + { + if (e.PropertyName != null && NetworkConnectionSettings.Contains(e.PropertyName)) + _isOutdated = true; + } +} \ No newline at end of file diff --git a/Source/NETworkManager/Views/NetworkConnectionWidgetView.xaml b/Source/NETworkManager/Views/NetworkConnectionWidgetView.xaml index 433800a607..935f0071e2 100644 --- a/Source/NETworkManager/Views/NetworkConnectionWidgetView.xaml +++ b/Source/NETworkManager/Views/NetworkConnectionWidgetView.xaml @@ -8,6 +8,8 @@ xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:viewModels="clr-namespace:NETworkManager.ViewModels" + xmlns:internalControls="clr-namespace:NETworkManager.Controls" + xmlns:models="clr-namespace:NETworkManager.Models;assembly=NETworkManager.Models" xmlns:wpfHelpers="clr-namespace:NETworkManager.Utilities.WPF;assembly=NETworkManager.Utilities.WPF" mc:Ignorable="d" d:DataContext="{d:DesignInstance viewModels:NetworkConnectionWidgetViewModel}"> @@ -18,6 +20,158 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -31,160 +185,101 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + diff --git a/Website/docs/application/dashboard.md b/Website/docs/application/dashboard.md index 919e59143f..acf4f598d8 100644 --- a/Website/docs/application/dashboard.md +++ b/Website/docs/application/dashboard.md @@ -6,19 +6,32 @@ keywords: [NETworkManager, dashboard, network status, network connection, networ # Dashboard -The **Dashboard** shows the status of your computer's current network connection to provide a quick overview of the most important information. Whenever the local network adapter changes state (e.g. an Ethernet cable is plugged in, Wi-Fi or VPN connects), the dashboard checks connectivity to the router and the internet. +The **Dashboard** shows the status of your computer's current network connection to provide a quick overview of the most important information. Whenever the local network adapter changes state (e.g. an Ethernet cable is plugged in, Wi-Fi or VPN connects), the dashboard checks connectivity to the router and the internet. When you switch back to the dashboard (or show the window again from the tray / taskbar), the network connection is only checked again if the last check is at least 60 seconds old (e.g. the public IP address may have changed) or the network or a setting of the network connection (e.g. the public IP address) has changed in the meantime, so switching between the tools doesn't send a request each time. **F5** or the refresh button always checks again. ![Dashboard](../img/dashboard.png) +## Network connection + +The **Network connection** widget (also shown in the status window) checks the connection of the computer, the gateway / router and the internet, each for IPv4, IPv6 and DNS. The gateway is pinged (2 attempts with a timeout of 2 seconds, like the IP Scanner). The internet is checked with a ping of the [Public IPv4 address](#public-ipv4-address) / [Public IPv6 address](#public-ipv6-address), the public IP address from [`api.ipify.org`](https://www.ipify.org/) (if [Check public IP address](#check-public-ip-address) is enabled) and the internet connectivity reported by Windows (detects a hotspot / captive portal that requires a sign-in). The value is the public IP address, or the pinged address with the round-trip time if the public IP address is not requested. The icon in front of each value shows the result, hover over it to see the reason. **DNS** is the DNS name (PTR record) of the IPv4 address, or of the IPv6 address if the IPv4 address has none: + +| Icon | Meaning | +|------|---------| +| Green | OK | +| Yellow | Works partly or may not work, e.g. the computer has only a link-local IPv4 address (`169.254.x.x`, no address from a DHCP server) or no route to the internet (the address of the first active network adapter is shown), the gateway did not reply to the ping (it may block ICMP), the network adapter has no gateway (e.g. a VPN connection), the public IP address API returned a private IP address (e.g. the page of a hotspot / captive portal or a proxy), Windows reports a hotspot / captive portal (IPv4, unless the public IP address API returned a public IP address), the ping works but the public IP address API doesn't, or the ping and the API fail but Windows reports internet access (e.g. both are blocked by a firewall or only reachable via a proxy) | +| Red | Failed, e.g. the computer has no IPv4 address, the DNS server did not answer, or the internet is not reachable | +| Gray | Information, e.g. no IPv6 connection: the network or the internet provider may not support IPv6 (the IPv6 checks of the router and the internet are skipped), or no DNS name (PTR record) for the IP address, which many networks don't have | + +Right-click a value to open it in another tool: an IP address in the **Port Scanner**, **Ping Monitor**, **Traceroute** or **DNS Lookup**, the gateway / router also in the **Web Console** (e.g. its web interface, not for a link-local IPv6 address like `fe80::1%12`), the public IP address also in **RDAP** and **IP Geolocation**, and a DNS name in the **DNS Lookup**. **Copy** copies the value. The **Copy all** button next to the refresh button copies all values with the reasons of the states as text (e.g. for a support request). + ### Keyboard shortcuts | Key | Action | |-----|--------| -| `F5` | Refresh the dashboard | +| `F5` | Check the network connection again | :::note -You may need to click into a widget first before keyboard shortcuts are recognized. +`F5` only works while the **Network connection** widget has the focus (e.g. click into it first). The other widgets are refreshed with their refresh button. ::: @@ -30,7 +43,7 @@ Open the tool with `dashboard`. The command accepts no target and no profile, se ### Public IPv4 address -Public IPv4 address reachable via ICMP. +Public IPv4 address that is pinged to check the internet connection. The route to this address is used to detect the local IPv4 address (no packet is sent for this), so it should be routed via the network adapter that is used for the internet. **Type:** `String` @@ -38,7 +51,7 @@ Public IPv4 address reachable via ICMP. ### Public IPv6 address -Public IPv6 address reachable via ICMP. +Public IPv6 address that is pinged to check the internet connection. The route to this address is used to detect the local IPv6 address (no packet is sent for this), so it should be routed via the network adapter that is used for the internet. **Type:** `String` @@ -46,7 +59,7 @@ Public IPv6 address reachable via ICMP. ### Check public IP address -Enables or disables the resolution of the public IP address via [`api.ipify.org`](https://www.ipify.org/) and [`api6.ipify.org`](https://www.ipify.org/). +Enables or disables the resolution of the public IP address via [`api.ipify.org`](https://www.ipify.org/) and [`api6.ipify.org`](https://www.ipify.org/). If disabled, the internet is only checked with the ping of the [Public IPv4 address](#public-ipv4-address) / [Public IPv6 address](#public-ipv6-address) and the connectivity reported by Windows. **Type:** `Boolean` @@ -54,7 +67,7 @@ Enables or disables the resolution of the public IP address via [`api.ipify.org` ### Use custom IPv4 address API -Override the default IPv4 address API to resolve the public IP address. The API should return only a plain text IPv4 address like `xx.xx.xx.xx`. +Override the default IPv4 address API to resolve the public IP address. The API should return only a plain text IPv4 address like `xx.xx.xx.xx`, or a JSON object with the address as a string value like `{"ip":"xx.xx.xx.xx"}`. Other answers (e.g. an HTML page) are not accepted. **Type:** `Boolean | String` @@ -62,13 +75,20 @@ Override the default IPv4 address API to resolve the public IP address. The API **Example:** -- [`api.ipify.org`](https://api.ipify.org/) -- [`ip4.seeip.org`](https://ip4.seeip.org/) -- [`api.my-ip.io/ip`](https://api.my-ip.io/ip) +| API | Answer | +|-----|--------| +| [`https://api.ipify.org`](https://api.ipify.org/) | Plain text | +| [`https://api.ipify.org?format=json`](https://api.ipify.org?format=json) | JSON `{"ip":"xx.xx.xx.xx"}` | +| [`https://checkip.amazonaws.com`](https://checkip.amazonaws.com/) | Plain text | +| [`https://ifconfig.co/ip`](https://ifconfig.co/ip) | Plain text | +| [`https://ipinfo.io/ip`](https://ipinfo.io/ip) | Plain text | +| [`http://ip-api.com/line/?fields=query`](http://ip-api.com/line/?fields=query) | Plain text (`http` only, 45 requests per minute, non-commercial use only) | + +Many APIs also return JSON with more information (e.g. `https://ipinfo.io/json`, `https://ifconfig.co/json`, `http://ip-api.com/json`), the first string value that is an IP address is used. An API that returns `key=value` lines (e.g. `https://1.1.1.1/cdn-cgi/trace`) is not supported. ### Use custom IPv6 address API -Override the default IPv6 address API to resolve the public IP address. The API should return only a plain text IPv6 address like `xxxx:xx:xxx::xx`. +Override the default IPv6 address API to resolve the public IP address. The API should return only a plain text IPv6 address like `xxxx:xx:xxx::xx`, or a JSON object with the address as a string value like `{"ip":"xxxx:xx:xxx::xx"}`. Other answers (e.g. an HTML page) are not accepted. **Type:** `Boolean | String` @@ -76,7 +96,10 @@ Override the default IPv6 address API to resolve the public IP address. The API **Example:** -- [`api6.ipify.org`](https://api6.ipify.org/) +| API | Answer | +|-----|--------| +| [`https://api6.ipify.org`](https://api6.ipify.org/) | Plain text | +| [`https://api64.ipify.org?format=json`](https://api64.ipify.org?format=json) | JSON `{"ip":"xxxx:xx:xxx::xx"}` (IPv6 if available, otherwise IPv4 - then the answer is not accepted) | ### Check IP geolocation @@ -90,7 +113,7 @@ The free API endpoint is limited to 45 requests per minute, supports only the `h **Type:** `Boolean` -**Default:** `Enabled` +**Default:** `Disabled` ### Check DNS resolver @@ -98,7 +121,15 @@ Enables or disables the detection of the DNS resolver in use via [`ip-api.com`]( **Type:** `Boolean` -**Default:** `Enabled` +**Default:** `Disabled` + +### Widgets + +Show or hide the widgets on the dashboard: **Network connection**, **Speed Test**, **IP geolocation** and **DNS resolver**. A hidden widget doesn't check anything (e.g. no request is sent to `ip-api.com`); a speed test that is already running when the widget is hidden is completed. If one of IP geolocation and DNS resolver is hidden, the other one uses the whole width. The status window always shows the network connection. + +**Type:** `Boolean` + +**Default:** `Enabled` (all widgets) ## Speed Test @@ -118,6 +149,6 @@ Before running the test, a privacy disclaimer informs the user that `speed.cloud ## Troubleshooting and limits - The local IP address is detected by the route to the [Public IPv4 address](#public-ipv4-address) / [Public IPv6 address](#public-ipv6-address) (no packet is sent), otherwise from the first active network interface. With several network adapters (e.g. LAN and VPN), set an address that is routed via the adapter you want to see. -- The internet is shown as reachable if the public IP address could be requested from `api.ipify.org` / `api6.ipify.org` (or the [custom API](#use-custom-ipv4-address-api)). A proxy or firewall that blocks the API shows the internet as not reachable although websites may work; disable [Check public IP address](#check-public-ip-address) or use another API. The IP geolocation and the DNS resolver are requested from `ip-api.com` (45 requests per minute). -- Without IPv6 connectivity (or no IPv6 from the internet provider), the IPv6 checks fail, the IPv4 checks are not affected. +- The internet is shown as reachable if the [Public IPv4 address](#public-ipv4-address) / [Public IPv6 address](#public-ipv6-address) replies to the ping or the public IP address could be requested from `api.ipify.org` / `api6.ipify.org` (or the [custom API](#use-custom-ipv4-address-api)). If both are blocked (e.g. by a firewall, or websites are only reachable via a proxy), the internet is shown as a warning if Windows reports internet access (IPv4), otherwise as not reachable; use another public IP address / API. The IP geolocation and the DNS resolver are requested from `ip-api.com` (45 requests per minute). +- Without IPv6 connectivity (or no IPv6 from the internet provider), the IPv6 checks are shown as information (gray) and skipped, the IPv4 checks are not affected. - The [Speed Test](#speed-test) measures the connection to the nearest Cloudflare server. A VPN, a proxy or other traffic on the network at the same time lowers the result. diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index f05bc2902a..16649903eb 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -19,6 +19,10 @@ Release date: **xx.xx.2026** ## Breaking Changes +**Dashboard** + +- A custom public IP address API (**Settings > Dashboard**) must return the IP address as plain text or in a JSON object (e.g. `{"ip":"xx.xx.xx.xx"}`). An address inside other text or an HTML page (e.g. `checkip.dyndns.org`) is no longer used, because the page of a hotspot / captive portal could be shown as the public IP address. See the [examples](../application/dashboard.md#use-custom-ipv4-address-api). [#3734](https://github.com/BornToBeRoot/NETworkManager/pull/3734) + ## What's new? **Network Interface** @@ -29,6 +33,10 @@ Release date: **xx.xx.2026** - Added a dedicated browser for services advertised on the local network, including printers, scanners, web servers and media devices. Select an interface and service types or service type profiles (e.g. Printers, editable in the settings, with history) or discover all types, inspect hostnames, ports, IPv4 / IPv6 addresses and TXT records, filter, copy and export the results. **Raw DNS records** shows the individual DNS records instead, with each TXT entry on its own row; other and unknown record types are preserved as raw data. Includes the `mdns` / `dnssd` run commands (e.g. `mdns printers 30`) with suggestions of the service type profiles and durations. Thanks to [@MovGP0](https://github.com/MovGP0) [#3719](https://github.com/BornToBeRoot/NETworkManager/pull/3719) +**Dashboard** + +- The widgets of the dashboard (Network connection, Speed Test, IP geolocation, DNS resolver) can be hidden in the settings (**Settings > Dashboard > Widgets**). A hidden widget doesn't check anything (a running speed test is completed). [#3734](https://github.com/BornToBeRoot/NETworkManager/pull/3734) + ## Improvements **Network Interface** @@ -49,6 +57,27 @@ Release date: **xx.xx.2026** - Renamed "Discovery Protocol" to "LLDP / CDP Capture", so it is clear what the tool does (and it is not confused with mDNS Discovery). The run command is now `lldpcdpcapture` with the aliases `lldp` and `cdp`, the documentation moved to [LLDP / CDP Capture](../application/lldp-cdp-capture.md). The selected protocol and duration are reset to the defaults. [#3721](https://github.com/BornToBeRoot/NETworkManager/issues/3721) +**Dashboard** + +- Switching back to the dashboard checks the network connection only if the last check is at least 60 seconds old (or the network / a setting of the network connection changed), instead of on every switch between the tools. **F5** and the refresh button always check. [#3734](https://github.com/BornToBeRoot/NETworkManager/pull/3734) +- The network connection check is faster (also at startup and in the status window): the local IP address and the gateway are read directly from the network adapters instead of querying all adapter details incl. PowerShell up to four times per check. This also speeds up the detection of the local IP address in the **IP Scanner** when no route is available. [#3734](https://github.com/BornToBeRoot/NETworkManager/pull/3734) +- The network connection shows a warning instead of OK if the computer has only a link-local IPv4 address (`169.254.x.x`, no address from a DHCP server) or no route to the internet. Without an IPv6 connection (e.g. the internet provider doesn't support IPv6), the IPv6 values are shown as information (gray) instead of failed (red), and the IPv6 address of the router and the internet are not checked. Hover over an icon to see the reason. [#3734](https://github.com/BornToBeRoot/NETworkManager/pull/3734) +- The DNS name (PTR) of the IPv6 address is no longer requested after the DNS server failed for the IPv4 address (the same server would time out again), so the network connection check finishes faster without a working DNS server. Without an IP address to resolve, the DNS value is shown as information instead of failed. [#3734](https://github.com/BornToBeRoot/NETworkManager/pull/3734) +- The gateway / router is now pinged (2 attempts, 2 seconds timeout) instead of only checking that a gateway is configured. No reply is shown as a warning (some routers block ICMP). A network adapter without a gateway (e.g. a VPN connection) is shown as a warning instead of failed if the internet is routed via it. [#3734](https://github.com/BornToBeRoot/NETworkManager/pull/3734) +- The internet is now checked with a ping of the public IPv4 / IPv6 address (settings, `1.1.1.1` / `2606:4700:4700::1111`), the public IP address API and the internet connectivity reported by Windows. A hotspot / captive portal that requires a sign-in, a blocked public IP address API (e.g. a proxy) or blocked ICMP are shown as a warning instead of the internet being not reachable. With **Check public IP address** disabled, the internet is still checked (ping and Windows) instead of showing "Check is disabled!". [#3734](https://github.com/BornToBeRoot/NETworkManager/pull/3734) +- The values of the network connection (dashboard and status window) can be opened in other tools via the context menu: Port Scanner, Ping Monitor, Traceroute and DNS Lookup, the gateway / router also in the Web Console, the public IP address also in RDAP and IP Geolocation. **Copy** copies the whole value. Opening a tool from the status window shows the main window. [#3734](https://github.com/BornToBeRoot/NETworkManager/pull/3734) +- A value of the network connection that is cut off in a narrow window (e.g. a long IPv6 address or DNS name) is shown completely in the tooltip. [#3734](https://github.com/BornToBeRoot/NETworkManager/pull/3734) +- The network connection shows the time of the last check ("Reloaded at ...") next to the refresh button, like other tools. [#3734](https://github.com/BornToBeRoot/NETworkManager/pull/3734) +- New **Copy all** button in the network connection: copies all values with the reasons of the states as text, e.g. for a support request. [#3734](https://github.com/BornToBeRoot/NETworkManager/pull/3734) + +**Status window** + +- The countdown of the status window moves smoothly (like the progress of the IP Scanner) instead of in small steps, and the window no longer grows and moves right after it was opened on a network change. [#3734](https://github.com/BornToBeRoot/NETworkManager/pull/3734) + +**Notifications** + +- The countdown of the notifications (e.g. Ping Monitor, IP Scanner) moves smoothly, like the progress of the IP Scanner, instead of in small steps. [#3734](https://github.com/BornToBeRoot/NETworkManager/pull/3734) + ## Bug Fixes **Tabs** @@ -121,6 +150,23 @@ Release date: **xx.xx.2026** - Fixed the license of ControlzEx in the library list: it showed the license text and link of Dragablz. [#3717](https://github.com/BornToBeRoot/NETworkManager/pull/3717) - Updated the license of MahApps.Metro in the library list (copyright: .NET Foundation and Contributors). [#3717](https://github.com/BornToBeRoot/NETworkManager/pull/3717) +**Dashboard** + +- Fixed the network connection check getting stuck (all values loading until the next refresh) when it was started several times while a check was running (e.g. the refresh and a network change). The refresh is disabled while a check runs, a network change during a check repeats the check once it has finished. [#3734](https://github.com/BornToBeRoot/NETworkManager/pull/3734) +- Fixed the network connection widget (dashboard and status window) not updating when **Check public IP address** was changed in the settings until the application was restarted: an old public IP address could be shown as current. [#3734](https://github.com/BornToBeRoot/NETworkManager/pull/3734) +- Fixed the network connection not being checked again when the network changed while the dashboard was open (e.g. a cable unplugged or a VPN connected), although the documentation says so. If the dashboard is not open (or the window is in the tray / minimized, the status window checks meanwhile), it is checked when it is shown again. [#3734](https://github.com/BornToBeRoot/NETworkManager/pull/3734) +- Fixed the gateway / router not being found (shown as failed although the internet works) for VPN connections whose adapter is not an Ethernet or Wi-Fi adapter (e.g. the Windows VPN client with IKEv2 / SSTP). A VPN adapter without a gateway is no longer shown with the gateway `0.0.0.0`. [#3734](https://github.com/BornToBeRoot/NETworkManager/pull/3734) +- Fixed an IP address on an error page or the page of a hotspot / captive portal (e.g. hotel Wi-Fi) being shown as the public IP address. The answer of the API must have a success status code, a private IP address is shown as a warning, and an API name that can't be resolved points to the DNS server. The public IPv4 and IPv6 addresses are requested at the same time. [#3734](https://github.com/BornToBeRoot/NETworkManager/pull/3734) +- Fixed custom public IPv6 address APIs that answer with a JSON object (e.g. `{"ip":"2001:db8::1"}`) not being recognized. A custom API may answer with the IP address as plain text or in a JSON object; other answers (e.g. the HTML page of a captive portal) are no longer searched for an IP address. [#3734](https://github.com/BornToBeRoot/NETworkManager/pull/3734) + +**Status window** + +- The status window now opens after a network change once the network has settled (5 seconds without further changes, e.g. after the DHCP address was assigned, at most 20 seconds after the first change) instead of 5 seconds after the first change, so it no longer shows an intermediate state. An error while updating the DNS configuration after a network change no longer stops the detection of further network changes. [#3734](https://github.com/BornToBeRoot/NETworkManager/pull/3734) +- The status window that opens on a network change no longer takes the keyboard focus from the application you are working in. Clicking into it keeps it open (the countdown stops). [#3734](https://github.com/BornToBeRoot/NETworkManager/pull/3734) +- Fixed the status window being hidden right after it was opened from the tray icon when the countdown of a previous network change had just ended. [#3734](https://github.com/BornToBeRoot/NETworkManager/pull/3734) +- Fixed the status window being cut off on the left on small screens (e.g. 1280 x 720 with 150 % scaling). It is no longer wider than the screen. [#3734](https://github.com/BornToBeRoot/NETworkManager/pull/3734) +- Fixed the status window opened by the user (e.g. from the tray icon) closing itself after a network change. It stays open and checks the network connection again. [#3734](https://github.com/BornToBeRoot/NETworkManager/pull/3734) + ## Dependencies, Refactoring & Documentation - Code cleanup & refactoring diff --git a/Website/docs/settings/status.md b/Website/docs/settings/status.md index 019dbae397..86015ee9d6 100644 --- a/Website/docs/settings/status.md +++ b/Website/docs/settings/status.md @@ -8,7 +8,7 @@ keywords: [NETworkManager, status settings, status window, network change notifi ### Show status window on network change -Show the status window when the network changes (e.g. Ethernet cable is plugged in, WLAN or VPN is connected, etc.). +Show the status window when the network changes (e.g. Ethernet cable is plugged in, WLAN or VPN is connected, etc.). The window opens once the network has settled (5 seconds without further changes, e.g. after the DHCP address was assigned, at most 20 seconds after the first change) and checks the network connection, see [Dashboard](../application/dashboard.md#network-connection). It doesn't take the keyboard focus; click into it to keep it open. **Type:** `Boolean`