private async Task StartMqttServer()
        {
            // Start a MQTT server.
            Logger.LogInfo(LogCategory.Processor, this.Name, "Starting MQTT Server..");

            _mqttServer = new MqttFactory().CreateMqttServer();

            var optionsBuilder = new MqttServerOptionsBuilder()
                                 .WithConnectionBacklog(100)
                                 .WithDefaultEndpointPort(BrokerPort)
                                 .WithConnectionValidator(AuthenticateUser)
                                 .WithStorage(new RetainedMqttMessageHandler());

            if (!string.IsNullOrEmpty(SecureCommunicationCertLocation))
            {
                optionsBuilder.WithEncryptedEndpoint().WithEncryptedEndpointPort(EncryptedBrokerPort);
            }

            var options = optionsBuilder.Build();

            if (!string.IsNullOrEmpty(SecureCommunicationCertLocation))
            {
                var certificate = new X509Certificate(SecureCommunicationCertLocation, "");
                options.TlsEndpointOptions.Certificate = certificate.Export(X509ContentType.Cert);
            }

            await _mqttServer.StartAsync(options);
        }
Ejemplo n.º 2
0
        private async Task StartMqttServer()
        {
            // Start a MQTT server.
            Logger.LogInfo(LogCategory.Processor, this.Name, "Starting MQTT Server..");

            _mqttServer = new MqttFactory().CreateMqttServer();

            var optionsBuilder = new MqttServerOptionsBuilder()
                                 .WithConnectionBacklog(100)
                                 .WithDefaultEndpointPort(BrokerPort)
                                 .WithConnectionValidator(AuthenticateUser)
                                 .WithStorage(new RetainedMqttMessageHandler());

            if (!string.IsNullOrEmpty(SecureCommunicationCertLocation))
            {
                optionsBuilder.WithEncryptedEndpoint().WithEncryptedEndpointPort(EncryptedBrokerPort);
            }

            var options = optionsBuilder.Build();

            if (!string.IsNullOrEmpty(SecureCommunicationCertLocation))
            {
                var certificate = new X509Certificate(SecureCommunicationCertLocation, "");
                options.TlsEndpointOptions.Certificate = certificate.Export(X509ContentType.Cert);
            }

            _mqttServer.Started += (s, a) =>
            {
                //Logger.LogTrace(LogCategory.Processor, this.Name, "MQTT Started", a.ToJSON());
            };

            _mqttServer.ApplicationMessageReceived += async(s, a) =>
            {
                Logger.LogTrace(LogCategory.Processor, this.Name, "MQTT Server Received Message", a.ToJSON());
            };

            _mqttServer.ClientSubscribedTopic += async(s, a) =>
            {
                //Logger.LogTrace(LogCategory.Processor, this.Name, "MQTT Client Subscribed to Topic", a.ToJSON());
            };

            _mqttServer.ClientUnsubscribedTopic += async(s, a) =>
            {
                //Logger.LogTrace(LogCategory.Processor, this.Name, "MQTT Client Unsubscribed to Topic", a.ToJSON());
            };

            _mqttServer.ClientConnected += async(s, a) =>
            {
                //Logger.LogTrace(LogCategory.Processor, this.Name, "MQTT Client Connected", a.ToJSON());
            };

            _mqttServer.ClientDisconnected += async(s, a) =>
            {
                //Logger.LogTrace(LogCategory.Processor, this.Name, "MQTT Client Disconnected", a.ToJSON());
            };

            await _mqttServer.StartAsync(options);
        }
