mirror of
https://git.ryujinx.app/ryubing/ryujinx.git
synced 2026-06-27 14:49:05 +00:00
TESTERS WANTED: RyuLDN implementation (#65)
These changes allow players to matchmake for local wireless using a LDN server. The network implementation originates from Berry's public TCP RyuLDN fork. Logo and unrelated changes have been removed. Additionally displays LDN game status in the game selection window when RyuLDN is enabled. Functionality is only enabled while network mode is set to "RyuLDN" in the settings.
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnRyu.Proxy
|
||||
{
|
||||
public class EphemeralPortPool
|
||||
{
|
||||
private const ushort EphemeralBase = 49152;
|
||||
|
||||
private readonly List<ushort> _ephemeralPorts = new List<ushort>();
|
||||
|
||||
private readonly object _lock = new object();
|
||||
|
||||
public ushort Get()
|
||||
{
|
||||
ushort port = EphemeralBase;
|
||||
lock (_lock)
|
||||
{
|
||||
// Starting at the ephemeral port base, return an ephemeral port that is not in use.
|
||||
// Returns 0 if the range is exhausted.
|
||||
|
||||
for (int i = 0; i < _ephemeralPorts.Count; i++)
|
||||
{
|
||||
ushort existingPort = _ephemeralPorts[i];
|
||||
|
||||
if (existingPort > port)
|
||||
{
|
||||
// The port was free - take it.
|
||||
_ephemeralPorts.Insert(i, port);
|
||||
|
||||
return port;
|
||||
}
|
||||
|
||||
port++;
|
||||
}
|
||||
|
||||
if (port != 0)
|
||||
{
|
||||
_ephemeralPorts.Add(port);
|
||||
}
|
||||
|
||||
return port;
|
||||
}
|
||||
}
|
||||
|
||||
public void Return(ushort port)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
_ephemeralPorts.Remove(port);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
using Ryujinx.Common.Logging;
|
||||
using Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnRyu.Types;
|
||||
using Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.Types;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnRyu.Proxy
|
||||
{
|
||||
class LdnProxy : IDisposable
|
||||
{
|
||||
public EndPoint LocalEndpoint { get; }
|
||||
public IPAddress LocalAddress { get; }
|
||||
|
||||
private readonly List<LdnProxySocket> _sockets = new List<LdnProxySocket>();
|
||||
private readonly Dictionary<ProtocolType, EphemeralPortPool> _ephemeralPorts = new Dictionary<ProtocolType, EphemeralPortPool>();
|
||||
|
||||
private readonly IProxyClient _parent;
|
||||
private RyuLdnProtocol _protocol;
|
||||
private readonly uint _subnetMask;
|
||||
private readonly uint _localIp;
|
||||
private readonly uint _broadcast;
|
||||
|
||||
public LdnProxy(ProxyConfig config, IProxyClient client, RyuLdnProtocol protocol)
|
||||
{
|
||||
_parent = client;
|
||||
_protocol = protocol;
|
||||
|
||||
_ephemeralPorts[ProtocolType.Udp] = new EphemeralPortPool();
|
||||
_ephemeralPorts[ProtocolType.Tcp] = new EphemeralPortPool();
|
||||
|
||||
byte[] address = BitConverter.GetBytes(config.ProxyIp);
|
||||
Array.Reverse(address);
|
||||
LocalAddress = new IPAddress(address);
|
||||
|
||||
_subnetMask = config.ProxySubnetMask;
|
||||
_localIp = config.ProxyIp;
|
||||
_broadcast = _localIp | (~_subnetMask);
|
||||
|
||||
RegisterHandlers(protocol);
|
||||
}
|
||||
|
||||
public bool Supported(AddressFamily domain, SocketType type, ProtocolType protocol)
|
||||
{
|
||||
if (protocol == ProtocolType.Tcp)
|
||||
{
|
||||
Logger.Error?.PrintMsg(LogClass.ServiceLdn, "Tcp proxy networking is untested. Please report this game so that it can be tested.");
|
||||
}
|
||||
return domain == AddressFamily.InterNetwork && (protocol == ProtocolType.Tcp || protocol == ProtocolType.Udp);
|
||||
}
|
||||
|
||||
private void RegisterHandlers(RyuLdnProtocol protocol)
|
||||
{
|
||||
protocol.ProxyConnect += HandleConnectionRequest;
|
||||
protocol.ProxyConnectReply += HandleConnectionResponse;
|
||||
protocol.ProxyData += HandleData;
|
||||
protocol.ProxyDisconnect += HandleDisconnect;
|
||||
|
||||
_protocol = protocol;
|
||||
}
|
||||
|
||||
public void UnregisterHandlers(RyuLdnProtocol protocol)
|
||||
{
|
||||
protocol.ProxyConnect -= HandleConnectionRequest;
|
||||
protocol.ProxyConnectReply -= HandleConnectionResponse;
|
||||
protocol.ProxyData -= HandleData;
|
||||
protocol.ProxyDisconnect -= HandleDisconnect;
|
||||
}
|
||||
|
||||
public ushort GetEphemeralPort(ProtocolType type)
|
||||
{
|
||||
return _ephemeralPorts[type].Get();
|
||||
}
|
||||
|
||||
public void ReturnEphemeralPort(ProtocolType type, ushort port)
|
||||
{
|
||||
_ephemeralPorts[type].Return(port);
|
||||
}
|
||||
|
||||
public void RegisterSocket(LdnProxySocket socket)
|
||||
{
|
||||
lock (_sockets)
|
||||
{
|
||||
_sockets.Add(socket);
|
||||
}
|
||||
}
|
||||
|
||||
public void UnregisterSocket(LdnProxySocket socket)
|
||||
{
|
||||
lock (_sockets)
|
||||
{
|
||||
_sockets.Remove(socket);
|
||||
}
|
||||
}
|
||||
|
||||
private void ForRoutedSockets(ProxyInfo info, Action<LdnProxySocket> action)
|
||||
{
|
||||
lock (_sockets)
|
||||
{
|
||||
foreach (LdnProxySocket socket in _sockets)
|
||||
{
|
||||
// Must match protocol and destination port.
|
||||
if (socket.ProtocolType != info.Protocol || socket.LocalEndPoint is not IPEndPoint endpoint || endpoint.Port != info.DestPort)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// We can assume packets routed to us have been sent to our destination.
|
||||
// They will either be sent to us, or broadcast packets.
|
||||
|
||||
action(socket);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void HandleConnectionRequest(LdnHeader header, ProxyConnectRequest request)
|
||||
{
|
||||
ForRoutedSockets(request.Info, (socket) =>
|
||||
{
|
||||
socket.HandleConnectRequest(request);
|
||||
});
|
||||
}
|
||||
|
||||
public void HandleConnectionResponse(LdnHeader header, ProxyConnectResponse response)
|
||||
{
|
||||
ForRoutedSockets(response.Info, (socket) =>
|
||||
{
|
||||
socket.HandleConnectResponse(response);
|
||||
});
|
||||
}
|
||||
|
||||
public void HandleData(LdnHeader header, ProxyDataHeader proxyHeader, byte[] data)
|
||||
{
|
||||
ProxyDataPacket packet = new ProxyDataPacket() { Header = proxyHeader, Data = data };
|
||||
|
||||
ForRoutedSockets(proxyHeader.Info, (socket) =>
|
||||
{
|
||||
socket.IncomingData(packet);
|
||||
});
|
||||
}
|
||||
|
||||
public void HandleDisconnect(LdnHeader header, ProxyDisconnectMessage disconnect)
|
||||
{
|
||||
ForRoutedSockets(disconnect.Info, (socket) =>
|
||||
{
|
||||
socket.HandleDisconnect(disconnect);
|
||||
});
|
||||
}
|
||||
|
||||
private uint GetIpV4(IPEndPoint endpoint)
|
||||
{
|
||||
if (endpoint.AddressFamily != AddressFamily.InterNetwork)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
byte[] address = endpoint.Address.GetAddressBytes();
|
||||
Array.Reverse(address);
|
||||
|
||||
return BitConverter.ToUInt32(address);
|
||||
}
|
||||
|
||||
private ProxyInfo MakeInfo(IPEndPoint localEp, IPEndPoint remoteEP, ProtocolType type)
|
||||
{
|
||||
return new ProxyInfo
|
||||
{
|
||||
SourceIpV4 = GetIpV4(localEp),
|
||||
SourcePort = (ushort)localEp.Port,
|
||||
|
||||
DestIpV4 = GetIpV4(remoteEP),
|
||||
DestPort = (ushort)remoteEP.Port,
|
||||
|
||||
Protocol = type
|
||||
};
|
||||
}
|
||||
|
||||
public void RequestConnection(IPEndPoint localEp, IPEndPoint remoteEp, ProtocolType type)
|
||||
{
|
||||
// We must ask the other side to initialize a connection, so they can accept a socket for us.
|
||||
|
||||
ProxyConnectRequest request = new ProxyConnectRequest
|
||||
{
|
||||
Info = MakeInfo(localEp, remoteEp, type)
|
||||
};
|
||||
|
||||
_parent.SendAsync(_protocol.Encode(PacketId.ProxyConnect, request));
|
||||
}
|
||||
|
||||
public void SignalConnected(IPEndPoint localEp, IPEndPoint remoteEp, ProtocolType type)
|
||||
{
|
||||
// We must tell the other side that we have accepted their request for connection.
|
||||
|
||||
ProxyConnectResponse request = new ProxyConnectResponse
|
||||
{
|
||||
Info = MakeInfo(localEp, remoteEp, type)
|
||||
};
|
||||
|
||||
_parent.SendAsync(_protocol.Encode(PacketId.ProxyConnectReply, request));
|
||||
}
|
||||
|
||||
public void EndConnection(IPEndPoint localEp, IPEndPoint remoteEp, ProtocolType type)
|
||||
{
|
||||
// We must tell the other side that our connection is dropped.
|
||||
|
||||
ProxyDisconnectMessage request = new ProxyDisconnectMessage
|
||||
{
|
||||
Info = MakeInfo(localEp, remoteEp, type),
|
||||
DisconnectReason = 0 // TODO
|
||||
};
|
||||
|
||||
_parent.SendAsync(_protocol.Encode(PacketId.ProxyDisconnect, request));
|
||||
}
|
||||
|
||||
public int SendTo(ReadOnlySpan<byte> buffer, SocketFlags flags, IPEndPoint localEp, IPEndPoint remoteEp, ProtocolType type)
|
||||
{
|
||||
// We send exactly as much as the user wants us to, currently instantly.
|
||||
// TODO: handle over "virtual mtu" (we have a max packet size to worry about anyways). fragment if tcp? throw if udp?
|
||||
|
||||
ProxyDataHeader request = new ProxyDataHeader
|
||||
{
|
||||
Info = MakeInfo(localEp, remoteEp, type),
|
||||
DataLength = (uint)buffer.Length
|
||||
};
|
||||
|
||||
_parent.SendAsync(_protocol.Encode(PacketId.ProxyData, request, buffer.ToArray()));
|
||||
|
||||
return buffer.Length;
|
||||
}
|
||||
|
||||
public bool IsBroadcast(uint ip)
|
||||
{
|
||||
return ip == _broadcast;
|
||||
}
|
||||
|
||||
public bool IsMyself(uint ip)
|
||||
{
|
||||
return ip == _localIp;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
UnregisterHandlers(_protocol);
|
||||
|
||||
lock (_sockets)
|
||||
{
|
||||
foreach (LdnProxySocket socket in _sockets)
|
||||
{
|
||||
socket.ProxyDestroyed();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,797 @@
|
||||
using Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnRyu.Types;
|
||||
using Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl;
|
||||
using Ryujinx.HLE.HOS.Services.Sockets.Bsd.Proxy;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
|
||||
namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnRyu.Proxy
|
||||
{
|
||||
/// <summary>
|
||||
/// This socket is forwarded through a TCP stream that goes through the Ldn server.
|
||||
/// The Ldn server will then route the packets we send (or need to receive) within the virtual adhoc network.
|
||||
/// </summary>
|
||||
class LdnProxySocket : ISocketImpl
|
||||
{
|
||||
private readonly LdnProxy _proxy;
|
||||
|
||||
private bool _isListening;
|
||||
private readonly List<LdnProxySocket> _listenSockets = new List<LdnProxySocket>();
|
||||
|
||||
private readonly Queue<ProxyConnectRequest> _connectRequests = new Queue<ProxyConnectRequest>();
|
||||
|
||||
private readonly AutoResetEvent _acceptEvent = new AutoResetEvent(false);
|
||||
private readonly int _acceptTimeout = -1;
|
||||
|
||||
private readonly Queue<int> _errors = new Queue<int>();
|
||||
|
||||
private readonly AutoResetEvent _connectEvent = new AutoResetEvent(false);
|
||||
private ProxyConnectResponse _connectResponse;
|
||||
|
||||
private int _receiveTimeout = -1;
|
||||
private readonly AutoResetEvent _receiveEvent = new AutoResetEvent(false);
|
||||
private readonly Queue<ProxyDataPacket> _receiveQueue = new Queue<ProxyDataPacket>();
|
||||
|
||||
// private int _sendTimeout = -1; // Sends are techically instant right now, so not _really_ used.
|
||||
|
||||
private bool _connecting;
|
||||
private bool _broadcast;
|
||||
private bool _readShutdown;
|
||||
// private bool _writeShutdown;
|
||||
private bool _closed;
|
||||
|
||||
private readonly Dictionary<SocketOptionName, int> _socketOptions = new Dictionary<SocketOptionName, int>()
|
||||
{
|
||||
{ SocketOptionName.Broadcast, 0 }, //TODO: honor this value
|
||||
{ SocketOptionName.DontLinger, 0 },
|
||||
{ SocketOptionName.Debug, 0 },
|
||||
{ SocketOptionName.Error, 0 },
|
||||
{ SocketOptionName.KeepAlive, 0 },
|
||||
{ SocketOptionName.OutOfBandInline, 0 },
|
||||
{ SocketOptionName.ReceiveBuffer, 131072 },
|
||||
{ SocketOptionName.ReceiveTimeout, -1 },
|
||||
{ SocketOptionName.SendBuffer, 131072 },
|
||||
{ SocketOptionName.SendTimeout, -1 },
|
||||
{ SocketOptionName.Type, 0 },
|
||||
{ SocketOptionName.ReuseAddress, 0 } //TODO: honor this value
|
||||
};
|
||||
|
||||
public EndPoint RemoteEndPoint { get; private set; }
|
||||
|
||||
public EndPoint LocalEndPoint { get; private set; }
|
||||
|
||||
public bool Connected { get; private set; }
|
||||
|
||||
public bool IsBound { get; private set; }
|
||||
|
||||
public AddressFamily AddressFamily { get; }
|
||||
|
||||
public SocketType SocketType { get; }
|
||||
|
||||
public ProtocolType ProtocolType { get; }
|
||||
|
||||
public bool Blocking { get; set; }
|
||||
|
||||
public int Available
|
||||
{
|
||||
get
|
||||
{
|
||||
int result = 0;
|
||||
|
||||
lock (_receiveQueue)
|
||||
{
|
||||
foreach (ProxyDataPacket data in _receiveQueue)
|
||||
{
|
||||
result += data.Data.Length;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
public bool Readable
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_isListening)
|
||||
{
|
||||
lock (_connectRequests)
|
||||
{
|
||||
return _connectRequests.Count > 0;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (_readShutdown)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
lock (_receiveQueue)
|
||||
{
|
||||
return _receiveQueue.Count > 0;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
public bool Writable => Connected || ProtocolType == ProtocolType.Udp;
|
||||
public bool Error => false;
|
||||
|
||||
public LdnProxySocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, LdnProxy proxy)
|
||||
{
|
||||
AddressFamily = addressFamily;
|
||||
SocketType = socketType;
|
||||
ProtocolType = protocolType;
|
||||
|
||||
_proxy = proxy;
|
||||
_socketOptions[SocketOptionName.Type] = (int)socketType;
|
||||
|
||||
proxy.RegisterSocket(this);
|
||||
}
|
||||
|
||||
private IPEndPoint EnsureLocalEndpoint(bool replace)
|
||||
{
|
||||
if (LocalEndPoint != null)
|
||||
{
|
||||
if (replace)
|
||||
{
|
||||
_proxy.ReturnEphemeralPort(ProtocolType, (ushort)((IPEndPoint)LocalEndPoint).Port);
|
||||
}
|
||||
else
|
||||
{
|
||||
return (IPEndPoint)LocalEndPoint;
|
||||
}
|
||||
}
|
||||
|
||||
IPEndPoint localEp = new IPEndPoint(_proxy.LocalAddress, _proxy.GetEphemeralPort(ProtocolType));
|
||||
LocalEndPoint = localEp;
|
||||
|
||||
return localEp;
|
||||
}
|
||||
|
||||
public LdnProxySocket AsAccepted(IPEndPoint remoteEp)
|
||||
{
|
||||
Connected = true;
|
||||
RemoteEndPoint = remoteEp;
|
||||
|
||||
IPEndPoint localEp = EnsureLocalEndpoint(true);
|
||||
|
||||
_proxy.SignalConnected(localEp, remoteEp, ProtocolType);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
private void SignalError(WsaError error)
|
||||
{
|
||||
lock (_errors)
|
||||
{
|
||||
_errors.Enqueue((int)error);
|
||||
}
|
||||
}
|
||||
|
||||
private IPEndPoint GetEndpoint(uint ipv4, ushort port)
|
||||
{
|
||||
byte[] address = BitConverter.GetBytes(ipv4);
|
||||
Array.Reverse(address);
|
||||
|
||||
return new IPEndPoint(new IPAddress(address), port);
|
||||
}
|
||||
|
||||
public void IncomingData(ProxyDataPacket packet)
|
||||
{
|
||||
bool isBroadcast = _proxy.IsBroadcast(packet.Header.Info.DestIpV4);
|
||||
|
||||
if (!_closed && (_broadcast || !isBroadcast))
|
||||
{
|
||||
lock (_receiveQueue)
|
||||
{
|
||||
_receiveQueue.Enqueue(packet);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public ISocketImpl Accept()
|
||||
{
|
||||
if (!_isListening)
|
||||
{
|
||||
throw new InvalidOperationException();
|
||||
}
|
||||
|
||||
// Accept a pending request to this socket.
|
||||
|
||||
lock (_connectRequests)
|
||||
{
|
||||
if (!Blocking && _connectRequests.Count == 0)
|
||||
{
|
||||
throw new SocketException((int)WsaError.WSAEWOULDBLOCK);
|
||||
}
|
||||
}
|
||||
|
||||
while (true)
|
||||
{
|
||||
_acceptEvent.WaitOne(_acceptTimeout);
|
||||
|
||||
lock (_connectRequests)
|
||||
{
|
||||
while (_connectRequests.Count > 0)
|
||||
{
|
||||
ProxyConnectRequest request = _connectRequests.Dequeue();
|
||||
|
||||
if (_connectRequests.Count > 0)
|
||||
{
|
||||
_acceptEvent.Set(); // Still more accepts to do.
|
||||
}
|
||||
|
||||
// Is this request made for us?
|
||||
IPEndPoint endpoint = GetEndpoint(request.Info.DestIpV4, request.Info.DestPort);
|
||||
|
||||
if (Equals(endpoint, LocalEndPoint))
|
||||
{
|
||||
// Yes - let's accept.
|
||||
IPEndPoint remoteEndpoint = GetEndpoint(request.Info.SourceIpV4, request.Info.SourcePort);
|
||||
|
||||
LdnProxySocket socket = new LdnProxySocket(AddressFamily, SocketType, ProtocolType, _proxy).AsAccepted(remoteEndpoint);
|
||||
|
||||
lock (_listenSockets)
|
||||
{
|
||||
_listenSockets.Add(socket);
|
||||
}
|
||||
|
||||
return socket;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Bind(EndPoint localEP)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(localEP);
|
||||
|
||||
if (LocalEndPoint != null)
|
||||
{
|
||||
_proxy.ReturnEphemeralPort(ProtocolType, (ushort)((IPEndPoint)LocalEndPoint).Port);
|
||||
}
|
||||
var asIPEndpoint = (IPEndPoint)localEP;
|
||||
if (asIPEndpoint.Port == 0)
|
||||
{
|
||||
asIPEndpoint.Port = (ushort)_proxy.GetEphemeralPort(ProtocolType);
|
||||
}
|
||||
|
||||
LocalEndPoint = (IPEndPoint)localEP;
|
||||
|
||||
IsBound = true;
|
||||
}
|
||||
|
||||
public void Close()
|
||||
{
|
||||
_closed = true;
|
||||
|
||||
_proxy.UnregisterSocket(this);
|
||||
|
||||
if (Connected)
|
||||
{
|
||||
Disconnect(false);
|
||||
}
|
||||
|
||||
lock (_listenSockets)
|
||||
{
|
||||
foreach (LdnProxySocket socket in _listenSockets)
|
||||
{
|
||||
socket.Close();
|
||||
}
|
||||
}
|
||||
|
||||
_isListening = false;
|
||||
}
|
||||
|
||||
public void Connect(EndPoint remoteEP)
|
||||
{
|
||||
if (_isListening || !IsBound)
|
||||
{
|
||||
throw new InvalidOperationException();
|
||||
}
|
||||
|
||||
if (remoteEP is not IPEndPoint)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
IPEndPoint localEp = EnsureLocalEndpoint(true);
|
||||
|
||||
_connecting = true;
|
||||
|
||||
_proxy.RequestConnection(localEp, (IPEndPoint)remoteEP, ProtocolType);
|
||||
|
||||
if (!Blocking && ProtocolType == ProtocolType.Tcp)
|
||||
{
|
||||
throw new SocketException((int)WsaError.WSAEWOULDBLOCK);
|
||||
}
|
||||
|
||||
_connectEvent.WaitOne(); //timeout?
|
||||
|
||||
if (_connectResponse.Info.SourceIpV4 == 0)
|
||||
{
|
||||
throw new SocketException((int)WsaError.WSAECONNREFUSED);
|
||||
}
|
||||
|
||||
_connectResponse = default;
|
||||
}
|
||||
|
||||
public void HandleConnectResponse(ProxyConnectResponse obj)
|
||||
{
|
||||
if (!_connecting)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_connecting = false;
|
||||
|
||||
if (_connectResponse.Info.SourceIpV4 != 0)
|
||||
{
|
||||
IPEndPoint remoteEp = GetEndpoint(obj.Info.SourceIpV4, obj.Info.SourcePort);
|
||||
RemoteEndPoint = remoteEp;
|
||||
|
||||
Connected = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Connection failed
|
||||
|
||||
SignalError(WsaError.WSAECONNREFUSED);
|
||||
}
|
||||
}
|
||||
|
||||
public void Disconnect(bool reuseSocket)
|
||||
{
|
||||
if (Connected)
|
||||
{
|
||||
ConnectionEnded();
|
||||
|
||||
// The other side needs to be notified that connection ended.
|
||||
_proxy.EndConnection(LocalEndPoint as IPEndPoint, RemoteEndPoint as IPEndPoint, ProtocolType);
|
||||
}
|
||||
}
|
||||
|
||||
private void ConnectionEnded()
|
||||
{
|
||||
if (Connected)
|
||||
{
|
||||
RemoteEndPoint = null;
|
||||
Connected = false;
|
||||
}
|
||||
}
|
||||
|
||||
public void GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue)
|
||||
{
|
||||
if (optionLevel != SocketOptionLevel.Socket)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
if (_socketOptions.TryGetValue(optionName, out int result))
|
||||
{
|
||||
byte[] data = BitConverter.GetBytes(result);
|
||||
Array.Copy(data, 0, optionValue, 0, Math.Min(data.Length, optionValue.Length));
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
public void Listen(int backlog)
|
||||
{
|
||||
if (!IsBound)
|
||||
{
|
||||
throw new SocketException();
|
||||
}
|
||||
|
||||
_isListening = true;
|
||||
}
|
||||
|
||||
public void HandleConnectRequest(ProxyConnectRequest obj)
|
||||
{
|
||||
lock (_connectRequests)
|
||||
{
|
||||
_connectRequests.Enqueue(obj);
|
||||
}
|
||||
|
||||
_connectEvent.Set();
|
||||
}
|
||||
|
||||
public void HandleDisconnect(ProxyDisconnectMessage message)
|
||||
{
|
||||
Disconnect(false);
|
||||
}
|
||||
|
||||
public int Receive(Span<byte> buffer)
|
||||
{
|
||||
EndPoint dummy = new IPEndPoint(IPAddress.Any, 0);
|
||||
|
||||
return ReceiveFrom(buffer, SocketFlags.None, ref dummy);
|
||||
}
|
||||
|
||||
public int Receive(Span<byte> buffer, SocketFlags flags)
|
||||
{
|
||||
EndPoint dummy = new IPEndPoint(IPAddress.Any, 0);
|
||||
|
||||
return ReceiveFrom(buffer, flags, ref dummy);
|
||||
}
|
||||
|
||||
public int Receive(Span<byte> buffer, SocketFlags flags, out SocketError socketError)
|
||||
{
|
||||
EndPoint dummy = new IPEndPoint(IPAddress.Any, 0);
|
||||
|
||||
return ReceiveFrom(buffer, flags, out socketError, ref dummy);
|
||||
}
|
||||
|
||||
public int ReceiveFrom(Span<byte> buffer, SocketFlags flags, ref EndPoint remoteEp)
|
||||
{
|
||||
// We just receive all packets meant for us anyways regardless of EP in the actual implementation.
|
||||
// The point is mostly to return the endpoint that we got the data from.
|
||||
|
||||
if (!Connected && ProtocolType == ProtocolType.Tcp)
|
||||
{
|
||||
throw new SocketException((int)WsaError.WSAECONNRESET);
|
||||
}
|
||||
|
||||
lock (_receiveQueue)
|
||||
{
|
||||
if (_receiveQueue.Count > 0)
|
||||
{
|
||||
return ReceiveFromQueue(buffer, flags, ref remoteEp);
|
||||
}
|
||||
else if (_readShutdown)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
else if (!Blocking)
|
||||
{
|
||||
throw new SocketException((int)WsaError.WSAEWOULDBLOCK);
|
||||
}
|
||||
}
|
||||
|
||||
int timeout = _receiveTimeout;
|
||||
|
||||
_receiveEvent.WaitOne(timeout == 0 ? -1 : timeout);
|
||||
|
||||
if (!Connected && ProtocolType == ProtocolType.Tcp)
|
||||
{
|
||||
throw new SocketException((int)WsaError.WSAECONNRESET);
|
||||
}
|
||||
|
||||
lock (_receiveQueue)
|
||||
{
|
||||
if (_receiveQueue.Count > 0)
|
||||
{
|
||||
return ReceiveFromQueue(buffer, flags, ref remoteEp);
|
||||
}
|
||||
else if (_readShutdown)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new SocketException((int)WsaError.WSAETIMEDOUT);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int ReceiveFrom(Span<byte> buffer, SocketFlags flags, out SocketError socketError, ref EndPoint remoteEp)
|
||||
{
|
||||
// We just receive all packets meant for us anyways regardless of EP in the actual implementation.
|
||||
// The point is mostly to return the endpoint that we got the data from.
|
||||
|
||||
if (!Connected && ProtocolType == ProtocolType.Tcp)
|
||||
{
|
||||
socketError = SocketError.ConnectionReset;
|
||||
return -1;
|
||||
}
|
||||
|
||||
lock (_receiveQueue)
|
||||
{
|
||||
if (_receiveQueue.Count > 0)
|
||||
{
|
||||
return ReceiveFromQueue(buffer, flags, out socketError, ref remoteEp);
|
||||
}
|
||||
else if (_readShutdown)
|
||||
{
|
||||
socketError = SocketError.Success;
|
||||
return 0;
|
||||
}
|
||||
else if (!Blocking)
|
||||
{
|
||||
throw new SocketException((int)WsaError.WSAEWOULDBLOCK);
|
||||
}
|
||||
}
|
||||
|
||||
int timeout = _receiveTimeout;
|
||||
|
||||
_receiveEvent.WaitOne(timeout == 0 ? -1 : timeout);
|
||||
|
||||
if (!Connected && ProtocolType == ProtocolType.Tcp)
|
||||
{
|
||||
throw new SocketException((int)WsaError.WSAECONNRESET);
|
||||
}
|
||||
|
||||
lock (_receiveQueue)
|
||||
{
|
||||
if (_receiveQueue.Count > 0)
|
||||
{
|
||||
return ReceiveFromQueue(buffer, flags, out socketError, ref remoteEp);
|
||||
}
|
||||
else if (_readShutdown)
|
||||
{
|
||||
socketError = SocketError.Success;
|
||||
return 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
socketError = SocketError.TimedOut;
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private int ReceiveFromQueue(Span<byte> buffer, SocketFlags flags, ref EndPoint remoteEp)
|
||||
{
|
||||
int size = buffer.Length;
|
||||
|
||||
// Assumes we have the receive queue lock, and at least one item in the queue.
|
||||
ProxyDataPacket packet = _receiveQueue.Peek();
|
||||
|
||||
remoteEp = GetEndpoint(packet.Header.Info.SourceIpV4, packet.Header.Info.SourcePort);
|
||||
|
||||
bool peek = (flags & SocketFlags.Peek) != 0;
|
||||
|
||||
int read;
|
||||
|
||||
if (packet.Data.Length > size)
|
||||
{
|
||||
read = size;
|
||||
|
||||
// Cannot fit in the output buffer. Copy up to what we've got.
|
||||
packet.Data.AsSpan(0, size).CopyTo(buffer);
|
||||
|
||||
if (ProtocolType == ProtocolType.Udp)
|
||||
{
|
||||
// Udp overflows, loses the data, then throws an exception.
|
||||
|
||||
if (!peek)
|
||||
{
|
||||
_receiveQueue.Dequeue();
|
||||
}
|
||||
|
||||
throw new SocketException((int)WsaError.WSAEMSGSIZE);
|
||||
}
|
||||
else if (ProtocolType == ProtocolType.Tcp)
|
||||
{
|
||||
// Split the data at the buffer boundary. It will stay on the recieve queue.
|
||||
|
||||
byte[] newData = new byte[packet.Data.Length - size];
|
||||
Array.Copy(packet.Data, size, newData, 0, newData.Length);
|
||||
|
||||
packet.Data = newData;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
read = packet.Data.Length;
|
||||
|
||||
packet.Data.AsSpan(0, packet.Data.Length).CopyTo(buffer);
|
||||
|
||||
if (!peek)
|
||||
{
|
||||
_receiveQueue.Dequeue();
|
||||
}
|
||||
}
|
||||
|
||||
return read;
|
||||
}
|
||||
|
||||
private int ReceiveFromQueue(Span<byte> buffer, SocketFlags flags, out SocketError socketError, ref EndPoint remoteEp)
|
||||
{
|
||||
int size = buffer.Length;
|
||||
|
||||
// Assumes we have the receive queue lock, and at least one item in the queue.
|
||||
ProxyDataPacket packet = _receiveQueue.Peek();
|
||||
|
||||
remoteEp = GetEndpoint(packet.Header.Info.SourceIpV4, packet.Header.Info.SourcePort);
|
||||
|
||||
bool peek = (flags & SocketFlags.Peek) != 0;
|
||||
|
||||
int read;
|
||||
|
||||
if (packet.Data.Length > size)
|
||||
{
|
||||
read = size;
|
||||
|
||||
// Cannot fit in the output buffer. Copy up to what we've got.
|
||||
packet.Data.AsSpan(0, size).CopyTo(buffer);
|
||||
|
||||
if (ProtocolType == ProtocolType.Udp)
|
||||
{
|
||||
// Udp overflows, loses the data, then throws an exception.
|
||||
|
||||
if (!peek)
|
||||
{
|
||||
_receiveQueue.Dequeue();
|
||||
}
|
||||
|
||||
socketError = SocketError.MessageSize;
|
||||
return -1;
|
||||
}
|
||||
else if (ProtocolType == ProtocolType.Tcp)
|
||||
{
|
||||
// Split the data at the buffer boundary. It will stay on the recieve queue.
|
||||
|
||||
byte[] newData = new byte[packet.Data.Length - size];
|
||||
Array.Copy(packet.Data, size, newData, 0, newData.Length);
|
||||
|
||||
packet.Data = newData;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
read = packet.Data.Length;
|
||||
|
||||
packet.Data.AsSpan(0, packet.Data.Length).CopyTo(buffer);
|
||||
|
||||
if (!peek)
|
||||
{
|
||||
_receiveQueue.Dequeue();
|
||||
}
|
||||
}
|
||||
|
||||
socketError = SocketError.Success;
|
||||
|
||||
return read;
|
||||
}
|
||||
|
||||
public int Send(ReadOnlySpan<byte> buffer)
|
||||
{
|
||||
// Send to the remote host chosen when we "connect" or "accept".
|
||||
if (!Connected)
|
||||
{
|
||||
throw new SocketException();
|
||||
}
|
||||
|
||||
return SendTo(buffer, SocketFlags.None, RemoteEndPoint);
|
||||
}
|
||||
|
||||
public int Send(ReadOnlySpan<byte> buffer, SocketFlags flags)
|
||||
{
|
||||
// Send to the remote host chosen when we "connect" or "accept".
|
||||
if (!Connected)
|
||||
{
|
||||
throw new SocketException();
|
||||
}
|
||||
|
||||
return SendTo(buffer, flags, RemoteEndPoint);
|
||||
}
|
||||
|
||||
public int Send(ReadOnlySpan<byte> buffer, SocketFlags flags, out SocketError socketError)
|
||||
{
|
||||
// Send to the remote host chosen when we "connect" or "accept".
|
||||
if (!Connected)
|
||||
{
|
||||
throw new SocketException();
|
||||
}
|
||||
|
||||
return SendTo(buffer, flags, out socketError, RemoteEndPoint);
|
||||
}
|
||||
|
||||
public int SendTo(ReadOnlySpan<byte> buffer, SocketFlags flags, EndPoint remoteEP)
|
||||
{
|
||||
if (!Connected && ProtocolType == ProtocolType.Tcp)
|
||||
{
|
||||
throw new SocketException((int)WsaError.WSAECONNRESET);
|
||||
}
|
||||
|
||||
IPEndPoint localEp = EnsureLocalEndpoint(false);
|
||||
|
||||
if (remoteEP is not IPEndPoint)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
return _proxy.SendTo(buffer, flags, localEp, (IPEndPoint)remoteEP, ProtocolType);
|
||||
}
|
||||
|
||||
public int SendTo(ReadOnlySpan<byte> buffer, SocketFlags flags, out SocketError socketError, EndPoint remoteEP)
|
||||
{
|
||||
if (!Connected && ProtocolType == ProtocolType.Tcp)
|
||||
{
|
||||
socketError = SocketError.ConnectionReset;
|
||||
return -1;
|
||||
}
|
||||
|
||||
IPEndPoint localEp = EnsureLocalEndpoint(false);
|
||||
|
||||
if (remoteEP is not IPEndPoint)
|
||||
{
|
||||
// throw new NotSupportedException();
|
||||
socketError = SocketError.OperationNotSupported;
|
||||
return -1;
|
||||
}
|
||||
|
||||
socketError = SocketError.Success;
|
||||
|
||||
return _proxy.SendTo(buffer, flags, localEp, (IPEndPoint)remoteEP, ProtocolType);
|
||||
}
|
||||
|
||||
public bool Poll(int microSeconds, SelectMode mode)
|
||||
{
|
||||
return mode switch
|
||||
{
|
||||
SelectMode.SelectRead => Readable,
|
||||
SelectMode.SelectWrite => Writable,
|
||||
SelectMode.SelectError => Error,
|
||||
_ => false
|
||||
};
|
||||
}
|
||||
|
||||
public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue)
|
||||
{
|
||||
if (optionLevel != SocketOptionLevel.Socket)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
switch (optionName)
|
||||
{
|
||||
case SocketOptionName.SendTimeout:
|
||||
//_sendTimeout = optionValue;
|
||||
break;
|
||||
case SocketOptionName.ReceiveTimeout:
|
||||
_receiveTimeout = optionValue;
|
||||
break;
|
||||
case SocketOptionName.Broadcast:
|
||||
_broadcast = optionValue != 0;
|
||||
break;
|
||||
}
|
||||
|
||||
lock (_socketOptions)
|
||||
{
|
||||
_socketOptions[optionName] = optionValue;
|
||||
}
|
||||
}
|
||||
|
||||
public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, object optionValue)
|
||||
{
|
||||
// Just linger uses this for now in BSD, which we ignore.
|
||||
}
|
||||
|
||||
public void Shutdown(SocketShutdown how)
|
||||
{
|
||||
switch (how)
|
||||
{
|
||||
case SocketShutdown.Both:
|
||||
_readShutdown = true;
|
||||
// _writeShutdown = true;
|
||||
break;
|
||||
case SocketShutdown.Receive:
|
||||
_readShutdown = true;
|
||||
break;
|
||||
case SocketShutdown.Send:
|
||||
// _writeShutdown = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public void ProxyDestroyed()
|
||||
{
|
||||
// Do nothing, for now. Will likely be more useful with TCP.
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
using Ryujinx.Common.Logging;
|
||||
using Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnRyu.Types;
|
||||
using Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.Types;
|
||||
using Ryujinx.HLE.HOS.Services.Sockets.Bsd.Proxy;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
using TcpClient = NetCoreServer.TcpClient;
|
||||
|
||||
namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnRyu.Proxy
|
||||
{
|
||||
class P2pProxyClient : TcpClient, IProxyClient
|
||||
{
|
||||
private const int FailureTimeout = 4000;
|
||||
|
||||
public ProxyConfig ProxyConfig { get; private set; }
|
||||
|
||||
private readonly RyuLdnProtocol _protocol;
|
||||
|
||||
private readonly ManualResetEvent _connected = new ManualResetEvent(false);
|
||||
private readonly ManualResetEvent _ready = new ManualResetEvent(false);
|
||||
private readonly AutoResetEvent _error = new AutoResetEvent(false);
|
||||
|
||||
public P2pProxyClient(string address, int port) : base(address, port)
|
||||
{
|
||||
if (ProxyHelpers.SupportsNoDelay())
|
||||
{
|
||||
OptionNoDelay = true;
|
||||
}
|
||||
|
||||
_protocol = new RyuLdnProtocol();
|
||||
|
||||
_protocol.ProxyConfig += HandleProxyConfig;
|
||||
|
||||
ConnectAsync();
|
||||
}
|
||||
|
||||
protected override void OnConnected()
|
||||
{
|
||||
Logger.Info?.PrintMsg(LogClass.ServiceLdn, $"Proxy TCP client connected a new session with Id {Id}");
|
||||
|
||||
_connected.Set();
|
||||
}
|
||||
|
||||
protected override void OnDisconnected()
|
||||
{
|
||||
Logger.Info?.PrintMsg(LogClass.ServiceLdn, $"Proxy TCP client disconnected a session with Id {Id}");
|
||||
|
||||
SocketHelpers.UnregisterProxy();
|
||||
|
||||
_connected.Reset();
|
||||
}
|
||||
|
||||
protected override void OnReceived(byte[] buffer, long offset, long size)
|
||||
{
|
||||
_protocol.Read(buffer, (int)offset, (int)size);
|
||||
}
|
||||
|
||||
protected override void OnError(SocketError error)
|
||||
{
|
||||
Logger.Info?.PrintMsg(LogClass.ServiceLdn, $"Proxy TCP client caught an error with code {error}");
|
||||
|
||||
_error.Set();
|
||||
}
|
||||
|
||||
private void HandleProxyConfig(LdnHeader header, ProxyConfig config)
|
||||
{
|
||||
ProxyConfig = config;
|
||||
|
||||
SocketHelpers.RegisterProxy(new LdnProxy(config, this, _protocol));
|
||||
|
||||
_ready.Set();
|
||||
}
|
||||
|
||||
public bool EnsureProxyReady()
|
||||
{
|
||||
return _ready.WaitOne(FailureTimeout);
|
||||
}
|
||||
|
||||
public bool PerformAuth(ExternalProxyConfig config)
|
||||
{
|
||||
bool signalled = _connected.WaitOne(FailureTimeout);
|
||||
|
||||
if (!signalled)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
SendAsync(_protocol.Encode(PacketId.ExternalProxy, config));
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,388 @@
|
||||
using NetCoreServer;
|
||||
using Open.Nat;
|
||||
using Ryujinx.Common.Logging;
|
||||
using Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnRyu.Types;
|
||||
using Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.Types;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnRyu.Proxy
|
||||
{
|
||||
class P2pProxyServer : TcpServer, IDisposable
|
||||
{
|
||||
public const ushort PrivatePortBase = 39990;
|
||||
public const int PrivatePortRange = 10;
|
||||
|
||||
private const ushort PublicPortBase = 39990;
|
||||
private const int PublicPortRange = 10;
|
||||
|
||||
private const ushort PortLeaseLength = 60;
|
||||
private const ushort PortLeaseRenew = 50;
|
||||
|
||||
private const ushort AuthWaitSeconds = 1;
|
||||
|
||||
private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
|
||||
|
||||
public ushort PrivatePort { get; }
|
||||
|
||||
private ushort _publicPort;
|
||||
|
||||
private bool _disposed;
|
||||
private readonly CancellationTokenSource _disposedCancellation = new CancellationTokenSource();
|
||||
|
||||
private NatDevice _natDevice;
|
||||
private Mapping _portMapping;
|
||||
|
||||
private readonly List<P2pProxySession> _players = new List<P2pProxySession>();
|
||||
|
||||
private readonly List<ExternalProxyToken> _waitingTokens = new List<ExternalProxyToken>();
|
||||
private readonly AutoResetEvent _tokenEvent = new AutoResetEvent(false);
|
||||
|
||||
private uint _broadcastAddress;
|
||||
|
||||
private readonly LdnMasterProxyClient _master;
|
||||
private readonly RyuLdnProtocol _masterProtocol;
|
||||
private readonly RyuLdnProtocol _protocol;
|
||||
|
||||
public P2pProxyServer(LdnMasterProxyClient master, ushort port, RyuLdnProtocol masterProtocol) : base(IPAddress.Any, port)
|
||||
{
|
||||
if (ProxyHelpers.SupportsNoDelay())
|
||||
{
|
||||
OptionNoDelay = true;
|
||||
}
|
||||
|
||||
PrivatePort = port;
|
||||
|
||||
_master = master;
|
||||
_masterProtocol = masterProtocol;
|
||||
|
||||
_masterProtocol.ExternalProxyState += HandleStateChange;
|
||||
_masterProtocol.ExternalProxyToken += HandleToken;
|
||||
|
||||
_protocol = new RyuLdnProtocol();
|
||||
}
|
||||
|
||||
private void HandleToken(LdnHeader header, ExternalProxyToken token)
|
||||
{
|
||||
_lock.EnterWriteLock();
|
||||
|
||||
_waitingTokens.Add(token);
|
||||
|
||||
_lock.ExitWriteLock();
|
||||
|
||||
_tokenEvent.Set();
|
||||
}
|
||||
|
||||
private void HandleStateChange(LdnHeader header, ExternalProxyConnectionState state)
|
||||
{
|
||||
if (!state.Connected)
|
||||
{
|
||||
_lock.EnterWriteLock();
|
||||
|
||||
_waitingTokens.RemoveAll(token => token.VirtualIp == state.IpAddress);
|
||||
|
||||
_players.RemoveAll(player =>
|
||||
{
|
||||
if (player.VirtualIpAddress == state.IpAddress)
|
||||
{
|
||||
player.DisconnectAndStop();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
});
|
||||
|
||||
_lock.ExitWriteLock();
|
||||
}
|
||||
}
|
||||
|
||||
public void Configure(ProxyConfig config)
|
||||
{
|
||||
_broadcastAddress = config.ProxyIp | (~config.ProxySubnetMask);
|
||||
}
|
||||
|
||||
public async Task<ushort> NatPunch()
|
||||
{
|
||||
NatDiscoverer discoverer = new NatDiscoverer();
|
||||
CancellationTokenSource cts = new CancellationTokenSource(1000);
|
||||
|
||||
NatDevice device;
|
||||
|
||||
try
|
||||
{
|
||||
device = await discoverer.DiscoverDeviceAsync(PortMapper.Upnp, cts);
|
||||
}
|
||||
catch (NatDeviceNotFoundException)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
_publicPort = PublicPortBase;
|
||||
|
||||
for (int i = 0; i < PublicPortRange; i++)
|
||||
{
|
||||
try
|
||||
{
|
||||
_portMapping = new Mapping(Protocol.Tcp, PrivatePort, _publicPort, PortLeaseLength, "Ryujinx Local Multiplayer");
|
||||
|
||||
await device.CreatePortMapAsync(_portMapping);
|
||||
|
||||
break;
|
||||
}
|
||||
catch (MappingException)
|
||||
{
|
||||
_publicPort++;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (i == PublicPortRange - 1)
|
||||
{
|
||||
_publicPort = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (_publicPort != 0)
|
||||
{
|
||||
_ = Task.Delay(PortLeaseRenew * 1000, _disposedCancellation.Token).ContinueWith((task) => Task.Run(RefreshLease));
|
||||
}
|
||||
|
||||
_natDevice = device;
|
||||
|
||||
return _publicPort;
|
||||
}
|
||||
|
||||
// Proxy handlers
|
||||
|
||||
private void RouteMessage(P2pProxySession sender, ref ProxyInfo info, Action<P2pProxySession> action)
|
||||
{
|
||||
if (info.SourceIpV4 == 0)
|
||||
{
|
||||
// If they sent from a connection bound on 0.0.0.0, make others see it as them.
|
||||
info.SourceIpV4 = sender.VirtualIpAddress;
|
||||
}
|
||||
else if (info.SourceIpV4 != sender.VirtualIpAddress)
|
||||
{
|
||||
// Can't pretend to be somebody else.
|
||||
return;
|
||||
}
|
||||
|
||||
uint destIp = info.DestIpV4;
|
||||
|
||||
if (destIp == 0xc0a800ff)
|
||||
{
|
||||
destIp = _broadcastAddress;
|
||||
}
|
||||
|
||||
bool isBroadcast = destIp == _broadcastAddress;
|
||||
|
||||
_lock.EnterReadLock();
|
||||
|
||||
if (isBroadcast)
|
||||
{
|
||||
_players.ForEach(player =>
|
||||
{
|
||||
action(player);
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
P2pProxySession target = _players.FirstOrDefault(player => player.VirtualIpAddress == destIp);
|
||||
|
||||
if (target != null)
|
||||
{
|
||||
action(target);
|
||||
}
|
||||
}
|
||||
|
||||
_lock.ExitReadLock();
|
||||
}
|
||||
|
||||
public void HandleProxyDisconnect(P2pProxySession sender, LdnHeader header, ProxyDisconnectMessage message)
|
||||
{
|
||||
RouteMessage(sender, ref message.Info, (target) =>
|
||||
{
|
||||
target.SendAsync(sender.Protocol.Encode(PacketId.ProxyDisconnect, message));
|
||||
});
|
||||
}
|
||||
|
||||
public void HandleProxyData(P2pProxySession sender, LdnHeader header, ProxyDataHeader message, byte[] data)
|
||||
{
|
||||
RouteMessage(sender, ref message.Info, (target) =>
|
||||
{
|
||||
target.SendAsync(sender.Protocol.Encode(PacketId.ProxyData, message, data));
|
||||
});
|
||||
}
|
||||
|
||||
public void HandleProxyConnectReply(P2pProxySession sender, LdnHeader header, ProxyConnectResponse message)
|
||||
{
|
||||
RouteMessage(sender, ref message.Info, (target) =>
|
||||
{
|
||||
target.SendAsync(sender.Protocol.Encode(PacketId.ProxyConnectReply, message));
|
||||
});
|
||||
}
|
||||
|
||||
public void HandleProxyConnect(P2pProxySession sender, LdnHeader header, ProxyConnectRequest message)
|
||||
{
|
||||
RouteMessage(sender, ref message.Info, (target) =>
|
||||
{
|
||||
target.SendAsync(sender.Protocol.Encode(PacketId.ProxyConnect, message));
|
||||
});
|
||||
}
|
||||
|
||||
// End proxy handlers
|
||||
|
||||
private async Task RefreshLease()
|
||||
{
|
||||
if (_disposed || _natDevice == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await _natDevice.CreatePortMapAsync(_portMapping);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
_ = Task.Delay(PortLeaseRenew, _disposedCancellation.Token).ContinueWith((task) => Task.Run(RefreshLease));
|
||||
}
|
||||
|
||||
public bool TryRegisterUser(P2pProxySession session, ExternalProxyConfig config)
|
||||
{
|
||||
_lock.EnterWriteLock();
|
||||
|
||||
// Attempt to find matching configuration. If we don't find one, wait for a bit and try again.
|
||||
// Woken by new tokens coming in from the master server.
|
||||
|
||||
IPAddress address = (session.Socket.RemoteEndPoint as IPEndPoint).Address;
|
||||
byte[] addressBytes = ProxyHelpers.AddressTo16Byte(address);
|
||||
|
||||
long time;
|
||||
long endTime = Stopwatch.GetTimestamp() + Stopwatch.Frequency * AuthWaitSeconds;
|
||||
|
||||
do
|
||||
{
|
||||
for (int i = 0; i < _waitingTokens.Count; i++)
|
||||
{
|
||||
ExternalProxyToken waitToken = _waitingTokens[i];
|
||||
|
||||
// Allow any client that has a private IP to connect. (indicated by the server as all 0 in the token)
|
||||
|
||||
bool isPrivate = waitToken.PhysicalIp.AsSpan().SequenceEqual(new byte[16]);
|
||||
bool ipEqual = isPrivate || waitToken.AddressFamily == address.AddressFamily && waitToken.PhysicalIp.AsSpan().SequenceEqual(addressBytes);
|
||||
|
||||
if (ipEqual && waitToken.Token.AsSpan().SequenceEqual(config.Token.AsSpan()))
|
||||
{
|
||||
// This is a match.
|
||||
|
||||
_waitingTokens.RemoveAt(i);
|
||||
|
||||
session.SetIpv4(waitToken.VirtualIp);
|
||||
|
||||
ProxyConfig pconfig = new ProxyConfig
|
||||
{
|
||||
ProxyIp = session.VirtualIpAddress,
|
||||
ProxySubnetMask = 0xFFFF0000 // TODO: Use from server.
|
||||
};
|
||||
|
||||
if (_players.Count == 0)
|
||||
{
|
||||
Configure(pconfig);
|
||||
}
|
||||
|
||||
_players.Add(session);
|
||||
|
||||
session.SendAsync(_protocol.Encode(PacketId.ProxyConfig, pconfig));
|
||||
|
||||
_lock.ExitWriteLock();
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Couldn't find the token.
|
||||
// It may not have arrived yet, so wait for one to arrive.
|
||||
|
||||
_lock.ExitWriteLock();
|
||||
|
||||
time = Stopwatch.GetTimestamp();
|
||||
int remainingMs = (int)((endTime - time) / (Stopwatch.Frequency / 1000));
|
||||
|
||||
if (remainingMs < 0)
|
||||
{
|
||||
remainingMs = 0;
|
||||
}
|
||||
|
||||
_tokenEvent.WaitOne(remainingMs);
|
||||
|
||||
_lock.EnterWriteLock();
|
||||
|
||||
} while (time < endTime);
|
||||
|
||||
_lock.ExitWriteLock();
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public void DisconnectProxyClient(P2pProxySession session)
|
||||
{
|
||||
_lock.EnterWriteLock();
|
||||
|
||||
bool removed = _players.Remove(session);
|
||||
|
||||
if (removed)
|
||||
{
|
||||
_master.SendAsync(_masterProtocol.Encode(PacketId.ExternalProxyState, new ExternalProxyConnectionState
|
||||
{
|
||||
IpAddress = session.VirtualIpAddress,
|
||||
Connected = false
|
||||
}));
|
||||
}
|
||||
|
||||
_lock.ExitWriteLock();
|
||||
}
|
||||
|
||||
public new void Dispose()
|
||||
{
|
||||
base.Dispose();
|
||||
|
||||
_disposed = true;
|
||||
_disposedCancellation.Cancel();
|
||||
|
||||
try
|
||||
{
|
||||
Task delete = _natDevice?.DeletePortMapAsync(new Mapping(Protocol.Tcp, PrivatePort, _publicPort, 60, "Ryujinx Local Multiplayer"));
|
||||
|
||||
// Just absorb any exceptions.
|
||||
delete?.ContinueWith((task) => { });
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// Fail silently.
|
||||
}
|
||||
}
|
||||
|
||||
protected override TcpSession CreateSession()
|
||||
{
|
||||
return new P2pProxySession(this);
|
||||
}
|
||||
|
||||
protected override void OnError(SocketError error)
|
||||
{
|
||||
Logger.Info?.PrintMsg(LogClass.ServiceLdn, $"Proxy TCP server caught an error with code {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
using NetCoreServer;
|
||||
using Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnRyu.Types;
|
||||
using System;
|
||||
|
||||
namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnRyu.Proxy
|
||||
{
|
||||
class P2pProxySession : TcpSession
|
||||
{
|
||||
public uint VirtualIpAddress { get; private set; }
|
||||
public RyuLdnProtocol Protocol { get; }
|
||||
|
||||
private readonly P2pProxyServer _parent;
|
||||
|
||||
private bool _masterClosed;
|
||||
|
||||
public P2pProxySession(P2pProxyServer server) : base(server)
|
||||
{
|
||||
_parent = server;
|
||||
|
||||
Protocol = new RyuLdnProtocol();
|
||||
|
||||
Protocol.ProxyDisconnect += HandleProxyDisconnect;
|
||||
Protocol.ProxyData += HandleProxyData;
|
||||
Protocol.ProxyConnectReply += HandleProxyConnectReply;
|
||||
Protocol.ProxyConnect += HandleProxyConnect;
|
||||
|
||||
Protocol.ExternalProxy += HandleAuthentication;
|
||||
}
|
||||
|
||||
private void HandleAuthentication(LdnHeader header, ExternalProxyConfig token)
|
||||
{
|
||||
if (!_parent.TryRegisterUser(this, token))
|
||||
{
|
||||
Disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
public void SetIpv4(uint ip)
|
||||
{
|
||||
VirtualIpAddress = ip;
|
||||
}
|
||||
|
||||
public void DisconnectAndStop()
|
||||
{
|
||||
_masterClosed = true;
|
||||
|
||||
Disconnect();
|
||||
}
|
||||
|
||||
protected override void OnDisconnected()
|
||||
{
|
||||
if (!_masterClosed)
|
||||
{
|
||||
_parent.DisconnectProxyClient(this);
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnReceived(byte[] buffer, long offset, long size)
|
||||
{
|
||||
try
|
||||
{
|
||||
Protocol.Read(buffer, (int)offset, (int)size);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
Disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
private void HandleProxyDisconnect(LdnHeader header, ProxyDisconnectMessage message)
|
||||
{
|
||||
_parent.HandleProxyDisconnect(this, header, message);
|
||||
}
|
||||
|
||||
private void HandleProxyData(LdnHeader header, ProxyDataHeader message, byte[] data)
|
||||
{
|
||||
_parent.HandleProxyData(this, header, message, data);
|
||||
}
|
||||
|
||||
private void HandleProxyConnectReply(LdnHeader header, ProxyConnectResponse data)
|
||||
{
|
||||
_parent.HandleProxyConnectReply(this, header, data);
|
||||
}
|
||||
|
||||
private void HandleProxyConnect(LdnHeader header, ProxyConnectRequest message)
|
||||
{
|
||||
_parent.HandleProxyConnect(this, header, message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnRyu.Proxy
|
||||
{
|
||||
static class ProxyHelpers
|
||||
{
|
||||
public static byte[] AddressTo16Byte(IPAddress address)
|
||||
{
|
||||
byte[] ipBytes = new byte[16];
|
||||
byte[] srcBytes = address.GetAddressBytes();
|
||||
|
||||
Array.Copy(srcBytes, 0, ipBytes, 0, srcBytes.Length);
|
||||
|
||||
return ipBytes;
|
||||
}
|
||||
|
||||
public static bool SupportsNoDelay()
|
||||
{
|
||||
return RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user