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.
 
 
 
 

278 lines
12 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using MQTTnet.Core.Adapter;
  6. using MQTTnet.Core.Exceptions;
  7. using MQTTnet.Core.Internal;
  8. using MQTTnet.Core.Packets;
  9. using MQTTnet.Core.Protocol;
  10. using MQTTnet.Core.Serializer;
  11. using Microsoft.Extensions.Logging;
  12. using Microsoft.Extensions.Options;
  13. namespace MQTTnet.Core.Server
  14. {
  15. public sealed class MqttClientSession
  16. {
  17. private readonly HashSet<ushort> _unacknowledgedPublishPackets = new HashSet<ushort>();
  18. private readonly IMqttClientRetainedMessageManager _clientRetainedMessageManager;
  19. private readonly MqttClientSubscriptionsManager _subscriptionsManager;
  20. private readonly MqttClientSessionsManager _sessionsManager;
  21. private readonly MqttClientPendingMessagesQueue _pendingMessagesQueue;
  22. private readonly MqttServerOptions _options;
  23. private readonly ILogger<MqttClientSession> _logger;
  24. private IMqttCommunicationAdapter _adapter;
  25. private CancellationTokenSource _cancellationTokenSource;
  26. private MqttApplicationMessage _willMessage;
  27. public MqttClientSession(
  28. string clientId,
  29. IOptions<MqttServerOptions> options,
  30. MqttClientSessionsManager sessionsManager,
  31. MqttClientSubscriptionsManager subscriptionsManager,
  32. ILogger<MqttClientSession> logger,
  33. ILogger<MqttClientPendingMessagesQueue> messageQueueLogger,
  34. IMqttClientRetainedMessageManager clientRetainedMessageManager)
  35. {
  36. _clientRetainedMessageManager = clientRetainedMessageManager ?? throw new ArgumentNullException(nameof(clientRetainedMessageManager));
  37. _sessionsManager = sessionsManager ?? throw new ArgumentNullException(nameof(sessionsManager));
  38. _subscriptionsManager = subscriptionsManager ?? throw new ArgumentNullException(nameof(subscriptionsManager));
  39. _logger = logger ?? throw new ArgumentNullException(nameof(logger));
  40. ClientId = clientId;
  41. _options = options.Value;
  42. _pendingMessagesQueue = new MqttClientPendingMessagesQueue(_options, this, messageQueueLogger);
  43. }
  44. public string ClientId { get; }
  45. public MqttProtocolVersion? ProtocolVersion => _adapter?.PacketSerializer.ProtocolVersion;
  46. public bool IsConnected => _adapter != null;
  47. public async Task RunAsync(MqttApplicationMessage willMessage, IMqttCommunicationAdapter adapter)
  48. {
  49. if (adapter == null) throw new ArgumentNullException(nameof(adapter));
  50. try
  51. {
  52. _willMessage = willMessage;
  53. _adapter = adapter;
  54. _cancellationTokenSource = new CancellationTokenSource();
  55. _pendingMessagesQueue.Start(adapter, _cancellationTokenSource.Token);
  56. await ReceivePacketsAsync(adapter, _cancellationTokenSource.Token).ConfigureAwait(false);
  57. }
  58. catch (OperationCanceledException)
  59. {
  60. }
  61. catch (MqttCommunicationException exception)
  62. {
  63. _logger.LogWarning(new EventId(), exception, "Client '{0}': Communication exception while processing client packets.", ClientId);
  64. }
  65. catch (Exception exception)
  66. {
  67. _logger.LogError(new EventId(), exception, "Client '{0}': Unhandled exception while processing client packets.", ClientId);
  68. }
  69. }
  70. public void Stop()
  71. {
  72. try
  73. {
  74. _cancellationTokenSource?.Cancel(false);
  75. _cancellationTokenSource?.Dispose();
  76. _cancellationTokenSource = null;
  77. _adapter = null;
  78. _logger.LogInformation("Client '{0}': Disconnected.", ClientId);
  79. }
  80. finally
  81. {
  82. if (_willMessage != null)
  83. {
  84. _sessionsManager.DispatchApplicationMessage(this, _willMessage);
  85. }
  86. }
  87. }
  88. public void EnqueuePublishPacket(MqttPublishPacket publishPacket)
  89. {
  90. if (publishPacket == null) throw new ArgumentNullException(nameof(publishPacket));
  91. if (!_subscriptionsManager.IsSubscribed(publishPacket))
  92. {
  93. return;
  94. }
  95. _pendingMessagesQueue.Enqueue(publishPacket);
  96. }
  97. private async Task ReceivePacketsAsync(IMqttCommunicationAdapter adapter, CancellationToken cancellationToken)
  98. {
  99. try
  100. {
  101. while (!cancellationToken.IsCancellationRequested)
  102. {
  103. var packet = await adapter.ReceivePacketAsync(TimeSpan.Zero, cancellationToken).ConfigureAwait(false);
  104. await ProcessReceivedPacketAsync(adapter, packet, cancellationToken).ConfigureAwait(false);
  105. }
  106. }
  107. catch (OperationCanceledException)
  108. {
  109. }
  110. catch (MqttCommunicationException exception)
  111. {
  112. _logger.LogWarning(new EventId(), exception, "Client '{0}': Communication exception while processing client packets.", ClientId);
  113. Stop();
  114. }
  115. catch (Exception exception)
  116. {
  117. _logger.LogError(new EventId(), exception, "Client '{0}': Unhandled exception while processing client packets.", ClientId);
  118. Stop();
  119. }
  120. }
  121. private Task ProcessReceivedPacketAsync(IMqttCommunicationAdapter adapter, MqttBasePacket packet, CancellationToken cancellationToken)
  122. {
  123. if (packet is MqttPingReqPacket)
  124. {
  125. return adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken, new MqttPingRespPacket());
  126. }
  127. if (packet is MqttPublishPacket publishPacket)
  128. {
  129. return HandleIncomingPublishPacketAsync(adapter, publishPacket, cancellationToken);
  130. }
  131. if (packet is MqttPubRelPacket pubRelPacket)
  132. {
  133. return HandleIncomingPubRelPacketAsync(adapter, pubRelPacket, cancellationToken);
  134. }
  135. if (packet is MqttPubRecPacket pubRecPacket)
  136. {
  137. return adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken, pubRecPacket.CreateResponse<MqttPubRelPacket>());
  138. }
  139. if (packet is MqttPubAckPacket || packet is MqttPubCompPacket)
  140. {
  141. // Discard message.
  142. return Task.FromResult(0);
  143. }
  144. if (packet is MqttSubscribePacket subscribePacket)
  145. {
  146. return HandleIncomingSubscribePacketAsync(adapter, subscribePacket, cancellationToken);
  147. }
  148. if (packet is MqttUnsubscribePacket unsubscribePacket)
  149. {
  150. return adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken, _subscriptionsManager.Unsubscribe(unsubscribePacket));
  151. }
  152. if (packet is MqttDisconnectPacket || packet is MqttConnectPacket)
  153. {
  154. Stop();
  155. return Task.FromResult(0);
  156. }
  157. _logger.LogWarning("Client '{0}': Received not supported packet ({1}). Closing connection.", ClientId, packet);
  158. Stop();
  159. return Task.FromResult(0);
  160. }
  161. private async Task HandleIncomingSubscribePacketAsync(IMqttCommunicationAdapter adapter, MqttSubscribePacket subscribePacket, CancellationToken cancellationToken)
  162. {
  163. var subscribeResult = _subscriptionsManager.Subscribe(subscribePacket, ClientId);
  164. await adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken, subscribeResult.ResponsePacket).ConfigureAwait(false);
  165. await EnqueueSubscribedRetainedMessagesAsync(subscribePacket).ConfigureAwait(false);
  166. if (subscribeResult.CloseConnection)
  167. {
  168. await adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken, new MqttDisconnectPacket()).ConfigureAwait(false);
  169. Stop();
  170. }
  171. }
  172. private async Task EnqueueSubscribedRetainedMessagesAsync(MqttSubscribePacket subscribePacket)
  173. {
  174. var retainedMessages = await _clientRetainedMessageManager.GetSubscribedMessagesAsync(subscribePacket).ConfigureAwait(false);
  175. foreach (var publishPacket in retainedMessages)
  176. {
  177. EnqueuePublishPacket(publishPacket.ToPublishPacket());
  178. }
  179. }
  180. private async Task HandleIncomingPublishPacketAsync(IMqttCommunicationAdapter adapter, MqttPublishPacket publishPacket, CancellationToken cancellationToken)
  181. {
  182. var applicationMessage = publishPacket.ToApplicationMessage();
  183. var interceptorContext = new MqttApplicationMessageInterceptorContext
  184. {
  185. ApplicationMessage = applicationMessage
  186. };
  187. _options.ApplicationMessageInterceptor?.Invoke(interceptorContext);
  188. applicationMessage = interceptorContext.ApplicationMessage;
  189. if (applicationMessage.Retain)
  190. {
  191. await _clientRetainedMessageManager.HandleMessageAsync(ClientId, applicationMessage).ConfigureAwait(false);
  192. }
  193. switch (applicationMessage.QualityOfServiceLevel)
  194. {
  195. case MqttQualityOfServiceLevel.AtMostOnce:
  196. {
  197. _sessionsManager.DispatchApplicationMessage(this, applicationMessage);
  198. return;
  199. }
  200. case MqttQualityOfServiceLevel.AtLeastOnce:
  201. {
  202. _sessionsManager.DispatchApplicationMessage(this, applicationMessage);
  203. await adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken,
  204. new MqttPubAckPacket { PacketIdentifier = publishPacket.PacketIdentifier });
  205. return;
  206. }
  207. case MqttQualityOfServiceLevel.ExactlyOnce:
  208. {
  209. // QoS 2 is implement as method "B" [4.3.3 QoS 2: Exactly once delivery]
  210. lock (_unacknowledgedPublishPackets)
  211. {
  212. _unacknowledgedPublishPackets.Add(publishPacket.PacketIdentifier);
  213. }
  214. _sessionsManager.DispatchApplicationMessage(this, applicationMessage);
  215. await adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken,
  216. new MqttPubRecPacket { PacketIdentifier = publishPacket.PacketIdentifier }).ConfigureAwait(false);
  217. return;
  218. }
  219. default:
  220. throw new MqttCommunicationException("Received a not supported QoS level.");
  221. }
  222. }
  223. private Task HandleIncomingPubRelPacketAsync(IMqttCommunicationAdapter adapter, MqttPubRelPacket pubRelPacket, CancellationToken cancellationToken)
  224. {
  225. lock (_unacknowledgedPublishPackets)
  226. {
  227. _unacknowledgedPublishPackets.Remove(pubRelPacket.PacketIdentifier);
  228. }
  229. return adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken, new MqttPubCompPacket { PacketIdentifier = pubRelPacket.PacketIdentifier });
  230. }
  231. }
  232. }