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.
 
 
 
 

169 regels
5.6 KiB

  1. #if WINDOWS_UWP
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Runtime.InteropServices.WindowsRuntime;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using Windows.Networking;
  10. using Windows.Networking.Sockets;
  11. using Windows.Security.Cryptography.Certificates;
  12. using MQTTnet.Channel;
  13. using MQTTnet.Client;
  14. namespace MQTTnet.Implementations
  15. {
  16. public class MqttTcpChannel : IMqttChannel
  17. {
  18. // ReSharper disable once MemberCanBePrivate.Global
  19. // ReSharper disable once AutoPropertyCanBeMadeGetOnly.Global
  20. public static int BufferSize { get; set; } = 4096; // Can be changed for fine tuning by library user.
  21. private readonly int _bufferSize = BufferSize;
  22. private readonly MqttClientTcpOptions _options;
  23. private StreamSocket _socket;
  24. private Stream _readStream;
  25. private Stream _writeStream;
  26. public MqttTcpChannel(MqttClientTcpOptions options)
  27. {
  28. _options = options ?? throw new ArgumentNullException(nameof(options));
  29. _bufferSize = options.BufferSize;
  30. }
  31. public MqttTcpChannel(StreamSocket socket)
  32. {
  33. _socket = socket ?? throw new ArgumentNullException(nameof(socket));
  34. CreateStreams();
  35. }
  36. public static Func<MqttClientTcpOptions, IEnumerable<ChainValidationResult>> CustomIgnorableServerCertificateErrorsResolver { get; set; }
  37. public string Endpoint => _socket?.Information?.RemoteAddress?.ToString(); // TODO: Check if contains also the port.
  38. public async Task ConnectAsync(CancellationToken cancellationToken)
  39. {
  40. if (_socket == null)
  41. {
  42. _socket = new StreamSocket();
  43. _socket.Control.NoDelay = true;
  44. _socket.Control.KeepAlive = true;
  45. }
  46. if (!_options.TlsOptions.UseTls)
  47. {
  48. await _socket.ConnectAsync(new HostName(_options.Server), _options.GetPort().ToString());
  49. }
  50. else
  51. {
  52. _socket.Control.ClientCertificate = LoadCertificate(_options);
  53. foreach (var ignorableChainValidationResult in ResolveIgnorableServerCertificateErrors())
  54. {
  55. _socket.Control.IgnorableServerCertificateErrors.Add(ignorableChainValidationResult);
  56. }
  57. await _socket.ConnectAsync(new HostName(_options.Server), _options.GetPort().ToString(), SocketProtectionLevel.Tls12);
  58. }
  59. CreateStreams();
  60. }
  61. public Task DisconnectAsync()
  62. {
  63. Dispose();
  64. return Task.FromResult(0);
  65. }
  66. public Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  67. {
  68. return _readStream.ReadAsync(buffer, offset, count, cancellationToken);
  69. }
  70. public async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  71. {
  72. await _writeStream.WriteAsync(buffer, offset, count, cancellationToken);
  73. await _writeStream.FlushAsync(cancellationToken);
  74. }
  75. public void Dispose()
  76. {
  77. TryDispose(_readStream, () => _readStream = null);
  78. TryDispose(_writeStream, () => _writeStream = null);
  79. TryDispose(_socket, () => _socket = null);
  80. }
  81. private static Certificate LoadCertificate(MqttClientTcpOptions options)
  82. {
  83. if (options.TlsOptions.Certificates == null || !options.TlsOptions.Certificates.Any())
  84. {
  85. return null;
  86. }
  87. if (options.TlsOptions.Certificates.Count > 1)
  88. {
  89. throw new NotSupportedException("Only one client certificate is supported for UWP.");
  90. }
  91. return new Certificate(options.TlsOptions.Certificates.First().AsBuffer());
  92. }
  93. private IEnumerable<ChainValidationResult> ResolveIgnorableServerCertificateErrors()
  94. {
  95. if (CustomIgnorableServerCertificateErrorsResolver != null)
  96. {
  97. return CustomIgnorableServerCertificateErrorsResolver(_options);
  98. }
  99. var result = new List<ChainValidationResult>();
  100. if (_options.TlsOptions.IgnoreCertificateRevocationErrors)
  101. {
  102. result.Add(ChainValidationResult.RevocationInformationMissing);
  103. //_socket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Revoked); Not supported.
  104. result.Add(ChainValidationResult.RevocationFailure);
  105. }
  106. if (_options.TlsOptions.IgnoreCertificateChainErrors)
  107. {
  108. result.Add(ChainValidationResult.IncompleteChain);
  109. }
  110. if (_options.TlsOptions.AllowUntrustedCertificates)
  111. {
  112. result.Add(ChainValidationResult.Untrusted);
  113. }
  114. return result;
  115. }
  116. private void CreateStreams()
  117. {
  118. _readStream = _socket.InputStream.AsStreamForRead(_bufferSize);
  119. _writeStream = _socket.OutputStream.AsStreamForWrite(_bufferSize);
  120. }
  121. private static void TryDispose(IDisposable disposable, Action afterDispose)
  122. {
  123. try
  124. {
  125. disposable?.Dispose();
  126. }
  127. catch (ObjectDisposedException)
  128. {
  129. }
  130. catch (NullReferenceException)
  131. {
  132. }
  133. finally
  134. {
  135. afterDispose();
  136. }
  137. }
  138. }
  139. }
  140. #endif