Skip to content
Open
Show file tree
Hide file tree
Changes from 3 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
24 changes: 24 additions & 0 deletions src/Neo.Extensions/Xml/XmlNodeExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Copyright (C) 2015-2025 The Neo Project.
//
// XmlNodeExtensions.cs file belongs to the neo project and is free
// software distributed under the MIT software license, see the
// accompanying file LICENSE in the main directory of the
// repository or http://www.opensource.org/licenses/mit-license.php
// for more details.
//
// Redistribution and use in source and binary forms with or without
// modifications are permitted.

using System.Xml;

namespace Neo.Extensions.Xml
{
public static class XmlNodeExtensions
{
public static string GetXmlElementText(this XmlNode node, string elementName)
{
var element = node[elementName];
return element != null ? element.InnerText : string.Empty;
}
}
}
40 changes: 40 additions & 0 deletions src/Neo/Network/Messages/DiscoveryResponseMessage.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// Copyright (C) 2015-2025 The Neo Project.
//
// DiscoveryResponseMessage.cs file belongs to the neo project and is free
// software distributed under the MIT software license, see the
// accompanying file LICENSE in the main directory of the
// repository or http://www.opensource.org/licenses/mit-license.php
// for more details.
//
// Redistribution and use in source and binary forms with or without
// modifications are permitted.

using System;
using System.Collections.Generic;
using System.Linq;

