Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 

178 Zeilen
7.3 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 MqttServerAdapter : IMqttServerAdapter, IDisposable
  17. {
  18. private readonly IMqttNetLogger _logger;
  19. private CancellationTokenSource _cancellationTokenSource;
  20. private Socket _defaultEndpointSocket;
  21. private Socket _tlsEndpointSocket;
  22. private X509Certificate2 _tlsCertificate;
  23. public MqttServerAdapter(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);
  35. _defaultEndpointSocket.Bind(new IPEndPoint(IPAddress.Any, options.GetDefaultEndpointPort()));
  36. _defaultEndpointSocket.Listen(options.ConnectionBacklog);
  37. Task.Run(async () => await AcceptDefaultEndpointConnectionsAsync(_cancellationTokenSource.Token).ConfigureAwait(false), _cancellationTokenSource.Token).ConfigureAwait(false);
  38. }
  39. if (options.TlsEndpointOptions.IsEnabled)
  40. {
  41. if (options.TlsEndpointOptions.Certificate == null)
  42. {
  43. throw new ArgumentException("TLS certificate is not set.");
  44. }
  45. _tlsCertificate = new X509Certificate2(options.TlsEndpointOptions.Certificate);
  46. if (!_tlsCertificate.HasPrivateKey)
  47. {
  48. throw new InvalidOperationException("The certificate for TLS encryption must contain the private key.");
  49. }
  50. _tlsEndpointSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
  51. _tlsEndpointSocket.Bind(new IPEndPoint(IPAddress.Any, options.GetTlsEndpointPort()));
  52. _tlsEndpointSocket.Listen(options.ConnectionBacklog);
  53. Task.Run(async () => await AcceptTlsEndpointConnectionsAsync(_cancellationTokenSource.Token).ConfigureAwait(false), _cancellationTokenSource.Token).ConfigureAwait(false);
  54. }
  55. return Task.FromResult(0);
  56. }
  57. public Task StopAsync()
  58. {
  59. _cancellationTokenSource?.Cancel(false);
  60. _cancellationTokenSource?.Dispose();
  61. _cancellationTokenSource = null;
  62. _defaultEndpointSocket?.Dispose();
  63. _defaultEndpointSocket = null;
  64. _tlsCertificate = null;
  65. _tlsEndpointSocket?.Dispose();
  66. _tlsEndpointSocket = null;
  67. return Task.FromResult(0);
  68. }
  69. public void Dispose()
  70. {
  71. StopAsync();
  72. }
  73. private async Task AcceptDefaultEndpointConnectionsAsync(CancellationToken cancellationToken)
  74. {
  75. while (!cancellationToken.IsCancellationRequested)
  76. {
  77. try
  78. {
  79. //todo: else branch can be used with min dependency NET46
  80. #if NET452 || NET461
  81. var clientSocket = await Task.Factory.FromAsync(_defaultEndpointSocket.BeginAccept, _defaultEndpointSocket.EndAccept, null).ConfigureAwait(false);
  82. #else
  83. var clientSocket = await _defaultEndpointSocket.AcceptAsync().ConfigureAwait(false);
  84. #endif
  85. var clientAdapter = new MqttChannelAdapter(new MqttTcpChannel(clientSocket, null), new MqttPacketSerializer(), _logger);
  86. ClientAccepted?.Invoke(this, new MqttServerAdapterClientAcceptedEventArgs(clientAdapter));
  87. }
  88. catch (ObjectDisposedException)
  89. {
  90. // It can happen that the listener socket is accessed after the cancellation token is already set and the listener socket is disposed.
  91. }
  92. catch (SocketException exception)
  93. {
  94. if (exception.SocketErrorCode == SocketError.OperationAborted)
  95. {
  96. return;
  97. }
  98. _logger.Error<MqttServerAdapter>(exception, "Error while accepting connection at default endpoint.");
  99. }
  100. catch (Exception exception)
  101. {
  102. _logger.Error<MqttServerAdapter>(exception, "Error while accepting connection at default endpoint.");
  103. }
  104. finally
  105. {
  106. //excessive CPU consumed if in endless loop of socket errors
  107. await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false);
  108. }
  109. }
  110. }
  111. private async Task AcceptTlsEndpointConnectionsAsync(CancellationToken cancellationToken)
  112. {
  113. while (!cancellationToken.IsCancellationRequested)
  114. {
  115. try
  116. {
  117. #if NET452 || NET461
  118. var clientSocket = await Task.Factory.FromAsync(_tlsEndpointSocket.BeginAccept, _tlsEndpointSocket.EndAccept, null).ConfigureAwait(false);
  119. #else
  120. var clientSocket = await _tlsEndpointSocket.AcceptAsync().ConfigureAwait(false);
  121. #endif
  122. var sslStream = new SslStream(new NetworkStream(clientSocket));
  123. await sslStream.AuthenticateAsServerAsync(_tlsCertificate, false, SslProtocols.Tls12, false).ConfigureAwait(false);
  124. var clientAdapter = new MqttChannelAdapter(new MqttTcpChannel(clientSocket, sslStream), new MqttPacketSerializer(), _logger);
  125. ClientAccepted?.Invoke(this, new MqttServerAdapterClientAcceptedEventArgs(clientAdapter));
  126. }
  127. catch (ObjectDisposedException)
  128. {
  129. // It can happen that the listener socket is accessed after the cancellation token is already set and the listener socket is disposed.
  130. }
  131. catch (SocketException exception)
  132. {
  133. if (exception.SocketErrorCode == SocketError.OperationAborted)
  134. {
  135. return;
  136. }
  137. _logger.Error<MqttServerAdapter>(exception, "Error while accepting connection at default endpoint.");
  138. }
  139. catch (Exception exception)
  140. {
  141. _logger.Error<MqttServerAdapter>(exception, "Error while accepting connection at TLS endpoint.");
  142. }
  143. finally
  144. {
  145. //excessive CPU consumed if in endless loop of socket errors
  146. await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false);
  147. }
  148. }
  149. }
  150. }
  151. }
  152. #endif