Ejemplo n.º 3
0
        /// <summary>
        ///     Starts the service.
        /// </summary>
        public void Start()
        {
            try
            {
                var certificate = new X509Certificate2(
                    Path.Combine(this.currentPath, "certificate.pfx"),
                    "test",
                    X509KeyStorageFlags.Exportable);

                Config config;

#if DEBUG
                using (var r = new StreamReader($"{this.currentPath}\\appsettings.Development.json"))
                {
                    var json = r.ReadToEnd();
                    config = JsonConvert.DeserializeObject <Config>(json);
                }
#else
                using (var r = new StreamReader($"{this.currentPath}\\appsettings.json"))
                {
                    var json = r.ReadToEnd();
                    config = JsonConvert.DeserializeObject <Config>(json);
                }
#endif

                var optionsBuilder = new MqttServerOptionsBuilder();

                optionsBuilder = config.UnencryptedPort == null
                                     ? optionsBuilder.WithoutDefaultEndpoint()
                                     : optionsBuilder.WithDefaultEndpoint()
                                 .WithDefaultEndpointPort(config.UnencryptedPort.Value);

                optionsBuilder.WithEncryptedEndpoint().WithEncryptedEndpointPort(config.Port)
                .WithEncryptionCertificate(certificate.Export(X509ContentType.Pfx))
                .WithEncryptionSslProtocol(SslProtocols.Tls12)
                .WithConnectionValidator(this.ValidateConnection)
                .WithSubscriptionInterceptor(this.ValidateSubscription)
                .WithApplicationMessageInterceptor(this.ValidatePublish);

                this.mqttServer = new MqttFactory().CreateMqttServer();
                this.mqttServer.StartAsync(optionsBuilder.Build());
                this.mqttServer.ClientUnsubscribedTopicHandler = new MqttServerClientUnsubscribedTopicHandlerDelegate(this.HandleUnsubscription);
                this.mqttServer.ClientDisconnectedHandler      = new MqttServerClientDisconnectedHandlerDelegate(this.HandleDisconnect);

                this.clusterClient = this.ConnectOrleansClient(config).Result;
                var repositoryGrain = this.clusterClient.GetGrain <IMqttRepositoryGrain>(0);
                repositoryGrain.ConnectBroker(config.BrokerConnectionSettings, this.brokerId);

                this.logger.Information("Started MQTT server.");
            }
            catch (Exception ex)
            {
                this.logger.Fatal("An error occured: {ex}.", ex);
                Environment.Exit(0);
            }
        }
Ejemplo n.º 4
0
        /// <inheritdoc cref="BackgroundService"/>
        /// <summary>
        /// Triggered when the application host is ready to start the service.
        /// </summary>
        /// <param name="cancellationToken">Indicates that the start process has been aborted.</param>
        /// <returns>A <see cref="Task"/> representing any asynchronous operation.</returns>
        /// <seealso cref="BackgroundService"/>
        public override async Task StartAsync(CancellationToken cancellationToken)
        {
            this.logger.Information("Starting MQTT server...");

            try
            {
                var currentLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

                var certificate = new X509Certificate2(
                    // ReSharper disable once AssignNullToNotNullAttribute
                    Path.Combine(currentLocation, "certificate.pfx"),
                    "test",
                    X509KeyStorageFlags.Exportable);

                var optionsBuilder = new MqttServerOptionsBuilder();

                optionsBuilder = this.clusterConfiguration.UnencryptedPort == null
                                     ? optionsBuilder.WithoutDefaultEndpoint()
                                     : optionsBuilder.WithDefaultEndpoint()
                                 .WithDefaultEndpointPort(this.clusterConfiguration.UnencryptedPort.Value);

                optionsBuilder.WithEncryptedEndpoint().WithEncryptedEndpointPort(this.clusterConfiguration.Port)
                .WithEncryptionCertificate(certificate.Export(X509ContentType.Pfx))
                .WithEncryptionSslProtocol(SslProtocols.Tls12)
                .WithConnectionValidator(this)
                .WithSubscriptionInterceptor(this)
                .WithApplicationMessageInterceptor(this)
                .WithUnsubscriptionInterceptor(this);

                this.mqttServer = new MqttFactory().CreateMqttServer();

                // Todo: Move this to handler once available
                this.mqttServer.ClientDisconnectedHandler = this;

                await this.mqttServer.StartAsync(optionsBuilder.Build());

                await this.ConnectOrleansClient();

                var repositoryGrain = clusterClient.GetGrain <IMqttRepositoryGrain>(0);
                await repositoryGrain.ConnectBroker(this.clusterConfiguration.BrokerConnectionSettings, this.brokerId);

                this.logger.Information("Started MQTT server.");
            }
            catch (Exception ex)
            {
                Environment.ExitCode = 1;
                this.logger.Fatal("An error occurred: {@ex}.", ex);
            }

            await base.StartAsync(cancellationToken);
        }
