2020-04-08 15:40:41 +02:00
|
|
|
using System.Net;
|
2019-03-17 16:03:02 +01:00
|
|
|
using System.Net.Sockets;
|
|
|
|
using System.Threading;
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
using BTCPayServer.Configuration;
|
2019-04-05 09:19:04 +02:00
|
|
|
using NBitcoin.Protocol;
|
2020-06-28 10:55:27 +02:00
|
|
|
using NBitcoin.Protocol.Connectors;
|
2019-03-17 16:03:02 +01:00
|
|
|
|
|
|
|
namespace BTCPayServer.Services
|
|
|
|
{
|
|
|
|
public class SocketFactory
|
|
|
|
{
|
|
|
|
private readonly BTCPayServerOptions _options;
|
2020-03-13 15:10:26 +01:00
|
|
|
|
2019-03-17 16:03:02 +01:00
|
|
|
public SocketFactory(BTCPayServerOptions options)
|
|
|
|
{
|
|
|
|
_options = options;
|
|
|
|
}
|
2020-03-13 15:10:26 +01:00
|
|
|
|
2019-03-31 06:16:05 +02:00
|
|
|
public async Task<Socket> ConnectAsync(EndPoint endPoint, CancellationToken cancellationToken)
|
2019-03-17 16:03:02 +01:00
|
|
|
{
|
2019-04-05 09:19:04 +02:00
|
|
|
DefaultEndpointConnector connector = new DefaultEndpointConnector();
|
|
|
|
NodeConnectionParameters connectionParameters = new NodeConnectionParameters();
|
|
|
|
if (_options.SocksEndpoint != null)
|
2019-03-17 16:03:02 +01:00
|
|
|
{
|
2019-04-05 09:19:04 +02:00
|
|
|
connectionParameters.TemplateBehaviors.Add(new NBitcoin.Protocol.Behaviors.SocksSettingsBehavior()
|
2019-03-17 16:03:02 +01:00
|
|
|
{
|
2019-04-05 09:19:04 +02:00
|
|
|
SocksEndpoint = _options.SocksEndpoint
|
|
|
|
});
|
|
|
|
}
|
2020-03-13 15:10:26 +01:00
|
|
|
|
2019-04-05 09:19:04 +02:00
|
|
|
var socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
|
|
|
|
try
|
|
|
|
{
|
|
|
|
await connector.ConnectSocket(socket, endPoint, connectionParameters, cancellationToken);
|
2019-03-17 16:03:02 +01:00
|
|
|
}
|
|
|
|
catch
|
|
|
|
{
|
2019-04-05 09:19:04 +02:00
|
|
|
SafeCloseSocket(socket);
|
2019-03-17 16:03:02 +01:00
|
|
|
}
|
2020-03-13 15:10:26 +01:00
|
|
|
|
2019-03-17 16:03:02 +01:00
|
|
|
return socket;
|
|
|
|
}
|
|
|
|
|
2020-04-08 15:40:41 +02:00
|
|
|
internal static void SafeCloseSocket(Socket socket)
|
2019-03-17 16:03:02 +01:00
|
|
|
{
|
|
|
|
try
|
|
|
|
{
|
2019-04-05 09:19:04 +02:00
|
|
|
socket.Shutdown(SocketShutdown.Both);
|
2019-03-17 16:03:02 +01:00
|
|
|
}
|
|
|
|
catch
|
|
|
|
{
|
|
|
|
}
|
2020-03-13 15:10:26 +01:00
|
|
|
|
2019-04-05 09:19:04 +02:00
|
|
|
try
|
|
|
|
{
|
|
|
|
socket.Dispose();
|
|
|
|
}
|
|
|
|
catch
|
2019-03-17 16:03:02 +01:00
|
|
|
{
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|