Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,9 @@ website changes also need `Build Website`), Transifex (`transifex.yml`: syncs th
- **Generated lists** (OUI, ports, WHOIS servers, public suffixes, world map, Lucide icons) are updated with the scripts
in `Scripts/`, not by hand.
- **Tests**: xUnit in `Source/NETworkManager.Tests/<Area>/<Class>Tests.cs`. Put testable logic (parsing, mapping,
decisions) in small public static methods in `NETworkManager.Models` (no `InternalsVisibleTo`). UI, system APIs and
network behaviour are tested manually on Windows.
decisions) in small public static methods in `NETworkManager.Models` (no `InternalsVisibleTo`); helpers that
`NETworkManager.Controls` uses go to `NETworkManager.Utilities` (Models references Controls), e.g. `InputConverter`.
UI, system APIs and network behaviour are tested manually on Windows.
- **Plans and reviews**: local, not committed: `.claude/plans/` and `.claude/reviews/` (e.g. `ping-monitor.md`). Read the
file of the area first - it records verified findings, decisions and open items.

Expand Down
99 changes: 0 additions & 99 deletions Source/NETworkManager.Controls/ComboBoxPasteBehavior.cs

This file was deleted.

101 changes: 101 additions & 0 deletions Source/NETworkManager.Controls/PasteBehavior.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using NETworkManager.Utilities;

namespace NETworkManager.Controls;

/// <summary>
/// Attached properties that convert text pasted (or dropped) into a TextBox or an editable ComboBox:
/// <list type="bullet">
/// <item>
/// <see cref="ConvertMultilineToSemicolonProperty" />: multiline text (e.g. a column pasted from Excel)
/// becomes a semicolon-separated single line. Without this the single-line TextBox
/// (<see cref="TextBox.AcceptsReturn" /> is <c>false</c>) drops everything after the first line.
/// </item>
/// <item>
/// <see cref="ConvertUrlsToHostsProperty" />: a URL (e.g. "https://borntoberoot.net/docs", copied from a
/// browser) becomes its host, see <see cref="InputConverter.ConvertUrlsToHosts" />.
/// </item>
/// </list>
/// The data of the paste is replaced in <see cref="DataObject.PastingEvent" /> and the default paste inserts it, so
/// undo, read-only inputs and drag &amp; drop work as usual and the system clipboard is never modified.
/// </summary>
public static class PasteBehavior
{
public static readonly DependencyProperty ConvertMultilineToSemicolonProperty =
DependencyProperty.RegisterAttached(
"ConvertMultilineToSemicolon",
typeof(bool),
typeof(PasteBehavior),
new PropertyMetadata(false, OnChanged));

public static void SetConvertMultilineToSemicolon(UIElement element, bool value) =>
element.SetValue(ConvertMultilineToSemicolonProperty, value);

public static bool GetConvertMultilineToSemicolon(UIElement element) =>
(bool)element.GetValue(ConvertMultilineToSemicolonProperty);

public static readonly DependencyProperty ConvertUrlsToHostsProperty =
DependencyProperty.RegisterAttached(
"ConvertUrlsToHosts",
typeof(bool),
typeof(PasteBehavior),
new PropertyMetadata(false, OnChanged));

public static void SetConvertUrlsToHosts(UIElement element, bool value) =>
element.SetValue(ConvertUrlsToHostsProperty, value);

public static bool GetConvertUrlsToHosts(UIElement element) =>
(bool)element.GetValue(ConvertUrlsToHostsProperty);

private static void OnChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// The pasting event bubbles from the editable text box inside the ComboBox template.
if (d is not (ComboBox or TextBox))
return;

// Added once, also if both properties are set.
DataObject.RemovePastingHandler(d, OnPasting);

if (GetConvertMultilineToSemicolon((UIElement)d) || GetConvertUrlsToHosts((UIElement)d))
DataObject.AddPastingHandler(d, OnPasting);
}