Ejemplo n.º 5
0
        private static async Task MainAsync(string[] args)
        {
            Settings = SettingManager.ReadConfiguration(args);
            IMqttServer broker = null;
            MqttServerOptionsBuilder optionsBuilder = new MqttServerOptionsBuilder();

            // TLS Support
            (X509Certificate2, string)tuple = GetBrokerCertificate();

            //MqttTcpChannel.CustomCertificateValidationCallback += CustomCertificateValidationCallback;
            if (Settings.Broker.UseTLS)
            {
                Logger.Info("TLS v1.2 requested. Trying to get Broker Certifacte.");
            }
            if (Settings.Broker.UseTLS && tuple.Item1 != null)
            {
                Logger.Info("Found certificate:");
                string san = GetSANFromCert(tuple.Item1);
                Logger.Info("Subject Alternative Names from Certifacate:");
                Logger.Info(san);
                Logger.Info(tuple.Item1);
                optionsBuilder = optionsBuilder
                                 .WithEncryptedEndpoint()
                                 .WithEncryptedEndpointPort(8883)
                                 .WithEncryptionSslProtocol(SslProtocols.Tls12)
                                 .WithEncryptionCertificate(tuple.Item1.Export(X509ContentType.SerializedCert, tuple.Item2));
                if (Settings.Broker.UseMutualAuth)
                {
                    //broker = new MqttBroker(brokerCertificate, MqttSslProtocols.TLSv1_2, ValidateClientCertificate, UserCertificateSelectionCallback);
                }
            }
            else
            {
                Logger.Info("No encryption used.");
                optionsBuilder = optionsBuilder.WithDefaultEndpointPort(1883);
            }
            optionsBuilder = optionsBuilder.WithConnectionValidator(ValidateUserAndPassword);
            broker         = new MqttFactory().CreateMqttServer();
            IMqttServerOptions options = optionsBuilder.Build();
            await broker.StartAsync(options);

            Console.ReadKey();
        }
Ejemplo n.º 6
0
        private IMqttServerOptions CreateMqttServerOptions()
        {
            var options = new MqttServerOptionsBuilder()
                          .WithMaxPendingMessagesPerClient(_settings.MaxPendingMessagesPerClient)
                          .WithDefaultCommunicationTimeout(TimeSpan.FromSeconds(_settings.CommunicationTimeout))
                          .WithConnectionValidator(_mqttConnectionValidator)
                          .WithApplicationMessageInterceptor(_mqttApplicationMessageInterceptor)
                          .WithSubscriptionInterceptor(_mqttSubscriptionInterceptor)
                          .WithStorage(_mqttServerStorage);

            // Configure unencrypted connections
            if (_settings.TcpEndPoint.Enabled)
            {
                options.WithDefaultEndpoint();

                if (_settings.TcpEndPoint.TryReadIPv4(out var address4))
                {
                    options.WithDefaultEndpointBoundIPAddress(address4);
                }

                if (_settings.TcpEndPoint.TryReadIPv6(out var address6))
                {
                    options.WithDefaultEndpointBoundIPV6Address(address6);
                }

                if (_settings.TcpEndPoint.Port > 0)
                {
                    options.WithDefaultEndpointPort(_settings.TcpEndPoint.Port);
                }
            }
            else
            {
                options.WithoutDefaultEndpoint();
            }

            // Configure encrypted connections
            if (_settings.EncryptedTcpEndPoint.Enabled)
            {
                options
                .WithEncryptedEndpoint()
                .WithEncryptionSslProtocol(SslProtocols.Tls12)
                .WithEncryptionCertificate(_settings.EncryptedTcpEndPoint.ReadCertificate());

                if (_settings.EncryptedTcpEndPoint.TryReadIPv4(out var address4))
                {
                    options.WithEncryptedEndpointBoundIPAddress(address4);
                }

                if (_settings.EncryptedTcpEndPoint.TryReadIPv6(out var address6))
                {
                    options.WithEncryptedEndpointBoundIPV6Address(address6);
                }

                if (_settings.EncryptedTcpEndPoint.Port > 0)
                {
                    options.WithEncryptedEndpointPort(_settings.EncryptedTcpEndPoint.Port);
                }
            }
            else
            {
                options.WithoutEncryptedEndpoint();
            }

            if (_settings.ConnectionBacklog > 0)
            {
                options.WithConnectionBacklog(_settings.ConnectionBacklog);
            }

            if (_settings.EnablePersistentSessions)
            {
                options.WithPersistentSessions();
            }

            return(options.Build());
        }
