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.

UDPListener.cs 3.9 kB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. using Splat;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.NetworkInformation;
  7. using System.Net.Sockets;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. namespace Shadowsocks.Net
  11. {
  12. public interface IDatagramService
  13. {
  14. public abstract Task< bool> Handle(Memory<byte> packet, Socket socket, EndPoint client);
  15. void Stop();
  16. }
  17. public abstract class DatagramService : IDatagramService
  18. {
  19. public abstract Task<bool> Handle(Memory<byte> packet, Socket socket, EndPoint client);
  20. public virtual void Stop() { }
  21. }
  22. public class UDPListener : IEnableLogger
  23. {
  24. public class UDPState
  25. {
  26. public UDPState(Socket s)
  27. {
  28. socket = s;
  29. remoteEndPoint = new IPEndPoint(s.AddressFamily == AddressFamily.InterNetworkV6 ? IPAddress.IPv6Any : IPAddress.Any, 0);
  30. }
  31. public Socket socket;
  32. public byte[] buffer = new byte[4096];
  33. public EndPoint remoteEndPoint;
  34. }
  35. IPEndPoint _localEndPoint;
  36. Socket _udpSocket;
  37. IEnumerable<IDatagramService> _services;
  38. CancellationTokenSource tokenSource = new CancellationTokenSource();
  39. public UDPListener(IPEndPoint localEndPoint, IEnumerable<IDatagramService> services)
  40. {
  41. _localEndPoint = localEndPoint;
  42. _services = services;
  43. }
  44. private bool CheckIfPortInUse(int port)
  45. {
  46. IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
  47. return ipProperties.GetActiveUdpListeners().Any(endPoint => endPoint.Port == port);
  48. }
  49. public void Start()
  50. {
  51. if (CheckIfPortInUse(_localEndPoint.Port))
  52. throw new Exception($"Port {_localEndPoint.Port} already in use");
  53. // Create a TCP/IP socket.
  54. _udpSocket = new Socket(_localEndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
  55. _udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  56. _udpSocket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);
  57. // Bind the socket to the local endpoint and listen for incoming connections.
  58. _udpSocket.Bind(_localEndPoint);
  59. // Start an asynchronous socket to listen for connections.
  60. this.Log().Info($"Shadowsocks started UDP");
  61. this.Log().Debug(Crypto.CryptoFactory.DumpRegisteredEncryptor());
  62. UDPState udpState = new UDPState(_udpSocket);
  63. // _udpSocket.BeginReceiveFrom(udpState.buffer, 0, udpState.buffer.Length, 0, ref udpState.remoteEndPoint, new AsyncCallback(RecvFromCallback), udpState);
  64. Task.Run(() => WorkLoop(tokenSource.Token));
  65. }
  66. private async Task WorkLoop(CancellationToken token)
  67. {
  68. byte[] buffer = new byte[4096];
  69. EndPoint remote = new IPEndPoint(_udpSocket.AddressFamily == AddressFamily.InterNetworkV6 ? IPAddress.IPv6Any : IPAddress.Any, 0);
  70. while (!token.IsCancellationRequested)
  71. {
  72. var result = await _udpSocket.ReceiveFromAsync(buffer, SocketFlags.None, remote);
  73. var len = result.ReceivedBytes;
  74. foreach (IDatagramService service in _services)
  75. {
  76. if (await service.Handle(new Memory<byte>(buffer)[..len], _udpSocket, result.RemoteEndPoint))
  77. {
  78. break;
  79. }
  80. }
  81. }
  82. }
  83. public void Stop()
  84. {
  85. tokenSource.Cancel();
  86. _udpSocket?.Close();
  87. foreach (var s in _services)
  88. {
  89. s.Stop();
  90. }
  91. }
  92. }
  93. }