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.

MqttServerAdapter.cs 6.2 KiB

7 vuotta sitten
7 vuotta sitten
7 vuotta sitten
7 vuotta sitten
7 vuotta sitten
7 vuotta sitten
7 vuotta sitten
7 vuotta sitten
7 vuotta sitten
7 vuotta sitten
7 vuotta sitten
7 vuotta sitten
7 vuotta sitten
7 vuotta sitten
7 vuotta sitten
7 vuotta sitten
7 vuotta sitten
7 vuotta sitten
7 vuotta sitten
7 vuotta sitten
7 vuotta sitten
7 vuotta sitten
7 vuotta sitten
7 vuotta sitten
7 vuotta sitten
7 vuotta sitten
7 vuotta sitten
7 vuotta sitten
7 vuotta sitten
7 vuotta sitten
7 vuotta sitten
7 vuotta sitten
7 vuotta sitten
7 vuotta sitten
7 vuotta sitten
7 vuotta sitten
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  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.Server;
  11. using Microsoft.Extensions.Logging;
  12. namespace MQTTnet.Implementations
  13. {
  14. public class MqttServerAdapter : IMqttServerAdapter, IDisposable
  15. {
  16. private readonly ILogger<MqttServerAdapter> _logger;
  17. private readonly IMqttCommunicationAdapterFactory _mqttCommunicationAdapterFactory;
  18. private CancellationTokenSource _cancellationTokenSource;
  19. private Socket _defaultEndpointSocket;
  20. private Socket _tlsEndpointSocket;
  21. private X509Certificate2 _tlsCertificate;
  22. public MqttServerAdapter(ILogger<MqttServerAdapter> logger, IMqttCommunicationAdapterFactory mqttCommunicationAdapterFactory)
  23. {
  24. _logger = logger ?? throw new ArgumentNullException(nameof(logger));
  25. _mqttCommunicationAdapterFactory = mqttCommunicationAdapterFactory ?? throw new ArgumentNullException(nameof(mqttCommunicationAdapterFactory));
  26. }
  27. public event EventHandler<MqttServerAdapterClientAcceptedEventArgs> ClientAccepted;
  28. public Task StartAsync(MqttServerOptions 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(() => AcceptDefaultEndpointConnectionsAsync(_cancellationTokenSource.Token), _cancellationTokenSource.Token);
  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(() => AcceptTlsEndpointConnectionsAsync(_cancellationTokenSource.Token), _cancellationTokenSource.Token);
  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 NET451
  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 = _mqttCommunicationAdapterFactory.CreateServerMqttCommunicationAdapter(new MqttTcpChannel(clientSocket, null));
  86. ClientAccepted?.Invoke(this, new MqttServerAdapterClientAcceptedEventArgs(clientAdapter));
  87. }
  88. catch (Exception exception)
  89. {
  90. _logger.LogError(new EventId(), exception, "Error while accepting connection at default endpoint.");
  91. //excessive CPU consumed if in endless loop of socket errors
  92. await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false);
  93. }
  94. }
  95. }
  96. private async Task AcceptTlsEndpointConnectionsAsync(CancellationToken cancellationToken)
  97. {
  98. while (!cancellationToken.IsCancellationRequested)
  99. {
  100. try
  101. {
  102. #if NET451
  103. var clientSocket = await Task.Factory.FromAsync(_tlsEndpointSocket.BeginAccept, _tlsEndpointSocket.EndAccept, null).ConfigureAwait(false);
  104. #else
  105. var clientSocket = await _tlsEndpointSocket.AcceptAsync().ConfigureAwait(false);
  106. #endif
  107. var sslStream = new SslStream(new NetworkStream(clientSocket));
  108. await sslStream.AuthenticateAsServerAsync(_tlsCertificate, false, SslProtocols.Tls12, false).ConfigureAwait(false);
  109. var clientAdapter = _mqttCommunicationAdapterFactory.CreateServerMqttCommunicationAdapter(new MqttTcpChannel(clientSocket, sslStream));
  110. ClientAccepted?.Invoke(this, new MqttServerAdapterClientAcceptedEventArgs(clientAdapter));
  111. }
  112. catch (Exception exception)
  113. {
  114. _logger.LogError(new EventId(), exception, "Error while accepting connection at TLS endpoint.");
  115. //excessive CPU consumed if in endless loop of socket errors
  116. await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false);
  117. }
  118. }
  119. }
  120. }
  121. }