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.
 
 
 
 

177 lines
5.4 KiB

  1. #if NET452 || NET461 || NETSTANDARD1_3 || NETSTANDARD2_0
  2. using System;
  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.Tasks;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Threading;
  11. using MQTTnet.Channel;
  12. using MQTTnet.Client;
  13. namespace MQTTnet.Implementations
  14. {
  15. public sealed class MqttTcpChannel : IMqttChannel
  16. {
  17. private readonly MqttClientTcpOptions _options;
  18. private Socket _socket;
  19. private Stream _stream;
  20. /// <summary>
  21. /// called on client sockets are created in connect
  22. /// </summary>
  23. public MqttTcpChannel(MqttClientTcpOptions options)
  24. {
  25. _options = options ?? throw new ArgumentNullException(nameof(options));
  26. }
  27. /// <summary>
  28. /// called on server, sockets are passed in
  29. /// connect will not be called
  30. /// </summary>
  31. public MqttTcpChannel(Socket socket, SslStream sslStream)
  32. {
  33. _socket = socket ?? throw new ArgumentNullException(nameof(socket));
  34. CreateStream(sslStream);
  35. }
  36. public static Func<X509Certificate, X509Chain, SslPolicyErrors, MqttClientTcpOptions, bool> CustomCertificateValidationCallback { get; set; }
  37. public async Task ConnectAsync(CancellationToken cancellationToken)
  38. {
  39. if (_socket == null)
  40. {
  41. _socket = new Socket(SocketType.Stream, ProtocolType.Tcp) { NoDelay = true };
  42. }
  43. #if NET452 || NET461
  44. await Task.Factory.FromAsync(_socket.BeginConnect, _socket.EndConnect, _options.Server, _options.GetPort(), null).ConfigureAwait(false);
  45. #else
  46. await _socket.ConnectAsync(_options.Server, _options.GetPort()).ConfigureAwait(false);
  47. #endif
  48. SslStream sslStream = null;
  49. if (_options.TlsOptions.UseTls)
  50. {
  51. sslStream = new SslStream(new NetworkStream(_socket, true), false, InternalUserCertificateValidationCallback);
  52. await sslStream.AuthenticateAsClientAsync(_options.Server, LoadCertificates(), SslProtocols.Tls12, _options.TlsOptions.IgnoreCertificateRevocationErrors).ConfigureAwait(false);
  53. }
  54. CreateStream(sslStream);
  55. }
  56. public Task DisconnectAsync()
  57. {
  58. Dispose();
  59. return Task.FromResult(0);
  60. }
  61. public Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  62. {
  63. return _stream.ReadAsync(buffer, offset, count, cancellationToken);
  64. }
  65. public Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  66. {
  67. return _stream.WriteAsync(buffer, offset, count, cancellationToken);
  68. }
  69. public void Dispose()
  70. {
  71. try
  72. {
  73. _stream?.Dispose();
  74. }
  75. catch (ObjectDisposedException)
  76. {
  77. }
  78. catch (NullReferenceException)
  79. {
  80. }
  81. finally
  82. {
  83. _stream = null;
  84. }
  85. try
  86. {
  87. _socket?.Dispose();
  88. }
  89. catch (ObjectDisposedException)
  90. {
  91. }
  92. catch (NullReferenceException)
  93. {
  94. }
  95. finally
  96. {
  97. _socket = null;
  98. }
  99. }
  100. private bool InternalUserCertificateValidationCallback(object sender, X509Certificate x509Certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
  101. {
  102. if (CustomCertificateValidationCallback != null)
  103. {
  104. return CustomCertificateValidationCallback(x509Certificate, chain, sslPolicyErrors, _options);
  105. }
  106. if (sslPolicyErrors == SslPolicyErrors.None)
  107. {
  108. return true;
  109. }
  110. if (chain.ChainStatus.Any(c => c.Status == X509ChainStatusFlags.RevocationStatusUnknown || c.Status == X509ChainStatusFlags.Revoked || c.Status == X509ChainStatusFlags.RevocationStatusUnknown))
  111. {
  112. if (!_options.TlsOptions.IgnoreCertificateRevocationErrors)
  113. {
  114. return false;
  115. }
  116. }
  117. if (chain.ChainStatus.Any(c => c.Status == X509ChainStatusFlags.PartialChain))
  118. {
  119. if (!_options.TlsOptions.IgnoreCertificateChainErrors)
  120. {
  121. return false;
  122. }
  123. }
  124. return _options.TlsOptions.AllowUntrustedCertificates;
  125. }
  126. private X509CertificateCollection LoadCertificates()
  127. {
  128. var certificates = new X509CertificateCollection();
  129. if (_options.TlsOptions.Certificates == null)
  130. {
  131. return certificates;
  132. }
  133. foreach (var certificate in _options.TlsOptions.Certificates)
  134. {
  135. certificates.Add(new X509Certificate2(certificate));
  136. }
  137. return certificates;
  138. }
  139. private void CreateStream(Stream stream)
  140. {
  141. if (stream != null)
  142. {
  143. _stream = stream;
  144. }
  145. else
  146. {
  147. _stream = new NetworkStream(_socket, true);
  148. }
  149. }
  150. }
  151. }
  152. #endif