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.
 
 
 
 

162 Zeilen
6.8 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(options.DefaultEndpointOptions.BoundIPAddress, 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(options.TlsEndpointOptions.BoundIPAddress, 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 (Exception exception)
  93. {
  94. if (exception is SocketException s && s.SocketErrorCode == SocketError.OperationAborted)
  95. {
  96. return;
  97. }
  98. _logger.Error<MqttServerAdapter>(exception, "Error while accepting connection at default endpoint.");
  99. await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false);
  100. }
  101. }
  102. }
  103. private async Task AcceptTlsEndpointConnectionsAsync(CancellationToken cancellationToken)
  104. {
  105. while (!cancellationToken.IsCancellationRequested)
  106. {
  107. try
  108. {
  109. #if NET452 || NET461
  110. var clientSocket = await Task.Factory.FromAsync(_tlsEndpointSocket.BeginAccept, _tlsEndpointSocket.EndAccept, null).ConfigureAwait(false);
  111. #else
  112. var clientSocket = await _tlsEndpointSocket.AcceptAsync().ConfigureAwait(false);
  113. #endif
  114. var sslStream = new SslStream(new NetworkStream(clientSocket));
  115. await sslStream.AuthenticateAsServerAsync(_tlsCertificate, false, SslProtocols.Tls12, false).ConfigureAwait(false);
  116. var clientAdapter = new MqttChannelAdapter(new MqttTcpChannel(clientSocket, sslStream), new MqttPacketSerializer(), _logger);
  117. ClientAccepted?.Invoke(this, new MqttServerAdapterClientAcceptedEventArgs(clientAdapter));
  118. }
  119. catch (ObjectDisposedException)
  120. {
  121. // It can happen that the listener socket is accessed after the cancellation token is already set and the listener socket is disposed.
  122. }
  123. catch (Exception exception)
  124. {
  125. if (exception is SocketException s && s.SocketErrorCode == SocketError.OperationAborted)
  126. {
  127. return;
  128. }
  129. _logger.Error<MqttServerAdapter>(exception, "Error while accepting connection at TLS endpoint.");
  130. await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false);
  131. }
  132. }
  133. }
  134. }
  135. }
  136. #endif