StunClient5389TCP.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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.Diagnostics.CodeAnalysis;
  10. using System.IO.Pipelines;
  11. using System.Net;
  12. namespace STUN.Client;
  13. public class StunClient5389TCP : IStunClient5389
  14. {
  15. public TimeSpan ConnectTimeout { get; set; } = TimeSpan.FromSeconds(3);
  16. private readonly IPEndPoint _remoteEndPoint;
  17. private IPEndPoint _lastLocalEndPoint;
  18. private readonly ITcpProxy _proxy;
  19. public StunResult5389 State { get; private set; } = new();
  20. public StunClient5389TCP(IPEndPoint server, IPEndPoint local, ITcpProxy? proxy = default)
  21. {
  22. Requires.NotNull(server, nameof(server));
  23. Requires.NotNull(local, nameof(local));
  24. _proxy = proxy ?? new DirectTcpProxy();
  25. _remoteEndPoint = server;
  26. _lastLocalEndPoint = local;
  27. State.LocalEndPoint = local;
  28. }
  29. public async ValueTask QueryAsync(CancellationToken cancellationToken = default)
  30. {
  31. await MappingBehaviorTestAsync(cancellationToken);
  32. State.FilteringBehavior = FilteringBehavior.None;
  33. }
  34. public async ValueTask MappingBehaviorTestAsync(CancellationToken cancellationToken = default)
  35. {
  36. State = new StunResult5389();
  37. // test I
  38. StunResult5389 bindingResult = await BindingTestAsync(cancellationToken);
  39. State = bindingResult with { };
  40. if (State.BindingTestResult is not BindingTestResult.Success)
  41. {
  42. return;
  43. }
  44. if (!HasValidOtherAddress(State.OtherEndPoint))
  45. {
  46. State.MappingBehavior = MappingBehavior.UnsupportedServer;
  47. return;
  48. }
  49. if (Equals(State.PublicEndPoint, State.LocalEndPoint))
  50. {
  51. State.MappingBehavior = MappingBehavior.Direct; // or Endpoint-Independent
  52. return;
  53. }
  54. // test II
  55. StunResult5389 result2 = await MappingBehaviorTestBase2Async();
  56. if (State.MappingBehavior is not MappingBehavior.Unknown)
  57. {
  58. return;
  59. }
  60. // test III
  61. await MappingBehaviorTestBase3Async();
  62. return;
  63. bool HasValidOtherAddress([NotNullWhen(true)] IPEndPoint? other)
  64. {
  65. return other is not null && !Equals(other.Address, _remoteEndPoint.Address) && other.Port != _remoteEndPoint.Port;
  66. }
  67. async ValueTask<StunResult5389> MappingBehaviorTestBase2Async()
  68. {
  69. StunResult5389 result = await BindingTestBaseAsync(new IPEndPoint(State.OtherEndPoint.Address, _remoteEndPoint.Port), cancellationToken);
  70. if (result.BindingTestResult is not BindingTestResult.Success)
  71. {
  72. State.MappingBehavior = MappingBehavior.Fail;
  73. }
  74. else if (Equals(result.PublicEndPoint, State.PublicEndPoint))
  75. {
  76. State.MappingBehavior = MappingBehavior.EndpointIndependent;
  77. }
  78. return result;
  79. }
  80. async ValueTask MappingBehaviorTestBase3Async()
  81. {
  82. StunResult5389 result3 = await BindingTestBaseAsync(State.OtherEndPoint, cancellationToken);
  83. if (result3.BindingTestResult is not BindingTestResult.Success)
  84. {
  85. State.MappingBehavior = MappingBehavior.Fail;
  86. return;
  87. }
  88. State.MappingBehavior = Equals(result3.PublicEndPoint, result2.PublicEndPoint) ? MappingBehavior.AddressDependent : MappingBehavior.AddressAndPortDependent;
  89. }
  90. }
  91. public ValueTask FilteringBehaviorTestAsync(CancellationToken cancellationToken = default)
  92. {
  93. throw new NotSupportedException(@"Filtering test applies only to UDP.");
  94. }
  95. public async ValueTask<StunResult5389> BindingTestAsync(CancellationToken cancellationToken = default)
  96. {
  97. return await BindingTestBaseAsync(_remoteEndPoint, cancellationToken);
  98. }
  99. protected virtual async ValueTask<StunResult5389> BindingTestBaseAsync(IPEndPoint remote, CancellationToken cancellationToken = default)
  100. {
  101. StunResult5389 result = new();
  102. StunMessage5389 test = new()
  103. {
  104. StunMessageType = StunMessageType.BindingRequest
  105. };
  106. StunResponse? response1 = await RequestAsync(test, remote, cancellationToken);
  107. IPEndPoint? mappedAddress1 = response1?.Message.GetXorMappedAddressAttribute();
  108. IPEndPoint? otherAddress = response1?.Message.GetOtherAddressAttribute();
  109. if (response1 is null)
  110. {
  111. result.BindingTestResult = BindingTestResult.Fail;
  112. }
  113. else if (mappedAddress1 is null)
  114. {
  115. result.BindingTestResult = BindingTestResult.UnsupportedServer;
  116. }
  117. else
  118. {
  119. result.BindingTestResult = BindingTestResult.Success;
  120. }
  121. IPEndPoint? local = response1?.Local;
  122. result.LocalEndPoint = local;
  123. result.PublicEndPoint = mappedAddress1;
  124. result.OtherEndPoint = otherAddress;
  125. return result;
  126. }
  127. private async ValueTask<StunResponse?> RequestAsync(StunMessage5389 sendMessage, IPEndPoint remote, CancellationToken cancellationToken)
  128. {
  129. try
  130. {
  131. using CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
  132. cts.CancelAfter(ConnectTimeout);
  133. IDuplexPipe pipe = await _proxy.ConnectAsync(_lastLocalEndPoint, remote, cts.Token);
  134. try
  135. {
  136. int length = sendMessage.WriteTo(pipe.Output.GetSpan(sendMessage.Length));
  137. pipe.Output.Advance(length);
  138. await pipe.Output.FlushAsync(cancellationToken);
  139. StunMessage5389 message = new();
  140. bool success = await ReadPipeAsync(message, pipe.Input);
  141. if (success && message.IsSameTransaction(sendMessage))
  142. {
  143. IPEndPoint? local = _proxy.CurrentLocalEndPoint;
  144. if (local is not null)
  145. {
  146. _lastLocalEndPoint = local;
  147. return new StunResponse(message, remote, local);
  148. }
  149. }
  150. }
  151. finally
  152. {
  153. await _proxy.CloseAsync(cancellationToken);
  154. }
  155. }
  156. catch (OperationCanceledException ex)
  157. {
  158. Debug.WriteLine(ex);
  159. }
  160. return default;
  161. async ValueTask<bool> ReadPipeAsync(StunMessage5389 message, PipeReader reader)
  162. {
  163. try
  164. {
  165. while (true)
  166. {
  167. cancellationToken.ThrowIfCancellationRequested();
  168. ReadResult result = await reader.ReadAsync(cancellationToken);
  169. ReadOnlySequence<byte> buffer = result.Buffer;
  170. try
  171. {
  172. if (message.TryParse(ref buffer))
  173. {
  174. return true;
  175. }
  176. if (result.IsCompleted)
  177. {
  178. break;
  179. }
  180. }
  181. finally
  182. {
  183. reader.AdvanceTo(buffer.Start, buffer.End);
  184. }
  185. }
  186. return false;
  187. }
  188. finally
  189. {
  190. await reader.CompleteAsync();
  191. }
  192. }
  193. }
  194. public void Dispose()
  195. {
  196. _proxy.Dispose();
  197. GC.SuppressFinalize(this);
  198. }
  199. }