You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

TcpPipeListener.cs 2.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using Pipelines.Sockets.Unofficial;
  2. using Shadowsocks.Protocol.Shadowsocks;
  3. using Shadowsocks.Protocol.Socks5;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Net;
  7. using System.Net.Sockets;
  8. using System.Threading.Tasks;
  9. namespace Shadowsocks.Protocol
  10. {
  11. public class TcpPipeListener
  12. {
  13. private readonly TcpListener _listener;
  14. private readonly IEnumerable<IStreamService> _services;
  15. public TcpPipeListener(IPEndPoint localEP)
  16. {
  17. _listener = new TcpListener(localEP);
  18. _services = new[] { new Socks5Service(), };
  19. }
  20. public TcpPipeListener(IPEndPoint endPoint, IEnumerable<IStreamService> services)
  21. {
  22. _listener = new TcpListener(endPoint);
  23. _services = services;
  24. }
  25. public async Task Start(IPEndPoint localEP, DnsEndPoint remoteEP, string method, string? password, byte[]? key)
  26. {
  27. _listener.Start();
  28. while (true)
  29. {
  30. var socket = await _listener.AcceptSocketAsync();
  31. var conn = SocketConnection.Create(socket);
  32. foreach (var svc in _services)
  33. {
  34. if (await svc.IsMyClient(conn))
  35. {
  36. // todo: save to list, so we can optionally close them
  37. _ = RunService(svc, conn, localEP, remoteEP, method, password, key);
  38. }
  39. }
  40. }
  41. }
  42. private async Task RunService(IStreamService svc, SocketConnection conn, IPEndPoint localEP, DnsEndPoint remoteEP, string method, string? password, byte[]? key)
  43. {
  44. var s5tcp = new PipePair();
  45. var raw = await svc.Handle(conn);
  46. ShadowsocksClient s5c;
  47. if (!string.IsNullOrEmpty(password))
  48. s5c = new ShadowsocksClient(method, password);
  49. else if (key != null)
  50. s5c = new ShadowsocksClient(method, key);
  51. else
  52. throw new ArgumentException("Either a password or a key must be provided.");
  53. var tpc = new TcpPipeClient();
  54. var t2 = tpc.Connect(remoteEP, s5tcp.DownSide, null);
  55. var t1 = s5c.Connect(localEP, raw, s5tcp.UpSide);
  56. await Task.WhenAll(t1, t2);
  57. }
  58. public void Stop() => _listener.Stop();
  59. }
  60. }