25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

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