StunClient3489.cs 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. using Microsoft;
  2. using STUN.Enums;
  3. using STUN.Messages;
  4. using STUN.Proxy;
  5. using STUN.StunResult;
  6. using STUN.Utils;
  7. using System.Buffers;
  8. using System.Diagnostics;
  9. using System.Net;
  10. using System.Net.Sockets;
  11. namespace STUN.Client;
  12. /// <summary>
  13. /// https://tools.ietf.org/html/rfc3489#section-10.1
  14. /// </summary>
  15. public class StunClient3489 : IUdpStunClient
  16. {
  17. public virtual IPEndPoint LocalEndPoint => (IPEndPoint)_proxy.Client.LocalEndPoint!;
  18. public TimeSpan ReceiveTimeout { get; set; } = TimeSpan.FromSeconds(3);
  19. private readonly IPEndPoint _remoteEndPoint;
  20. private readonly IUdpProxy _proxy;
  21. public ClassicStunResult State { get; private set; } = new();
  22. public StunClient3489(IPEndPoint server, IPEndPoint local, IUdpProxy? proxy = null)
  23. {
  24. Requires.NotNull(server, nameof(server));
  25. Requires.NotNull(local, nameof(local));
  26. _proxy = proxy ?? new NoneUdpProxy(local);
  27. _remoteEndPoint = server;
  28. State.LocalEndPoint = local;
  29. }
  30. public async ValueTask ConnectProxyAsync(CancellationToken cancellationToken = default)
  31. {
  32. using CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
  33. cts.CancelAfter(ReceiveTimeout);
  34. await _proxy.ConnectAsync(cts.Token);
  35. }
  36. public async ValueTask CloseProxyAsync(CancellationToken cancellationToken = default)
  37. {
  38. await _proxy.CloseAsync(cancellationToken);
  39. }
  40. public async ValueTask QueryAsync(CancellationToken cancellationToken = default)
  41. {
  42. State = new ClassicStunResult();
  43. // test I
  44. StunResponse? response1 = await Test1Async(cancellationToken);
  45. if (response1 is null)
  46. {
  47. State.NatType = NatType.UdpBlocked;
  48. return;
  49. }
  50. State.LocalEndPoint = response1.Local;
  51. IPEndPoint? mappedAddress1 = response1.Message.GetMappedAddressAttribute();
  52. IPEndPoint? changedAddress = response1.Message.GetChangedAddressAttribute();
  53. State.PublicEndPoint = mappedAddress1; // 显示 test I 得到的映射地址
  54. // 某些单 IP 服务器的迷惑操作
  55. if (mappedAddress1 is null || changedAddress is null
  56. || Equals(changedAddress.Address, response1.Remote.Address)
  57. || changedAddress.Port == response1.Remote.Port)
  58. {
  59. State.NatType = NatType.UnsupportedServer;
  60. return;
  61. }
  62. // test II
  63. StunResponse? response2 = await Test2Async(changedAddress, cancellationToken);
  64. IPEndPoint? mappedAddress2 = response2?.Message.GetMappedAddressAttribute();
  65. if (response2 is not null)
  66. {
  67. // 有些单 IP 服务器并不能测 NAT 类型
  68. if (Equals(response1.Remote.Address, response2.Remote.Address) || response1.Remote.Port == response2.Remote.Port)
  69. {
  70. State.NatType = NatType.UnsupportedServer;
  71. State.PublicEndPoint = mappedAddress2;
  72. return;
  73. }
  74. }
  75. // is Public IP == link's IP?
  76. if (Equals(mappedAddress1, response1.Local))
  77. {
  78. // No NAT
  79. if (response2 is null)
  80. {
  81. State.NatType = NatType.SymmetricUdpFirewall;
  82. State.PublicEndPoint = mappedAddress1;
  83. }
  84. else
  85. {
  86. State.NatType = NatType.OpenInternet;
  87. State.PublicEndPoint = mappedAddress2;
  88. }
  89. return;
  90. }
  91. // NAT
  92. if (response2 is not null)
  93. {
  94. State.NatType = NatType.FullCone;
  95. State.PublicEndPoint = mappedAddress2;
  96. return;
  97. }
  98. // Test I(#2)
  99. StunResponse? response12 = await Test1_2Async(changedAddress, cancellationToken);
  100. IPEndPoint? mappedAddress12 = response12?.Message.GetMappedAddressAttribute();
  101. if (mappedAddress12 is null)
  102. {
  103. State.NatType = NatType.Unknown;
  104. return;
  105. }
  106. if (!Equals(mappedAddress12, mappedAddress1))
  107. {
  108. State.NatType = NatType.Symmetric;
  109. State.PublicEndPoint = mappedAddress12;
  110. return;
  111. }
  112. // Test III
  113. StunResponse? response3 = await Test3Async(cancellationToken);
  114. if (response3 is not null)
  115. {
  116. IPEndPoint? mappedAddress3 = response3.Message.GetMappedAddressAttribute();
  117. if (mappedAddress3 is not null
  118. && Equals(response3.Remote.Address, response1.Remote.Address)
  119. && response3.Remote.Port != response1.Remote.Port)
  120. {
  121. State.NatType = NatType.RestrictedCone;
  122. State.PublicEndPoint = mappedAddress3;
  123. return;
  124. }
  125. }
  126. State.NatType = NatType.PortRestrictedCone;
  127. State.PublicEndPoint = mappedAddress12;
  128. }
  129. private async ValueTask<StunResponse?> RequestAsync(StunMessage5389 sendMessage, IPEndPoint remote, IPEndPoint receive, CancellationToken cancellationToken)
  130. {
  131. try
  132. {
  133. using IMemoryOwner<byte> memoryOwner = MemoryPool<byte>.Shared.Rent(0x10000);
  134. Memory<byte> buffer = memoryOwner.Memory;
  135. int length = sendMessage.WriteTo(buffer.Span);
  136. await _proxy.SendToAsync(buffer[..length], SocketFlags.None, remote, cancellationToken);
  137. using CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
  138. cts.CancelAfter(ReceiveTimeout);
  139. SocketReceiveMessageFromResult r = await _proxy.ReceiveMessageFromAsync(buffer, SocketFlags.None, receive, cts.Token);
  140. StunMessage5389 message = new();
  141. if (message.TryParse(buffer[..r.ReceivedBytes]) && message.IsSameTransaction(sendMessage))
  142. {
  143. return new StunResponse(message, (IPEndPoint)r.RemoteEndPoint, new IPEndPoint(r.PacketInformation.Address, ((IPEndPoint)_proxy.Client.LocalEndPoint!).Port));
  144. }
  145. }
  146. catch (OperationCanceledException ex)
  147. {
  148. Debug.WriteLine(ex);
  149. }
  150. return default;
  151. }
  152. public virtual async ValueTask<StunResponse?> Test1Async(CancellationToken cancellationToken)
  153. {
  154. StunMessage5389 message = new()
  155. {
  156. StunMessageType = StunMessageType.BindingRequest,
  157. MagicCookie = 0
  158. };
  159. return await RequestAsync(message, _remoteEndPoint, _remoteEndPoint, cancellationToken);
  160. }
  161. public virtual async ValueTask<StunResponse?> Test2Async(IPEndPoint other, CancellationToken cancellationToken)
  162. {
  163. StunMessage5389 message = new()
  164. {
  165. StunMessageType = StunMessageType.BindingRequest,
  166. MagicCookie = 0,
  167. Attributes = new[] { AttributeExtensions.BuildChangeRequest(true, true) }
  168. };
  169. return await RequestAsync(message, _remoteEndPoint, other, cancellationToken);
  170. }
  171. public virtual async ValueTask<StunResponse?> Test1_2Async(IPEndPoint other, CancellationToken cancellationToken)
  172. {
  173. StunMessage5389 message = new()
  174. {
  175. StunMessageType = StunMessageType.BindingRequest,
  176. MagicCookie = 0
  177. };
  178. return await RequestAsync(message, other, other, cancellationToken);
  179. }
  180. public virtual async ValueTask<StunResponse?> Test3Async(CancellationToken cancellationToken)
  181. {
  182. StunMessage5389 message = new()
  183. {
  184. StunMessageType = StunMessageType.BindingRequest,
  185. MagicCookie = 0,
  186. Attributes = new[] { AttributeExtensions.BuildChangeRequest(false, true) }
  187. };
  188. return await RequestAsync(message, _remoteEndPoint, _remoteEndPoint, cancellationToken);
  189. }
  190. public void Dispose()
  191. {
  192. _proxy.Dispose();
  193. GC.SuppressFinalize(this);
  194. }
  195. }