MqttChannelAdapter.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. using MQTTnet.Channel;
  2. using MQTTnet.Diagnostics;
  3. using MQTTnet.Exceptions;
  4. using MQTTnet.Formatter;
  5. using MQTTnet.Internal;
  6. using MQTTnet.Packets;
  7. using System;
  8. using System.IO;
  9. using System.Net.Sockets;
  10. using System.Runtime.InteropServices;
  11. using System.Security.Cryptography.X509Certificates;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. namespace MQTTnet.Adapter
  15. {
  16. public sealed class MqttChannelAdapter : Disposable, IMqttChannelAdapter
  17. {
  18. const uint ErrorOperationAborted = 0x800703E3;
  19. const int ReadBufferSize = 4096; // TODO: Move buffer size to config
  20. readonly IMqttNetLogger _logger;
  21. readonly IMqttChannel _channel;
  22. readonly MqttPacketReader _packetReader;
  23. readonly byte[] _fixedHeaderBuffer = new byte[2];
  24. SemaphoreSlim _writerSemaphore = new SemaphoreSlim(1, 1);
  25. long _bytesReceived;
  26. long _bytesSent;
  27. public MqttChannelAdapter(IMqttChannel channel, MqttPacketFormatterAdapter packetFormatterAdapter, IMqttNetLogger logger)
  28. {
  29. if (logger == null) throw new ArgumentNullException(nameof(logger));
  30. _channel = channel ?? throw new ArgumentNullException(nameof(channel));
  31. PacketFormatterAdapter = packetFormatterAdapter ?? throw new ArgumentNullException(nameof(packetFormatterAdapter));
  32. _packetReader = new MqttPacketReader(_channel);
  33. _logger = logger.CreateChildLogger(nameof(MqttChannelAdapter));
  34. }
  35. public string Endpoint => _channel.Endpoint;
  36. public bool IsSecureConnection => _channel.IsSecureConnection;
  37. public X509Certificate2 ClientCertificate => _channel.ClientCertificate;
  38. public MqttPacketFormatterAdapter PacketFormatterAdapter { get; }
  39. public long BytesSent => Interlocked.Read(ref _bytesSent);
  40. public long BytesReceived => Interlocked.Read(ref _bytesReceived);
  41. public Action ReadingPacketStartedCallback { get; set; }
  42. public Action ReadingPacketCompletedCallback { get; set; }
  43. public async Task ConnectAsync(TimeSpan timeout, CancellationToken cancellationToken)
  44. {
  45. ThrowIfDisposed();
  46. try
  47. {
  48. if (timeout == TimeSpan.Zero)
  49. {
  50. await _channel.ConnectAsync(cancellationToken).ConfigureAwait(false);
  51. }
  52. else
  53. {
  54. await MqttTaskTimeout.WaitAsync(t => _channel.ConnectAsync(t), timeout, cancellationToken).ConfigureAwait(false);
  55. }
  56. }
  57. catch (Exception exception)
  58. {
  59. if (IsWrappedException(exception))
  60. {
  61. throw;
  62. }
  63. WrapException(exception);
  64. }
  65. }
  66. public async Task DisconnectAsync(TimeSpan timeout, CancellationToken cancellationToken)
  67. {
  68. ThrowIfDisposed();
  69. try
  70. {
  71. if (timeout == TimeSpan.Zero)
  72. {
  73. await _channel.DisconnectAsync(cancellationToken).ConfigureAwait(false);
  74. }
  75. else
  76. {
  77. await MqttTaskTimeout.WaitAsync(
  78. t => _channel.DisconnectAsync(t), timeout, cancellationToken).ConfigureAwait(false);
  79. }
  80. }
  81. catch (Exception exception)
  82. {
  83. if (IsWrappedException(exception))
  84. {
  85. throw;
  86. }
  87. WrapException(exception);
  88. }
  89. }
  90. public async Task SendPacketAsync(MqttBasePacket packet, TimeSpan timeout, CancellationToken cancellationToken)
  91. {
  92. await _writerSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  93. try
  94. {
  95. var packetData = PacketFormatterAdapter.Encode(packet);
  96. if (timeout == TimeSpan.Zero)
  97. {
  98. await _channel.WriteAsync(packetData.Array, packetData.Offset, packetData.Count, cancellationToken).ConfigureAwait(false);
  99. }
  100. else
  101. {
  102. await MqttTaskTimeout.WaitAsync(
  103. t => _channel.WriteAsync(packetData.Array, packetData.Offset, packetData.Count, t), timeout, cancellationToken).ConfigureAwait(false);
  104. }
  105. Interlocked.Add(ref _bytesReceived, packetData.Count);
  106. PacketFormatterAdapter.FreeBuffer();
  107. _logger.Verbose("TX ({0} bytes) >>> {1}", packetData.Count, packet);
  108. }
  109. catch (Exception exception)
  110. {
  111. if (IsWrappedException(exception))
  112. {
  113. throw;
  114. }
  115. WrapException(exception);
  116. }
  117. finally
  118. {
  119. _writerSemaphore?.Release();
  120. }
  121. }
  122. public async Task<MqttBasePacket> ReceivePacketAsync(TimeSpan timeout, CancellationToken cancellationToken)
  123. {
  124. ThrowIfDisposed();
  125. try
  126. {
  127. ReceivedMqttPacket receivedMqttPacket;
  128. if (timeout == TimeSpan.Zero)
  129. {
  130. receivedMqttPacket = await ReceiveAsync(cancellationToken).ConfigureAwait(false);
  131. }
  132. else
  133. {
  134. receivedMqttPacket = await MqttTaskTimeout.WaitAsync(ReceiveAsync, timeout, cancellationToken).ConfigureAwait(false);
  135. }
  136. if (receivedMqttPacket == null || cancellationToken.IsCancellationRequested)
  137. {
  138. return null;
  139. }
  140. Interlocked.Add(ref _bytesSent, receivedMqttPacket.TotalLength);
  141. if (PacketFormatterAdapter.ProtocolVersion == MqttProtocolVersion.Unknown)
  142. {
  143. PacketFormatterAdapter.DetectProtocolVersion(receivedMqttPacket);
  144. }
  145. var packet = PacketFormatterAdapter.Decode(receivedMqttPacket);
  146. if (packet == null)
  147. {
  148. throw new MqttProtocolViolationException("Received malformed packet.");
  149. }
  150. _logger.Verbose("RX ({0} bytes) <<< {1}", receivedMqttPacket.TotalLength, packet);
  151. return packet;
  152. }
  153. catch (OperationCanceledException)
  154. {
  155. }
  156. catch (Exception exception)
  157. {
  158. if (IsWrappedException(exception))
  159. {
  160. throw;
  161. }
  162. WrapException(exception);
  163. }
  164. return null;
  165. }
  166. public void ResetStatistics()
  167. {
  168. Interlocked.Exchange(ref _bytesReceived, 0L);
  169. Interlocked.Exchange(ref _bytesSent, 0L);
  170. }
  171. protected override void Dispose(bool disposing)
  172. {
  173. if (disposing)
  174. {
  175. _channel?.Dispose();
  176. _writerSemaphore?.Dispose();
  177. _writerSemaphore = null;
  178. }
  179. base.Dispose(disposing);
  180. }
  181. async Task<ReceivedMqttPacket> ReceiveAsync(CancellationToken cancellationToken)
  182. {
  183. var readFixedHeaderResult = await _packetReader.ReadFixedHeaderAsync(_fixedHeaderBuffer, cancellationToken).ConfigureAwait(false);
  184. if (cancellationToken.IsCancellationRequested)
  185. {
  186. return null;
  187. }
  188. try
  189. {
  190. if (readFixedHeaderResult.ConnectionClosed)
  191. {
  192. return null;
  193. }
  194. ReadingPacketStartedCallback?.Invoke();
  195. var fixedHeader = readFixedHeaderResult.FixedHeader;
  196. if (fixedHeader.RemainingLength == 0)
  197. {
  198. return new ReceivedMqttPacket(fixedHeader.Flags, null, 2);
  199. }
  200. var body = new byte[fixedHeader.RemainingLength];
  201. var bodyOffset = 0;
  202. var chunkSize = Math.Min(ReadBufferSize, fixedHeader.RemainingLength);
  203. do
  204. {
  205. var bytesLeft = body.Length - bodyOffset;
  206. if (chunkSize > bytesLeft)
  207. {
  208. chunkSize = bytesLeft;
  209. }
  210. var readBytes = await _channel.ReadAsync(body, bodyOffset, chunkSize, cancellationToken).ConfigureAwait(false);
  211. if (cancellationToken.IsCancellationRequested)
  212. {
  213. return null;
  214. }
  215. if (readBytes == 0)
  216. {
  217. return null;
  218. }
  219. bodyOffset += readBytes;
  220. } while (bodyOffset < body.Length);
  221. var bodyReader = new MqttPacketBodyReader(body, 0, body.Length);
  222. return new ReceivedMqttPacket(fixedHeader.Flags, bodyReader, fixedHeader.TotalLength);
  223. }
  224. finally
  225. {
  226. ReadingPacketCompletedCallback?.Invoke();
  227. }
  228. }
  229. static bool IsWrappedException(Exception exception)
  230. {
  231. return exception is OperationCanceledException ||
  232. exception is MqttCommunicationTimedOutException ||
  233. exception is MqttCommunicationException;
  234. }
  235. static void WrapException(Exception exception)
  236. {
  237. if (exception is IOException && exception.InnerException is SocketException innerException)
  238. {
  239. exception = innerException;
  240. }
  241. if (exception is SocketException socketException)
  242. {
  243. if (socketException.SocketErrorCode == SocketError.ConnectionAborted ||
  244. socketException.SocketErrorCode == SocketError.OperationAborted)
  245. {
  246. throw new OperationCanceledException();
  247. }
  248. }
  249. if (exception is COMException comException)
  250. {
  251. if ((uint)comException.HResult == ErrorOperationAborted)
  252. {
  253. throw new OperationCanceledException();
  254. }
  255. }
  256. throw new MqttCommunicationException(exception);
  257. }
  258. }
  259. }