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.

MqttServerConnectionValidator.cs 2.4 KiB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using System;
  2. using System.Threading.Tasks;
  3. using IronPython.Runtime;
  4. using Microsoft.Extensions.Logging;
  5. using MQTTnet.Protocol;
  6. using MQTTnet.Server.Scripting;
  7. namespace MQTTnet.Server.Mqtt
  8. {
  9. public class MqttServerConnectionValidator : IMqttServerConnectionValidator
  10. {
  11. public const string WrappedSessionItemsKey = "WRAPPED_ITEMS";
  12. private readonly PythonScriptHostService _pythonScriptHostService;
  13. private readonly ILogger _logger;
  14. public MqttServerConnectionValidator(PythonScriptHostService pythonScriptHostService, ILogger<MqttServerConnectionValidator> logger)
  15. {
  16. _pythonScriptHostService = pythonScriptHostService ?? throw new ArgumentNullException(nameof(pythonScriptHostService));
  17. _logger = logger ?? throw new ArgumentNullException(nameof(logger));
  18. }
  19. public Task ValidateConnectionAsync(MqttConnectionValidatorContext context)
  20. {
  21. try
  22. {
  23. var sessionItems = new PythonDictionary();
  24. var pythonContext = new PythonDictionary
  25. {
  26. { "endpoint", context.Endpoint },
  27. { "is_secure_connection", context.IsSecureConnection },
  28. { "client_id", context.ClientId },
  29. { "username", context.Username },
  30. { "password", context.Password },
  31. { "raw_password", new Bytes(context.RawPassword ?? new byte[0]) },
  32. { "clean_session", context.CleanSession},
  33. { "authentication_method", context.AuthenticationMethod},
  34. { "authentication_data", new Bytes(context.AuthenticationData ?? new byte[0]) },
  35. { "session_items", sessionItems },
  36. { "result", PythonConvert.Pythonfy(context.ReasonCode) }
  37. };
  38. _pythonScriptHostService.InvokeOptionalFunction("on_validate_client_connection", pythonContext);
  39. context.ReasonCode = PythonConvert.ParseEnum<MqttConnectReasonCode>((string)pythonContext["result"]);
  40. context.SessionItems[WrappedSessionItemsKey] = sessionItems;
  41. }
  42. catch (Exception exception)
  43. {
  44. _logger.LogError(exception, "Error while validating client connection.");
  45. context.ReasonCode = MqttConnectReasonCode.UnspecifiedError;
  46. }
  47. return Task.CompletedTask;
  48. }
  49. }
  50. }