private static void OnPasting(object sender, DataObjectPastingEventArgs e)
{
if (sender is not UIElement element)
return;

string text;

try
{
text = e.SourceDataObject.GetData(DataFormats.UnicodeText, true) as string;
}
catch (ExternalException)
{
// Clipboard is locked by another process or its data can't be read (COMException) - default paste.
return;
}

if (text == null)
return;

var converted = text;

// URLs first, line by line (a ";" in a URL belongs to the URL, a line break ends it).
if (GetConvertUrlsToHosts(element))
converted = InputConverter.ConvertUrlsToHosts(converted);

if (GetConvertMultilineToSemicolon(element))
converted = InputConverter.ConvertMultilineToSemicolon(converted);

if (converted == text)
return;

// The default paste inserts the converted text instead.
e.DataObject = new DataObject(DataFormats.UnicodeText, converted);
e.FormatToApply = DataFormats.UnicodeText;
}
}
57 changes: 37 additions & 20 deletions Source/NETworkManager.Models/Network/Whois.cs
Original file line number Diff line number Diff line change
@@ -1,38 +1,26 @@
using System.IO;
using System;
using System.IO;
using System.Net;
using System.Linq;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using NETworkManager.Models.RDAP;
using NETworkManager.Utilities;

namespace NETworkManager.Models.Network;

public static class Whois
{
#region Constructor

static Whois()
{
var document = new XmlDocument();
document.Load(WhoisServerFilePath);

var whoisServerList = (from XmlNode node in document.SelectNodes("/WhoisServers/WhoisServer")!
where node != null
select new WhoisServerInfo(node.SelectSingleNode("Server")?.InnerText,
node.SelectSingleNode("TLD")?.InnerText)).ToList();

WhoisServers = (Lookup<string, WhoisServerInfo>)whoisServerList.ToLookup(x => x.Tld);
}

#endregion

#region Variables

private static readonly string WhoisServerFilePath =
Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location)!, "Resources", "WhoisServers.xml");

private static readonly Lookup<string, WhoisServerInfo> WhoisServers;
// Loaded on first use, so the methods without the list (e.g. GetQueryDomain) can be used without the file.
private static readonly Lazy<ILookup<string, WhoisServerInfo>> WhoisServers = new(LoadWhoisServers);

#endregion

Expand Down Expand Up @@ -71,7 +59,36 @@ public static string GetWhoisServer(string domain)
var domainParts = domain.TrimEnd('.').Split('.');

// TLD to upper because the lookup is case sensitive
return WhoisServers[domainParts[^1].ToUpper()].FirstOrDefault()?.Server;
return WhoisServers.Value[domainParts[^1].ToUpper()].FirstOrDefault()?.Server;
}

/// <summary>
/// Gets the domain to query: a subdomain (e.g. "www.borntoberoot.net", the host of a pasted URL) is queried as
/// its registered domain ("borntoberoot.net"), like in RDAP, since Whois servers only know registered domains.
/// </summary>
/// <param name="domain">Domain (e.g. "www.bbc.co.uk").</param>
/// <returns>Registered domain in lowercase (e.g. "bbc.co.uk"), or the domain if it is a public suffix itself.</returns>
public static string GetQueryDomain(string domain)
{
var name = domain.Trim().TrimEnd('.').ToLowerInvariant();

// An IP address (e.g. the inherited host of a profile) is not a domain. Only complete addresses - IPAddress.TryParse
// also accepts short forms like "1.2" or "10".
if (RegexHelper.IPv4AddressRegex().IsMatch(name) || name.Contains(':') && IPAddress.TryParse(name, out _))
return name;

return PublicSuffixList.GetRegisteredDomain(name) ?? name;
}

private static ILookup<string, WhoisServerInfo> LoadWhoisServers()
{
var document = new XmlDocument();
document.Load(WhoisServerFilePath);

return (from XmlNode node in document.SelectNodes("/WhoisServers/WhoisServer")!
where node != null
select new WhoisServerInfo(node.SelectSingleNode("Server")?.InnerText,
node.SelectSingleNode("TLD")?.InnerText)).ToLookup(x => x.Tld);
}

#endregion
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,12 @@ public sealed class RunCommandDefinition
/// </summary>
public bool SupportsTarget { get; init; }