Ejemplo n.º 7
0
        IMqttServerOptions CreateMqttServerOptions()
        {
            var options = new MqttServerOptionsBuilder()
                          .WithMaxPendingMessagesPerClient(_settings.MaxPendingMessagesPerClient)
                          .WithDefaultCommunicationTimeout(TimeSpan.FromSeconds(_settings.CommunicationTimeout))
                          .WithConnectionValidator(_mqttConnectionValidator)
                          .WithApplicationMessageInterceptor(_mqttApplicationMessageInterceptor)
                          .WithSubscriptionInterceptor(_mqttSubscriptionInterceptor)
                          .WithUnsubscriptionInterceptor(_mqttUnsubscriptionInterceptor)
                          .WithStorage(_mqttServerStorage);

            // Configure unencrypted connections
            if (_settings.TcpEndPoint.Enabled)
            {
                options.WithDefaultEndpoint();

                if (_settings.TcpEndPoint.TryReadIPv4(out var address4))
                {
                    options.WithDefaultEndpointBoundIPAddress(address4);
                }

                if (_settings.TcpEndPoint.TryReadIPv6(out var address6))
                {
                    options.WithDefaultEndpointBoundIPV6Address(address6);
                }

                if (_settings.TcpEndPoint.Port > 0)
                {
                    options.WithDefaultEndpointPort(_settings.TcpEndPoint.Port);
                }
            }
            else
            {
                options.WithoutDefaultEndpoint();
            }

            // Configure encrypted connections
            if (_settings.EncryptedTcpEndPoint.Enabled)
            {
#if NETCOREAPP3_1 || NET5_0
                options
                .WithEncryptedEndpoint()
                .WithEncryptionSslProtocol(SslProtocols.Tls13);
#else
                options
                .WithEncryptedEndpoint()
                .WithEncryptionSslProtocol(SslProtocols.Tls12);
#endif

                if (!string.IsNullOrEmpty(_settings.EncryptedTcpEndPoint?.Certificate?.Path))
                {
                    IMqttServerCertificateCredentials certificateCredentials = null;

                    if (!string.IsNullOrEmpty(_settings.EncryptedTcpEndPoint?.Certificate?.Password))
                    {
                        certificateCredentials = new MqttServerCertificateCredentials
                        {
                            Password = _settings.EncryptedTcpEndPoint.Certificate.Password
                        };
                    }

                    options.WithEncryptionCertificate(_settings.EncryptedTcpEndPoint.Certificate.ReadCertificate(), certificateCredentials);
                }

                if (_settings.EncryptedTcpEndPoint.TryReadIPv4(out var address4))
                {
                    options.WithEncryptedEndpointBoundIPAddress(address4);
                }

                if (_settings.EncryptedTcpEndPoint.TryReadIPv6(out var address6))
                {
                    options.WithEncryptedEndpointBoundIPV6Address(address6);
                }

                if (_settings.EncryptedTcpEndPoint.Port > 0)
                {
                    options.WithEncryptedEndpointPort(_settings.EncryptedTcpEndPoint.Port);
                }
            }
            else
            {
                options.WithoutEncryptedEndpoint();
            }

            if (_settings.ConnectionBacklog > 0)
            {
                options.WithConnectionBacklog(_settings.ConnectionBacklog);
            }

            if (_settings.EnablePersistentSessions)
            {
                options.WithPersistentSessions();
            }

            return(options.Build());
        }
Ejemplo n.º 8
0
        static Igloo15MqttServer InitializeServer(Options config, ILoggerFactory factory)
        {
            Igloo15MqttServer server = null;

            try
            {
                MqttServerOptionsBuilder serverBuilder = new MqttServerOptionsBuilder();

                if (config.Encrypted && File.Exists(config.CertificateLocation))
                {
                    if (config.IPAddress == "Any")
                    {
                        serverBuilder.WithEncryptedEndpoint();
                    }
                    else if (IPAddress.TryParse(config.IPAddress, out IPAddress address))
                    {
                        serverBuilder.WithEncryptedEndpointBoundIPAddress(address);
                    }
                    else
                    {
                        _logger.LogWarning($"Failed to parse provided IP Address : {config.IPAddress} using default");
                        serverBuilder.WithEncryptedEndpoint();
                    }

                    serverBuilder.WithEncryptedEndpointPort(config.Port);

                    var certificate = new X509Certificate2(config.CertificateLocation, config.CertificatePassword);
                    var certBytes   = certificate.Export(X509ContentType.Cert);

                    serverBuilder.WithEncryptionCertificate(certBytes);
                }
                else
                {
                    if (config.IPAddress == "Any")
                    {
                        serverBuilder.WithDefaultEndpoint();
                    }
                    else if (IPAddress.TryParse(config.IPAddress, out IPAddress address))
                    {
                        serverBuilder.WithDefaultEndpointBoundIPAddress(address);
                    }
                    else
                    {
                        _logger.LogWarning("Failed to parse provided IP Address : {IPAddress} using default", config.IPAddress);
                        serverBuilder.WithDefaultEndpoint();
                    }

                    serverBuilder.WithDefaultEndpointPort(config.Port);
                }

                if (config.Persistent)
                {
                    serverBuilder.WithPersistentSessions();
                }

                if (!String.IsNullOrEmpty(config.MessageStorageLocation))
                {
                    serverBuilder.WithStorage(new RetainedMessageHandler(config.MessageStorageLocation));
                }

                if (config.ShowSubscriptions)
                {
                    serverBuilder.WithSubscriptionInterceptor(_interceptors.SubscriptionInterceptor);
                }

                if (config.ShowMessages)
                {
                    serverBuilder.WithApplicationMessageInterceptor(_interceptors.MessageInterceptor);
                }

                if (config.ShowClientConnections)
                {
                    serverBuilder.WithConnectionValidator(_interceptors.ConnectionInterceptor);
                }

                serverBuilder
                .WithConnectionBacklog(config.ConnectionBacklog)
                .WithMaxPendingMessagesPerClient(config.MaxPendingMessagesPerClient)
                .WithDefaultCommunicationTimeout(TimeSpan.FromSeconds(config.CommunicationTimeout));


                server = new Igloo15MqttServer(serverBuilder.Build(), factory);
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Exception occured during Initialization of Server");
                return(null);
            }

            return(server);
        }
