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.
 
 
 
 

147 rivejä
6.2 KiB

  1. using System;
  2. using System.Net;
  3. using System.Net.Security;
  4. using System.Net.Sockets;
  5. using System.Security.Authentication;
  6. using System.Security.Cryptography.X509Certificates;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using MQTTnet.Core.Adapter;
  10. using MQTTnet.Core.Serializer;
  11. using MQTTnet.Core.Server;
  12. using Microsoft.Extensions.Logging;
  13. using MQTTnet.Core.Client;
  14. namespace MQTTnet.Implementations
  15. {
  16. public class MqttServerAdapter : IMqttServerAdapter, IDisposable
  17. {
  18. private readonly ILogger<MqttServerAdapter> _logger;
  19. private readonly IMqttCommunicationAdapterFactory _mqttCommunicationAdapterFactory;
  20. private CancellationTokenSource _cancellationTokenSource;
  21. private Socket _defaultEndpointSocket;
  22. private Socket _tlsEndpointSocket;
  23. private X509Certificate2 _tlsCertificate;
  24. public MqttServerAdapter(ILogger<MqttServerAdapter> logger, IMqttCommunicationAdapterFactory mqttCommunicationAdapterFactory)
  25. {
  26. _logger = logger ?? throw new ArgumentNullException(nameof(logger));
  27. _mqttCommunicationAdapterFactory = mqttCommunicationAdapterFactory ?? throw new ArgumentNullException(nameof(mqttCommunicationAdapterFactory));
  28. }
  29. public event EventHandler<MqttServerAdapterClientAcceptedEventArgs> ClientAccepted;
  30. public Task StartAsync(MqttServerOptions options)
  31. {
  32. if (_cancellationTokenSource != null) throw new InvalidOperationException("Server is already started.");
  33. _cancellationTokenSource = new CancellationTokenSource();
  34. if (options.DefaultEndpointOptions.IsEnabled)
  35. {
  36. _defaultEndpointSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
  37. _defaultEndpointSocket.Bind(new IPEndPoint(IPAddress.Any, options.GetDefaultEndpointPort()));
  38. _defaultEndpointSocket.Listen(options.ConnectionBacklog);
  39. Task.Run(() => AcceptDefaultEndpointConnectionsAsync(_cancellationTokenSource.Token), _cancellationTokenSource.Token);
  40. }
  41. if (options.TlsEndpointOptions.IsEnabled)
  42. {
  43. if (options.TlsEndpointOptions.Certificate == null)
  44. {
  45. throw new ArgumentException("TLS certificate is not set.");
  46. }
  47. _tlsCertificate = new X509Certificate2(options.TlsEndpointOptions.Certificate);
  48. if (!_tlsCertificate.HasPrivateKey)
  49. {
  50. throw new InvalidOperationException("The certificate for TLS encryption must contain the private key.");
  51. }
  52. _tlsEndpointSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
  53. _tlsEndpointSocket.Bind(new IPEndPoint(IPAddress.Any, options.GetTlsEndpointPort()));
  54. _tlsEndpointSocket.Listen(options.ConnectionBacklog);
  55. Task.Run(() => AcceptTlsEndpointConnectionsAsync(_cancellationTokenSource.Token), _cancellationTokenSource.Token);
  56. }
  57. return Task.FromResult(0);
  58. }
  59. public Task StopAsync()
  60. {
  61. _cancellationTokenSource?.Cancel(false);
  62. _cancellationTokenSource?.Dispose();
  63. _cancellationTokenSource = null;
  64. _defaultEndpointSocket?.Dispose();
  65. _defaultEndpointSocket = null;
  66. _tlsCertificate = null;
  67. _tlsEndpointSocket?.Dispose();
  68. _tlsEndpointSocket = null;
  69. return Task.FromResult(0);
  70. }
  71. public void Dispose()
  72. {
  73. StopAsync();
  74. }
  75. private async Task AcceptDefaultEndpointConnectionsAsync(CancellationToken cancellationToken)
  76. {
  77. while (!cancellationToken.IsCancellationRequested)
  78. {
  79. try
  80. {
  81. //todo: else branch can be used with min dependency NET46
  82. #if NET451
  83. var clientSocket = await Task.Factory.FromAsync(_defaultEndpointSocket.BeginAccept, _defaultEndpointSocket.EndAccept, null).ConfigureAwait(false);
  84. #else
  85. var clientSocket = await _defaultEndpointSocket.AcceptAsync().ConfigureAwait(false);
  86. #endif
  87. var clientAdapter = _mqttCommunicationAdapterFactory.CreateServerMqttCommunicationAdapter(new MqttTcpChannel(clientSocket, null));
  88. ClientAccepted?.Invoke(this, new MqttServerAdapterClientAcceptedEventArgs(clientAdapter));
  89. }
  90. catch (Exception exception)
  91. {
  92. _logger.LogError(new EventId(), exception, "Error while accepting connection at default endpoint.");
  93. //excessive CPU consumed if in endless loop of socket errors
  94. await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false);
  95. }
  96. }
  97. }
  98. private async Task AcceptTlsEndpointConnectionsAsync(CancellationToken cancellationToken)
  99. {
  100. while (!cancellationToken.IsCancellationRequested)
  101. {
  102. try
  103. {
  104. #if NET451
  105. var clientSocket = await Task.Factory.FromAsync(_tlsEndpointSocket.BeginAccept, _tlsEndpointSocket.EndAccept, null).ConfigureAwait(false);
  106. #else
  107. var clientSocket = await _tlsEndpointSocket.AcceptAsync().ConfigureAwait(false);
  108. #endif
  109. var sslStream = new SslStream(new NetworkStream(clientSocket));
  110. await sslStream.AuthenticateAsServerAsync(_tlsCertificate, false, SslProtocols.Tls12, false).ConfigureAwait(false);
  111. var clientAdapter = _mqttCommunicationAdapterFactory.CreateServerMqttCommunicationAdapter(new MqttTcpChannel(clientSocket, sslStream));
  112. ClientAccepted?.Invoke(this, new MqttServerAdapterClientAcceptedEventArgs(clientAdapter));
  113. }
  114. catch (Exception exception)
  115. {
  116. _logger.LogError(new EventId(), exception, "Error while accepting connection at TLS endpoint.");
  117. //excessive CPU consumed if in endless loop of socket errors
  118. await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false);
  119. }
  120. }
  121. }
  122. }
  123. }