Improve port parsing
MODIFY
WalletWasabi.Tests/ParserTests.cs
WalletWasabi.Tests/ParserTests.cs
@@ -82,8 +82,11 @@ namespace WalletWasabi.Tests
// Default port is used.
foreach (var inputString in inputsWithoutPorts)
{
- var success = EndPointParser.TryParse(inputString, 5000, out EndPoint ep);
- AssertEndPointParserOutputs(success, ep, host, 5000);
+ foreach (var defaultPort in validPorts)
+ {
+ var success = EndPointParser.TryParse(inputString, defaultPort, out EndPoint ep);
+ AssertEndPointParserOutputs(success, ep, host, defaultPort);
+ }
}
// Default port is not used.
@@ -99,12 +102,12 @@ namespace WalletWasabi.Tests
Assert.False(EndPointParser.TryParse(inputString, -1, out EndPoint ep));
}
- // Defaultport corrects invalid inputs.
+ // Defaultport doesn't correct invalid port input.
foreach (var inputString in inputsWithInvalidPorts)
{
foreach (var defaultPort in validPorts)
{
- Assert.True(EndPointParser.TryParse(inputString, defaultPort, out EndPoint ep));
+ Assert.False(EndPointParser.TryParse(inputString, defaultPort, out EndPoint ep));
}
}

MODIFY
WalletWasabi/Helpers/EndPointParser.cs
WalletWasabi/Helpers/EndPointParser.cs
@@ -53,7 +53,7 @@ namespace System.Net
endPointString = endPointString.TrimEnd(':', '/');
var parts = endPointString.Split(':', StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim().TrimEnd('/').TrimEnd()).ToArray();
- var isDefaultPortInvalid = !ushort.TryParse(defaultPort.ToString(), out _);
+ var isDefaultPortInvalid = !ushort.TryParse(defaultPort.ToString(), out ushort dp) || dp < IPEndPoint.MinPort || dp > IPEndPoint.MaxPort;
int port;
if (parts.Length == 0)
{
@@ -73,21 +73,14 @@ namespace System.Net
else if (parts.Length == 2)
{
var portString = parts[1];
- if (ushort.TryParse(portString, out ushort p))
+ if (ushort.TryParse(portString, out ushort p) && p >= IPEndPoint.MinPort && p <= IPEndPoint.MaxPort)
{
port = p;
}
else
- {
- if (isDefaultPortInvalid)
{
return false;
}
- else
- {
- port = defaultPort;
- }
- }
}
else
{
@@ -100,34 +93,14 @@ namespace System.Net
host = IPAddress.Loopback.ToString();
}
- bool isPortInvalid = port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort || !ushort.TryParse(port.ToString(), out _);
- if (isPortInvalid)
- {
- if (isDefaultPortInvalid)
- {
- return false;
- }
- else
- {
- port = defaultPort;
- }
- }
-
if (IPAddress.TryParse(host, out IPAddress addr))
{
endPoint = new IPEndPoint(addr, port);
}
else
- {
- try
{
endPoint = new DnsEndPoint(host, port);
}
- catch
- {
- return false;
- }
- }
return true;
}

Improve port parsing