namespace Neo.Network.Messages
{
internal class DiscoveryResponseMessage
{
private readonly IDictionary<string, string> _headers;

public DiscoveryResponseMessage(string message)
{
var lines = message.Split(["\r\n"], StringSplitOptions.RemoveEmptyEntries);
var headers = from h in lines.Skip(1)
let c = h.Split(':')
let key = c[0]
let value = c.Length > 1
? string.Join(":", c.Skip(1).ToArray())
: string.Empty
select new { Key = key, Value = value.Trim() };
_headers = headers.ToDictionary(x => x.Key.ToUpperInvariant(), x => x.Value);
}

public string this[string key]
{
get { return _headers[key.ToUpperInvariant()]; }
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// Copyright (C) 2015-2025 The Neo Project.
//
// CreatePortMappingRequestMessage.cs file belongs to the neo project and is free
// software distributed under the MIT software license, see the
// accompanying file LICENSE in the main directory of the
// repository or http://www.opensource.org/licenses/mit-license.php
// for more details.
//
// Redistribution and use in source and binary forms with or without
// modifications are permitted.

using System.Collections.Generic;

namespace Neo.Network.Messages.Requests
{
internal class CreatePortMappingRequestMessage : RequestMessage
{
private readonly string _remoteHost;
private readonly string _publicPort;
private readonly string _privatePort;
private readonly string _privateIp;
private readonly string _description;

public CreatePortMappingRequestMessage(
string remoteHost,
string publicPort,
string privatePort,
string privateIp,
string description)
{
_remoteHost = remoteHost;
_publicPort = publicPort;
_privatePort = privatePort;
_privateIp = privateIp;
_description = description;
}

public override Dictionary<string, object> ToXml() =>
new()
{
{"NewRemoteHost", _remoteHost},
{"NewExternalPort", _publicPort},
{"NewProtocol", "TCP"},
{"NewInternalPort", _privatePort},
{"NewInternalClient", _privateIp},
{"NewEnabled", 1},
{"NewPortMappingDescription", _description},
{"NewLeaseDuration", 0},
};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Copyright (C) 2015-2025 The Neo Project.
//
// DeletePortMappingRequestMessage.cs file belongs to the neo project and is free
// software distributed under the MIT software license, see the
// accompanying file LICENSE in the main directory of the
// repository or http://www.opensource.org/licenses/mit-license.php
// for more details.
//
// Redistribution and use in source and binary forms with or without
// modifications are permitted.

using System.Collections.Generic;

namespace Neo.Network.Messages.Requests
{
internal class DeletePortMappingRequestMessage : RequestMessage
{
private readonly string _publicPort;

public DeletePortMappingRequestMessage(
string publicPort)
{
_publicPort = publicPort;
}

public override Dictionary<string, object> ToXml() =>
new()
{
{"NewRemoteHost", string.Empty},
{"NewExternalPort", _publicPort},
{"NewProtocol", "TCP"},
};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Copyright (C) 2015-2025 The Neo Project.
//
// GetExternalIPAddressRequestMessage.cs file belongs to the neo project and is free
// software distributed under the MIT software license, see the
// accompanying file LICENSE in the main directory of the
// repository or http://www.opensource.org/licenses/mit-license.php
// for more details.
//
// Redistribution and use in source and binary forms with or without
// modifications are permitted.

using System.Collections.Generic;

namespace Neo.Network.Messages.Requests
{
internal class GetExternalIPAddressRequestMessage : RequestMessage
{
public override Dictionary<string, object> ToXml() =>
[];
}
}
23 changes: 23 additions & 0 deletions src/Neo/Network/Messages/Requests/RequestMessage.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Copyright (C) 2015-2025 The Neo Project.
//
// RequestMessage.cs file belongs to the neo project and is free
// software distributed under the MIT software license, see the
// accompanying file LICENSE in the main directory of the
// repository or http://www.opensource.org/licenses/mit-license.php
// for more details.
//
// Redistribution and use in source and binary forms with or without
// modifications are permitted.

using System.Collections.Generic;

namespace Neo.Network.Messages.Requests
{
internal abstract class RequestMessage
{
public const string GetExternalIpAddressActionName = "GetExternalIpAddress";
public const string AddPortMappingActionName = "AddPortMapping";

public abstract IDictionary<string, object> ToXml();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Copyright (C) 2015-2025 The Neo Project.
//
// GetExternalIPAddressResponseMessage.cs file belongs to the neo project and is free
// software distributed under the MIT software license, see the
// accompanying file LICENSE in the main directory of the
// repository or http://www.opensource.org/licenses/mit-license.php
// for more details.
//
// Redistribution and use in source and binary forms with or without
// modifications are permitted.

using Neo.Extensions.Xml;
using System.Net;
using System.Xml;

namespace Neo.Network.Messages.Responses
{
internal class GetExternalIPAddressResponseMessage : ResponseMessage
{
public IPAddress ExternalIPAddress { get; private set; }

public GetExternalIPAddressResponseMessage(XmlDocument response, string serviceType)
: base(response, serviceType, nameof(GetExternalIPAddressResponseMessage))
{
var ip = GetNode().GetXmlElementText("NewExternalIPAddress");

if (IPAddress.TryParse(ip, out var ipAddress))
ExternalIPAddress = ipAddress;
}
}
}
43 changes: 43 additions & 0 deletions src/Neo/Network/Messages/Responses/ResponseMessage.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// Copyright (C) 2015-2025 The Neo Project.
//
// ResponseMessage.cs file belongs to the neo project and is free
// software distributed under the MIT software license, see the
// accompanying file LICENSE in the main directory of the
// repository or http://www.opensource.org/licenses/mit-license.php
// for more details.
//
// Redistribution and use in source and binary forms with or without
// modifications are permitted.

using System;
using System.Xml;

namespace Neo.Network.Messages.Responses
{
internal abstract class ResponseMessage
{
private readonly XmlDocument _document;
protected string _serviceType;
private readonly string _typeName;

protected ResponseMessage(XmlDocument response, string serviceType, string typeName)
{
_document = response;
_serviceType = serviceType;
_typeName = typeName;
}

protected XmlNode GetNode()
{
var nsm = new XmlNamespaceManager(_document.NameTable);
nsm.AddNamespace("responseNs", _serviceType);

var typeName = _typeName;
var messageName = typeName.Substring(0, typeName.Length - "Message".Length);
var node = _document.SelectSingleNode("//responseNs:" + messageName, nsm) ??
throw new InvalidOperationException("The response is invalid: " + messageName);

return node;
}
}
}
41 changes: 17 additions & 24 deletions src/Neo/Network/P2P/Peer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,15 @@
using Akka.Actor;
using Akka.IO;
using Neo.Extensions;
using Neo.Extensions.Factories;
using Neo.Network.Messages.Requests;
using Neo.Network.Messages.Responses;
using System;
using System.Buffers.Binary;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;

namespace Neo.Network.P2P
{
Expand Down Expand Up @@ -167,17 +166,6 @@ protected void ConnectToPeer(IPEndPoint endPoint, bool isTrusted = false)
});
}

private static bool IsIntranetAddress(IPAddress address)
{
byte[] data = address.MapToIPv4().GetAddressBytes();
uint value = BinaryPrimitives.ReadUInt32BigEndian(data);
return (value & 0xff000000) == 0x0a000000 ||
(value & 0xff000000) == 0x7f000000 ||
(value & 0xfff00000) == 0xac100000 ||
(value & 0xffff0000) == 0xc0a80000 ||
(value & 0xffff0000) == 0xa9fe0000;
}

/// <summary>
/// Called for asking for more peers.
/// </summary>
Expand Down Expand Up @@ -222,20 +210,25 @@ private void OnStart(ChannelsConfig config)

// schedule time to trigger `OnTimer` event every TimerMillisecondsInterval ms
_timer = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(0, 5000, Context.Self, new Timer(), ActorRefs.NoSender);
if ((ListenerTcpPort > 0)
&& s_localAddresses.All(p => !p.IsIPv4MappedToIPv6 || IsIntranetAddress(p))
&& UPnP.Discover())
if (ListenerTcpPort > 0)
{
try
// Opens port on all NAT devices
var natDevices = UPnP.Search();

foreach (var (_, device) in natDevices)
{
s_localAddresses.Add(UPnP.GetExternalIP());
var soapClient = new SoapClient(device.ServiceControlUri, device.ServiceType);
var externalIpMessage = new GetExternalIPAddressRequestMessage();
var responseData = soapClient.Invoke(RequestMessage.GetExternalIpAddressActionName, externalIpMessage.ToXml());

if (ListenerTcpPort > 0) UPnP.ForwardPort(ListenerTcpPort, ProtocolType.Tcp, "NEO Tcp");
var response = new GetExternalIPAddressResponseMessage(responseData, device.ServiceType);
var publicIp = response.ExternalIPAddress.Equals(IPAddress.None) ? string.Empty : $"{response.ExternalIPAddress}";
var port = $"{ListenerTcpPort}";
var portMessage = new CreatePortMappingRequestMessage(publicIp, port, port, $"{device.LocalAddress}", "NEO Tcp");

_ = soapClient.Invoke(RequestMessage.AddPortMappingActionName, portMessage.ToXml());
}
catch { }
}
if (ListenerTcpPort > 0)
{

s_tcpManager.Tell(new Tcp.Bind(Self, config.Tcp, options: [new Inet.SO.ReuseAddress(true)]));
}
}
Expand Down
Loading
Loading