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.
 
 
 
 

350 lines
14 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using MQTTnet.Adapter;
  6. using MQTTnet.Client;
  7. using MQTTnet.Diagnostics;
  8. using MQTTnet.Exceptions;
  9. using MQTTnet.Internal;
  10. using MQTTnet.Packets;
  11. using MQTTnet.Protocol;
  12. using MQTTnet.Serializer;
  13. namespace MQTTnet.Server
  14. {
  15. public sealed class MqttClientSession : IDisposable
  16. {
  17. private readonly MqttPacketIdentifierProvider _packetIdentifierProvider = new MqttPacketIdentifierProvider();
  18. private readonly IMqttServerOptions _options;
  19. private readonly IMqttNetLogger _logger;
  20. private readonly MqttRetainedMessagesManager _retainedMessagesManager;
  21. private IMqttChannelAdapter _adapter;
  22. private CancellationTokenSource _cancellationTokenSource;
  23. private MqttApplicationMessage _willMessage;
  24. private bool _wasCleanDisconnect;
  25. public MqttClientSession(
  26. string clientId,
  27. IMqttServerOptions options,
  28. MqttRetainedMessagesManager retainedMessagesManager,
  29. IMqttNetLogger logger)
  30. {
  31. _options = options ?? throw new ArgumentNullException(nameof(options));
  32. _retainedMessagesManager = retainedMessagesManager ?? throw new ArgumentNullException(nameof(retainedMessagesManager));
  33. _logger = logger ?? throw new ArgumentNullException(nameof(logger));
  34. ClientId = clientId;
  35. KeepAliveMonitor = new MqttClientKeepAliveMonitor(clientId, StopDueToKeepAliveTimeoutAsync, _logger);
  36. SubscriptionsManager = new MqttClientSubscriptionsManager(_options, clientId);
  37. PendingMessagesQueue = new MqttClientPendingMessagesQueue(_options, this, _logger);
  38. }
  39. public Func<MqttClientSession, MqttApplicationMessage, Task> ApplicationMessageReceivedCallback { get; set; }
  40. public MqttClientSubscriptionsManager SubscriptionsManager { get; }
  41. public MqttClientPendingMessagesQueue PendingMessagesQueue { get; }
  42. public MqttClientKeepAliveMonitor KeepAliveMonitor { get; }
  43. public string ClientId { get; }
  44. public MqttProtocolVersion? ProtocolVersion => _adapter?.PacketSerializer.ProtocolVersion;
  45. public bool IsConnected => _adapter != null;
  46. public async Task<bool> RunAsync(MqttConnectPacket connectPacket, IMqttChannelAdapter adapter)
  47. {
  48. if (connectPacket == null) throw new ArgumentNullException(nameof(connectPacket));
  49. if (adapter == null) throw new ArgumentNullException(nameof(adapter));
  50. try
  51. {
  52. var cancellationTokenSource = new CancellationTokenSource();
  53. _wasCleanDisconnect = false;
  54. _willMessage = connectPacket.WillMessage;
  55. _adapter = adapter;
  56. _cancellationTokenSource = cancellationTokenSource;
  57. PendingMessagesQueue.Start(adapter, cancellationTokenSource.Token);
  58. KeepAliveMonitor.Start(connectPacket.KeepAlivePeriod, cancellationTokenSource.Token);
  59. await ReceivePacketsAsync(adapter, cancellationTokenSource.Token).ConfigureAwait(false);
  60. }
  61. catch (OperationCanceledException)
  62. {
  63. }
  64. catch (MqttCommunicationException exception)
  65. {
  66. _logger.Warning<MqttClientSession>(exception, "Client '{0}': Communication exception while processing client packets.", ClientId);
  67. }
  68. catch (Exception exception)
  69. {
  70. _logger.Error<MqttClientSession>(exception, "Client '{0}': Unhandled exception while processing client packets.", ClientId);
  71. }
  72. return _wasCleanDisconnect;
  73. }
  74. public async Task StopAsync(MqttClientDisconnectType type)
  75. {
  76. try
  77. {
  78. if (_cancellationTokenSource == null)
  79. {
  80. return;
  81. }
  82. _wasCleanDisconnect = type == MqttClientDisconnectType.Clean;
  83. _cancellationTokenSource?.Cancel(false);
  84. PendingMessagesQueue.WaitForCompletion();
  85. KeepAliveMonitor.WaitForCompletion();
  86. _cancellationTokenSource?.Dispose();
  87. _cancellationTokenSource = null;
  88. _adapter = null;
  89. _logger.Info<MqttClientSession>("Client '{0}': Session stopped.", ClientId);
  90. }
  91. finally
  92. {
  93. var willMessage = _willMessage;
  94. _willMessage = null; // clear willmessage so it is send just once
  95. if (willMessage != null && !_wasCleanDisconnect)
  96. {
  97. await ApplicationMessageReceivedCallback(this, willMessage).ConfigureAwait(false);
  98. }
  99. }
  100. }
  101. public async Task EnqueueApplicationMessageAsync(MqttApplicationMessage applicationMessage)
  102. {
  103. if (applicationMessage == null) throw new ArgumentNullException(nameof(applicationMessage));
  104. var result = await SubscriptionsManager.CheckSubscriptionsAsync(applicationMessage);
  105. if (!result.IsSubscribed)
  106. {
  107. return;
  108. }
  109. var publishPacket = applicationMessage.ToPublishPacket();
  110. publishPacket.QualityOfServiceLevel = result.QualityOfServiceLevel;
  111. if (publishPacket.QualityOfServiceLevel > 0)
  112. {
  113. publishPacket.PacketIdentifier = _packetIdentifierProvider.GetNewPacketIdentifier();
  114. }
  115. PendingMessagesQueue.Enqueue(publishPacket);
  116. }
  117. public async Task SubscribeAsync(IList<TopicFilter> topicFilters)
  118. {
  119. if (topicFilters == null) throw new ArgumentNullException(nameof(topicFilters));
  120. await SubscriptionsManager.SubscribeAsync(new MqttSubscribePacket
  121. {
  122. TopicFilters = topicFilters
  123. }).ConfigureAwait(false);
  124. await EnqueueSubscribedRetainedMessagesAsync(topicFilters).ConfigureAwait(false);
  125. }
  126. public Task UnsubscribeAsync(IList<string> topicFilters)
  127. {
  128. if (topicFilters == null) throw new ArgumentNullException(nameof(topicFilters));
  129. return SubscriptionsManager.UnsubscribeAsync(new MqttUnsubscribePacket
  130. {
  131. TopicFilters = topicFilters
  132. });
  133. }
  134. public void Dispose()
  135. {
  136. ApplicationMessageReceivedCallback = null;
  137. SubscriptionsManager?.Dispose();
  138. PendingMessagesQueue?.Dispose();
  139. _cancellationTokenSource?.Dispose();
  140. }
  141. private Task StopDueToKeepAliveTimeoutAsync()
  142. {
  143. _logger.Info<MqttClientSession>("Client '{0}': Timeout while waiting for KeepAlive packet.", ClientId);
  144. return StopAsync(MqttClientDisconnectType.NotClean);
  145. }
  146. private async Task ReceivePacketsAsync(IMqttChannelAdapter adapter, CancellationToken cancellationToken)
  147. {
  148. try
  149. {
  150. while (!cancellationToken.IsCancellationRequested)
  151. {
  152. var packet = await adapter.ReceivePacketAsync(TimeSpan.Zero, cancellationToken).ConfigureAwait(false);
  153. KeepAliveMonitor.PacketReceived(packet);
  154. await ProcessReceivedPacketAsync(adapter, packet, cancellationToken).ConfigureAwait(false);
  155. }
  156. }
  157. catch (OperationCanceledException)
  158. {
  159. }
  160. catch (Exception exception)
  161. {
  162. if (exception is MqttCommunicationException)
  163. {
  164. _logger.Warning<MqttClientSession>(exception, "Client '{0}': Communication exception while processing client packets.", ClientId);
  165. }
  166. else
  167. {
  168. _logger.Error<MqttClientSession>(exception, "Client '{0}': Unhandled exception while processing client packets.", ClientId);
  169. }
  170. await StopAsync(MqttClientDisconnectType.NotClean).ConfigureAwait(false);
  171. }
  172. }
  173. private Task ProcessReceivedPacketAsync(IMqttChannelAdapter adapter, MqttBasePacket packet, CancellationToken cancellationToken)
  174. {
  175. if (packet is MqttPublishPacket publishPacket)
  176. {
  177. return HandleIncomingPublishPacketAsync(adapter, publishPacket, cancellationToken);
  178. }
  179. if (packet is MqttPingReqPacket)
  180. {
  181. return adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken, new[] { new MqttPingRespPacket() });
  182. }
  183. if (packet is MqttPubRelPacket pubRelPacket)
  184. {
  185. return HandleIncomingPubRelPacketAsync(adapter, pubRelPacket, cancellationToken);
  186. }
  187. if (packet is MqttPubRecPacket pubRecPacket)
  188. {
  189. var responsePacket = new MqttPubRelPacket
  190. {
  191. PacketIdentifier = pubRecPacket.PacketIdentifier
  192. };
  193. return adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken, new[] { responsePacket });
  194. }
  195. if (packet is MqttPubAckPacket || packet is MqttPubCompPacket)
  196. {
  197. // Discard message.
  198. return Task.FromResult(0);
  199. }
  200. if (packet is MqttSubscribePacket subscribePacket)
  201. {
  202. return HandleIncomingSubscribePacketAsync(adapter, subscribePacket, cancellationToken);
  203. }
  204. if (packet is MqttUnsubscribePacket unsubscribePacket)
  205. {
  206. return HandleIncomingUnsubscribePacketAsync(adapter, unsubscribePacket, cancellationToken);
  207. }
  208. if (packet is MqttDisconnectPacket)
  209. {
  210. return StopAsync(MqttClientDisconnectType.Clean);
  211. }
  212. if (packet is MqttConnectPacket)
  213. {
  214. return StopAsync(MqttClientDisconnectType.NotClean);
  215. }
  216. _logger.Warning<MqttClientSession>("Client '{0}': Received not supported packet ({1}). Closing connection.", ClientId, packet);
  217. return StopAsync(MqttClientDisconnectType.NotClean);
  218. }
  219. private async Task HandleIncomingSubscribePacketAsync(IMqttChannelAdapter adapter, MqttSubscribePacket subscribePacket, CancellationToken cancellationToken)
  220. {
  221. var subscribeResult = await SubscriptionsManager.SubscribeAsync(subscribePacket).ConfigureAwait(false);
  222. await adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken, new[] { subscribeResult.ResponsePacket }).ConfigureAwait(false);
  223. if (subscribeResult.CloseConnection)
  224. {
  225. await StopAsync(MqttClientDisconnectType.NotClean).ConfigureAwait(false);
  226. }
  227. await EnqueueSubscribedRetainedMessagesAsync(subscribePacket.TopicFilters).ConfigureAwait(false);
  228. }
  229. private async Task HandleIncomingUnsubscribePacketAsync(IMqttChannelAdapter adapter, MqttUnsubscribePacket unsubscribePacket, CancellationToken cancellationToken)
  230. {
  231. var unsubscribeResult = await SubscriptionsManager.UnsubscribeAsync(unsubscribePacket).ConfigureAwait(false);
  232. await adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken, new[] { unsubscribeResult });
  233. }
  234. private async Task EnqueueSubscribedRetainedMessagesAsync(ICollection<TopicFilter> topicFilters)
  235. {
  236. var retainedMessages = await _retainedMessagesManager.GetSubscribedMessagesAsync(topicFilters);
  237. foreach (var applicationMessage in retainedMessages)
  238. {
  239. await EnqueueApplicationMessageAsync(applicationMessage).ConfigureAwait(false);
  240. }
  241. }
  242. private Task HandleIncomingPublishPacketAsync(IMqttChannelAdapter adapter, MqttPublishPacket publishPacket, CancellationToken cancellationToken)
  243. {
  244. var applicationMessage = publishPacket.ToApplicationMessage();
  245. switch (applicationMessage.QualityOfServiceLevel)
  246. {
  247. case MqttQualityOfServiceLevel.AtMostOnce:
  248. {
  249. return ApplicationMessageReceivedCallback?.Invoke(this, applicationMessage);
  250. }
  251. case MqttQualityOfServiceLevel.AtLeastOnce:
  252. {
  253. return HandleIncomingPublishPacketWithQoS1(adapter, applicationMessage, publishPacket, cancellationToken);
  254. }
  255. case MqttQualityOfServiceLevel.ExactlyOnce:
  256. {
  257. return HandleIncomingPublishPacketWithQoS2(adapter, applicationMessage, publishPacket, cancellationToken);
  258. }
  259. default:
  260. {
  261. throw new MqttCommunicationException("Received a not supported QoS level.");
  262. }
  263. }
  264. }
  265. private async Task HandleIncomingPublishPacketWithQoS1(IMqttChannelAdapter adapter, MqttApplicationMessage applicationMessage, MqttPublishPacket publishPacket, CancellationToken cancellationToken)
  266. {
  267. await ApplicationMessageReceivedCallback(this, applicationMessage).ConfigureAwait(false);
  268. var response = new MqttPubAckPacket { PacketIdentifier = publishPacket.PacketIdentifier };
  269. await adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken, new[] { response }).ConfigureAwait(false);
  270. }
  271. private async Task HandleIncomingPublishPacketWithQoS2(IMqttChannelAdapter adapter, MqttApplicationMessage applicationMessage, MqttPublishPacket publishPacket, CancellationToken cancellationToken)
  272. {
  273. // QoS 2 is implement as method "B" [4.3.3 QoS 2: Exactly once delivery]
  274. await ApplicationMessageReceivedCallback(this, applicationMessage).ConfigureAwait(false);
  275. var response = new MqttPubRecPacket { PacketIdentifier = publishPacket.PacketIdentifier };
  276. await adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken, new[] { response }).ConfigureAwait(false);
  277. }
  278. private Task HandleIncomingPubRelPacketAsync(IMqttChannelAdapter adapter, MqttPubRelPacket pubRelPacket, CancellationToken cancellationToken)
  279. {
  280. var response = new MqttPubCompPacket { PacketIdentifier = pubRelPacket.PacketIdentifier };
  281. return adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken, new[] { response });
  282. }
  283. }
  284. }