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

172 lines
7.0 KiB

  1. #if NET452 || NET461 || NETSTANDARD1_3 || NETSTANDARD2_0
  2. using System;
  3. using System.Net;
  4. using System.Net.Security;
  5. using System.Net.Sockets;
  6. using System.Security.Authentication;
  7. using System.Security.Cryptography.X509Certificates;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using MQTTnet.Adapter;
  11. using MQTTnet.Diagnostics;
  12. using MQTTnet.Serializer;
  13. using MQTTnet.Server;
  14. namespace MQTTnet.Implementations
  15. {
  16. public class MqttTcpServerAdapter : IMqttServerAdapter
  17. {
  18. private readonly IMqttNetLogger _logger;
  19. private CancellationTokenSource _cancellationTokenSource;
  20. private Socket _defaultEndpointSocket;
  21. private Socket _tlsEndpointSocket;
  22. private X509Certificate2 _tlsCertificate;
  23. public MqttTcpServerAdapter(IMqttNetLogger logger)
  24. {
  25. _logger = logger ?? throw new ArgumentNullException(nameof(logger));
  26. }
  27. public event EventHandler<MqttServerAdapterClientAcceptedEventArgs> ClientAccepted;
  28. public Task StartAsync(IMqttServerOptions options)
  29. {
  30. if (_cancellationTokenSource != null) throw new InvalidOperationException("Server is already started.");
  31. _cancellationTokenSource = new CancellationTokenSource();
  32. if (options.DefaultEndpointOptions.IsEnabled)
  33. {
  34. _defaultEndpointSocket = new Socket(SocketType.Stream, ProtocolType.Tcp) { NoDelay = true };
  35. _defaultEndpointSocket.Bind(new IPEndPoint(options.DefaultEndpointOptions.BoundIPAddress, options.GetDefaultEndpointPort()));
  36. _defaultEndpointSocket.Listen(options.ConnectionBacklog);
  37. Task.Factory.StartNew(
  38. () => AcceptDefaultEndpointConnectionsAsync(_cancellationTokenSource.Token),
  39. _cancellationTokenSource.Token,
  40. TaskCreationOptions.LongRunning,
  41. TaskScheduler.Current);
  42. }
  43. if (options.TlsEndpointOptions.IsEnabled)
  44. {
  45. if (options.TlsEndpointOptions.Certificate == null)
  46. {
  47. throw new ArgumentException("TLS certificate is not set.");
  48. }
  49. _tlsCertificate = new X509Certificate2(options.TlsEndpointOptions.Certificate);
  50. if (!_tlsCertificate.HasPrivateKey)
  51. {
  52. throw new InvalidOperationException("The certificate for TLS encryption must contain the private key.");
  53. }
  54. _tlsEndpointSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
  55. _tlsEndpointSocket.Bind(new IPEndPoint(options.TlsEndpointOptions.BoundIPAddress, options.GetTlsEndpointPort()));
  56. _tlsEndpointSocket.Listen(options.ConnectionBacklog);
  57. Task.Factory.StartNew(
  58. () => AcceptTlsEndpointConnectionsAsync(_cancellationTokenSource.Token),
  59. _cancellationTokenSource.Token,
  60. TaskCreationOptions.LongRunning,
  61. TaskScheduler.Current);
  62. }
  63. return Task.FromResult(0);
  64. }
  65. public Task StopAsync()
  66. {
  67. _cancellationTokenSource?.Cancel(false);
  68. _cancellationTokenSource?.Dispose();
  69. _cancellationTokenSource = null;
  70. _defaultEndpointSocket?.Dispose();
  71. _defaultEndpointSocket = null;
  72. _tlsCertificate = null;
  73. _tlsEndpointSocket?.Dispose();
  74. _tlsEndpointSocket = null;
  75. return Task.FromResult(0);
  76. }
  77. public void Dispose()
  78. {
  79. StopAsync().GetAwaiter().GetResult();
  80. }
  81. private async Task AcceptDefaultEndpointConnectionsAsync(CancellationToken cancellationToken)
  82. {
  83. while (!cancellationToken.IsCancellationRequested)
  84. {
  85. try
  86. {
  87. //todo: else branch can be used with min dependency NET46
  88. #if NET452 || NET461
  89. var clientSocket = await Task.Factory.FromAsync(_defaultEndpointSocket.BeginAccept, _defaultEndpointSocket.EndAccept, null).ConfigureAwait(false);
  90. #else
  91. var clientSocket = await _defaultEndpointSocket.AcceptAsync().ConfigureAwait(false);
  92. #endif
  93. clientSocket.NoDelay = true;
  94. var clientAdapter = new MqttChannelAdapter(new MqttTcpChannel(clientSocket, null), new MqttPacketSerializer(), _logger);
  95. ClientAccepted?.Invoke(this, new MqttServerAdapterClientAcceptedEventArgs(clientAdapter));
  96. }
  97. catch (ObjectDisposedException)
  98. {
  99. // It can happen that the listener socket is accessed after the cancellation token is already set and the listener socket is disposed.
  100. }
  101. catch (Exception exception)
  102. {
  103. if (exception is SocketException s && s.SocketErrorCode == SocketError.OperationAborted)
  104. {
  105. return;
  106. }
  107. _logger.Error<MqttTcpServerAdapter>(exception, "Error while accepting connection at default endpoint.");
  108. await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false);
  109. }
  110. }
  111. }
  112. private async Task AcceptTlsEndpointConnectionsAsync(CancellationToken cancellationToken)
  113. {
  114. while (!cancellationToken.IsCancellationRequested)
  115. {
  116. try
  117. {
  118. #if NET452 || NET461
  119. var clientSocket = await Task.Factory.FromAsync(_tlsEndpointSocket.BeginAccept, _tlsEndpointSocket.EndAccept, null).ConfigureAwait(false);
  120. #else
  121. var clientSocket = await _tlsEndpointSocket.AcceptAsync().ConfigureAwait(false);
  122. #endif
  123. var sslStream = new SslStream(new NetworkStream(clientSocket));
  124. await sslStream.AuthenticateAsServerAsync(_tlsCertificate, false, SslProtocols.Tls12, false).ConfigureAwait(false);
  125. var clientAdapter = new MqttChannelAdapter(new MqttTcpChannel(clientSocket, sslStream), new MqttPacketSerializer(), _logger);
  126. ClientAccepted?.Invoke(this, new MqttServerAdapterClientAcceptedEventArgs(clientAdapter));
  127. }
  128. catch (ObjectDisposedException)
  129. {
  130. // It can happen that the listener socket is accessed after the cancellation token is already set and the listener socket is disposed.
  131. }
  132. catch (Exception exception)
  133. {
  134. if (exception is SocketException s && s.SocketErrorCode == SocketError.OperationAborted)
  135. {
  136. return;
  137. }
  138. _logger.Error<MqttTcpServerAdapter>(exception, "Error while accepting connection at TLS endpoint.");
  139. await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false);
  140. }
  141. }
  142. }
  143. }
  144. }
  145. #endif