P2pProxyClient.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using Ryujinx.Common.Logging;
  2. using Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnRyu.Types;
  3. using Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.Types;
  4. using Ryujinx.HLE.HOS.Services.Sockets.Bsd.Proxy;
  5. using System.Net.Sockets;
  6. using System.Threading;
  7. using TcpClient = NetCoreServer.TcpClient;
  8. namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnRyu.Proxy
  9. {
  10. class P2pProxyClient : TcpClient, IProxyClient
  11. {
  12. private const int FailureTimeout = 4000;
  13. public ProxyConfig ProxyConfig { get; private set; }
  14. private readonly RyuLdnProtocol _protocol;
  15. private readonly ManualResetEvent _connected = new(false);
  16. private readonly ManualResetEvent _ready = new(false);
  17. private readonly AutoResetEvent _error = new(false);
  18. public P2pProxyClient(string address, int port) : base(address, port)
  19. {
  20. if (ProxyHelpers.SupportsNoDelay())
  21. {
  22. OptionNoDelay = true;
  23. }
  24. _protocol = new RyuLdnProtocol();
  25. _protocol.ProxyConfig += HandleProxyConfig;
  26. ConnectAsync();
  27. }
  28. protected override void OnConnected()
  29. {
  30. Logger.Info?.PrintMsg(LogClass.ServiceLdn, $"Proxy TCP client connected a new session with Id {Id}");
  31. _connected.Set();
  32. }
  33. protected override void OnDisconnected()
  34. {
  35. Logger.Info?.PrintMsg(LogClass.ServiceLdn, $"Proxy TCP client disconnected a session with Id {Id}");
  36. SocketHelpers.UnregisterProxy();
  37. _connected.Reset();
  38. }
  39. protected override void OnReceived(byte[] buffer, long offset, long size)
  40. {
  41. _protocol.Read(buffer, (int)offset, (int)size);
  42. }
  43. protected override void OnError(SocketError error)
  44. {
  45. Logger.Info?.PrintMsg(LogClass.ServiceLdn, $"Proxy TCP client caught an error with code {error}");
  46. _error.Set();
  47. }
  48. private void HandleProxyConfig(LdnHeader header, ProxyConfig config)
  49. {
  50. ProxyConfig = config;
  51. SocketHelpers.RegisterProxy(new LdnProxy(config, this, _protocol));
  52. _ready.Set();
  53. }
  54. public bool EnsureProxyReady()
  55. {
  56. return _ready.WaitOne(FailureTimeout);
  57. }
  58. public bool PerformAuth(ExternalProxyConfig config)
  59. {
  60. bool signalled = _connected.WaitOne(FailureTimeout);
  61. if (!signalled)
  62. {
  63. return false;
  64. }
  65. SendAsync(_protocol.Encode(PacketId.ExternalProxy, config));
  66. return true;
  67. }
  68. }
  69. }