MqttTcpServerAdapter.cs 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. #if !WINDOWS_UWP
  2. using MQTTnet.Adapter;
  3. using MQTTnet.Diagnostics;
  4. using MQTTnet.Internal;
  5. using MQTTnet.Server;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Net;
  9. using System.Net.Sockets;
  10. using System.Security.Cryptography.X509Certificates;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. namespace MQTTnet.Implementations
  14. {
  15. public sealed class MqttTcpServerAdapter : Disposable, IMqttServerAdapter
  16. {
  17. readonly List<MqttTcpServerListener> _listeners = new List<MqttTcpServerListener>();
  18. readonly IMqttNetLogger _logger;
  19. CancellationTokenSource _cancellationTokenSource;
  20. public MqttTcpServerAdapter(IMqttNetLogger logger)
  21. {
  22. if (logger == null) throw new ArgumentNullException(nameof(logger));
  23. _logger = logger.CreateChildLogger(nameof(MqttTcpServerAdapter));
  24. }
  25. public Func<IMqttChannelAdapter, Task> ClientHandler { get; set; }
  26. public bool TreatSocketOpeningErrorAsWarning { get; set; }
  27. public Task StartAsync(IMqttServerOptions options)
  28. {
  29. if (_cancellationTokenSource != null) throw new InvalidOperationException("Server is already started.");
  30. _cancellationTokenSource = new CancellationTokenSource();
  31. if (options.DefaultEndpointOptions.IsEnabled)
  32. {
  33. RegisterListeners(options.DefaultEndpointOptions, null, _cancellationTokenSource.Token);
  34. }
  35. if (options.TlsEndpointOptions?.IsEnabled == true)
  36. {
  37. if (options.TlsEndpointOptions.Certificate == null)
  38. {
  39. throw new ArgumentException("TLS certificate is not set.");
  40. }
  41. X509Certificate2 tlsCertificate;
  42. if (string.IsNullOrEmpty(options.TlsEndpointOptions.CertificateCredentials?.Password))
  43. {
  44. // Use a different overload when no password is specified. Otherwise the constructor will fail.
  45. tlsCertificate = new X509Certificate2(options.TlsEndpointOptions.Certificate);
  46. }
  47. else
  48. {
  49. tlsCertificate = new X509Certificate2(options.TlsEndpointOptions.Certificate, options.TlsEndpointOptions.CertificateCredentials.Password);
  50. }
  51. if (!tlsCertificate.HasPrivateKey)
  52. {
  53. throw new InvalidOperationException("The certificate for TLS encryption must contain the private key.");
  54. }
  55. RegisterListeners(options.TlsEndpointOptions, tlsCertificate, _cancellationTokenSource.Token);
  56. }
  57. return Task.FromResult(0);
  58. }
  59. public Task StopAsync()
  60. {
  61. Cleanup();
  62. return Task.FromResult(0);
  63. }
  64. protected override void Dispose(bool disposing)
  65. {
  66. if (disposing)
  67. {
  68. Cleanup();
  69. }
  70. base.Dispose(disposing);
  71. }
  72. void Cleanup()
  73. {
  74. _cancellationTokenSource?.Cancel(false);
  75. _cancellationTokenSource?.Dispose();
  76. _cancellationTokenSource = null;
  77. foreach (var listener in _listeners)
  78. {
  79. listener.Dispose();
  80. }
  81. _listeners.Clear();
  82. }
  83. void RegisterListeners(MqttServerTcpEndpointBaseOptions options, X509Certificate2 tlsCertificate, CancellationToken cancellationToken)
  84. {
  85. if (!options.BoundInterNetworkAddress.Equals(IPAddress.None))
  86. {
  87. var listenerV4 = new MqttTcpServerListener(
  88. AddressFamily.InterNetwork,
  89. options,
  90. tlsCertificate,
  91. _logger)
  92. {
  93. ClientHandler = OnClientAcceptedAsync
  94. };
  95. if (listenerV4.Start(TreatSocketOpeningErrorAsWarning, cancellationToken))
  96. {
  97. _listeners.Add(listenerV4);
  98. }
  99. }
  100. if (!options.BoundInterNetworkV6Address.Equals(IPAddress.None))
  101. {
  102. var listenerV6 = new MqttTcpServerListener(
  103. AddressFamily.InterNetworkV6,
  104. options,
  105. tlsCertificate,
  106. _logger)
  107. {
  108. ClientHandler = OnClientAcceptedAsync
  109. };
  110. if (listenerV6.Start(TreatSocketOpeningErrorAsWarning, cancellationToken))
  111. {
  112. _listeners.Add(listenerV6);
  113. }
  114. }
  115. }
  116. private Task OnClientAcceptedAsync(IMqttChannelAdapter channelAdapter)
  117. {
  118. var clientHandler = ClientHandler;
  119. if (clientHandler == null)
  120. {
  121. return Task.FromResult(0);
  122. }
  123. return clientHandler(channelAdapter);
  124. }
  125. }
  126. }
  127. #endif