/// <summary>
/// The target is a host (or a list / range of hosts): a URL is converted to its host (e.g. "trace
/// https://borntoberoot.net/docs" traces "borntoberoot.net"), like a URL pasted into the host input.
/// </summary>
public bool TargetIsHost { get; init; }

/// <summary>
/// The command accepts a profile ("@name") instead of a target.
/// </summary>
Expand Down
3 changes: 2 additions & 1 deletion Source/NETworkManager.Models/RunCommand/RunCommandParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using NETworkManager.Utilities;

namespace NETworkManager.Models.RunCommand;

Expand Down Expand Up @@ -203,7 +204,7 @@ public static RunCommandParseResult Parse(string input, IEnumerable<RunCommandDe
{
Command = command,
CommandText = commandText,
Target = words[1],
Target = command.TargetIsHost ? InputConverter.ConvertUrlsToHosts(words[1]) : words[1],
Argument = argument,
Type = type,
Position = isTypingTarget ? RunCommandPosition.Target : RunCommandPosition.Argument,
Expand Down
26 changes: 26 additions & 0 deletions Source/NETworkManager.Tests/Network/WhoisTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using NETworkManager.Models.Network;
using Xunit;

namespace NETworkManager.Tests.Network;

public class WhoisTests
{
[Theory]
[InlineData("borntoberoot.net", "borntoberoot.net")]
[InlineData("www.borntoberoot.net", "borntoberoot.net")]
[InlineData("a.b.borntoberoot.net", "borntoberoot.net")]
[InlineData("www.bbc.co.uk", "bbc.co.uk")]
[InlineData(" WWW.BornToBeRoot.net. ", "borntoberoot.net")]
// A public suffix itself is queried as it is.
[InlineData("co.uk", "co.uk")]
// An IP address is not a domain.
[InlineData("10.0.0.1", "10.0.0.1")]
[InlineData("2001:db8::1", "2001:db8::1")]
// Short numeric forms are not treated as IP addresses (IPAddress.TryParse accepts them).
[InlineData("1.2", "1.2")]
[InlineData("www.1.2", "1.2")]
public void GetQueryDomain(string domain, string expected)
{
Assert.Equal(expected, Whois.GetQueryDomain(domain));
}
}
17 changes: 16 additions & 1 deletion Source/NETworkManager.Tests/RunCommand/RunCommandParserTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public class RunCommandParserTests
new()
{
Type = RunCommandType.Application, Application = ApplicationName.DNSLookup, Command = "dnslookup",
Aliases = ["dns", "nslookup"], SupportsTarget = true, SupportsProfile = true,
Aliases = ["dns", "nslookup"], SupportsTarget = true, TargetIsHost = true, SupportsProfile = true,
Argument = RunCommandArgument.DNSServer, Types = ["a", "aaaa", "cname", "ptr"],
SyntaxParts =
[
Expand Down Expand Up @@ -562,4 +562,19 @@ public void CurrentSyntaxPart(string input, RunCommandSyntaxPartKind? part)
{
Assert.Equal(part, Parse(input).CurrentSyntaxPart);
}

[Theory]
[InlineData("dns https://borntoberoot.net/docs", "borntoberoot.net")]
[InlineData("dns https://borntoberoot.net;10.0.0.1 aaaa", "borntoberoot.net;10.0.0.1")]
// A ";" in the path of a URL belongs to the URL.
[InlineData("dns https://borntoberoot.net/cart;jsessionid=1", "borntoberoot.net")]
// What follows a URL with a path belongs to it (a link is one entry).
[InlineData("dns https://borntoberoot.net/docs;10.0.0.1", "borntoberoot.net")]
[InlineData("dns borntoberoot.net", "borntoberoot.net")]
// Not a host command: the URL is kept (validated by the application).
[InlineData("subnet https://borntoberoot.net", "https://borntoberoot.net")]
public void UrlTargetOfHostCommand(string input, string target)
{
Assert.Equal(target, Parse(input).Target);
}
}
Loading