Ejemplo n.º 9
0
        IMqttServerOptions CreateMqttServerOptions()
        {
            // Create client id if none provided
            var cid = string.IsNullOrWhiteSpace(_settings.BrokerClientId) ? Guid.NewGuid().ToString("N").ToUpper() : _settings.BrokerClientId;

            var options = new MqttServerOptionsBuilder()
                          .WithMaxPendingMessagesPerClient(_settings.MaxPendingMessagesPerClient)
                          .WithDefaultCommunicationTimeout(TimeSpan.FromSeconds(_settings.CommunicationTimeout))
                          .WithConnectionValidator(_mqttConnectionValidator)
                          .WithApplicationMessageInterceptor(_mqttApplicationMessageInterceptor)
                          .WithSubscriptionInterceptor(_mqttSubscriptionInterceptor)
                          .WithUnsubscriptionInterceptor(_mqttUnsubscriptionInterceptor)
                          .WithClientId(cid);

            // Configure unencrypted connections
            if (_settings.TcpEndPoint.Enabled)
            {
                options.WithDefaultEndpoint();

                if (_settings.TcpEndPoint.TryReadIPv4(out var address4))
                {
                    options.WithDefaultEndpointBoundIPAddress(address4);
                }

                if (_settings.TcpEndPoint.TryReadIPv6(out var address6))
                {
                    options.WithDefaultEndpointBoundIPV6Address(address6);
                }

                if (_settings.TcpEndPoint.Port > 0)
                {
                    options.WithDefaultEndpointPort(_settings.TcpEndPoint.Port);
                    _logger.LogInformation($"MQTT Broker '{_settings.BrokerName}' listening on TCP port {_settings.TcpEndPoint.Port}, ClientID: {cid}");
                }
            }
            else
            {
                options.WithoutDefaultEndpoint();
            }

            // Configure encrypted connections
            if (_settings.EncryptedTcpEndPoint.Enabled)
            {
                options
                .WithEncryptedEndpoint()
                .WithEncryptionSslProtocol(SslProtocols.Tls13);

                if (!string.IsNullOrEmpty(_settings.EncryptedTcpEndPoint?.Certificate?.Path))
                {
                    IMqttServerCertificateCredentials certificateCredentials = null;

                    if (!string.IsNullOrEmpty(_settings.EncryptedTcpEndPoint?.Certificate?.Password))
                    {
                        certificateCredentials = new MqttServerCertificateCredentials
                        {
                            Password = _settings.EncryptedTcpEndPoint.Certificate.Password
                        };
                    }

                    options.WithEncryptionCertificate(_settings.EncryptedTcpEndPoint.Certificate.ReadCertificate(), certificateCredentials);
                }

                if (_settings.EncryptedTcpEndPoint.TryReadIPv4(out var address4))
                {
                    options.WithEncryptedEndpointBoundIPAddress(address4);
                }

                if (_settings.EncryptedTcpEndPoint.TryReadIPv6(out var address6))
                {
                    options.WithEncryptedEndpointBoundIPV6Address(address6);
                }

                if (_settings.EncryptedTcpEndPoint.Port > 0)
                {
                    options.WithEncryptedEndpointPort(_settings.EncryptedTcpEndPoint.Port);
                    _logger.LogInformation($"MQTT Broker {_settings.BrokerName} listening on SSL port {_settings.TcpEndPoint.Port}");
                }
            }
            else
            {
                options.WithoutEncryptedEndpoint();
            }

            if (_settings.ConnectionBacklog > 0)
            {
                options.WithConnectionBacklog(_settings.ConnectionBacklog);
            }

            if (_settings.EnablePersistentSessions)
            {
                options.WithPersistentSessions();
            }

            return(options.Build());
        }