Skip to content

Commit

Permalink
tls support
Browse files Browse the repository at this point in the history
  • Loading branch information
felipejfc committed Jul 15, 2016
1 parent 16d4c04 commit f791c6f
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
4 changes: 3 additions & 1 deletion config/local.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ mqttserver:
port: 1883
user: "admin"
pass: "admin"
usetls: false
insecure_tls: true
subscriptionRequests:
- topic: 'chat/+/room/+'
qos: 2
Expand Down Expand Up @@ -34,7 +36,7 @@ elasticsearch:
chat: '{ "mappings": { "message":{"_ttl": { "enabled": true, "default": "2d" }}}}'
redis:
host: "localhost"
port: 4444
port: 6379
password: ""
maxPoolSize: 10
logger:
Expand Down
2 changes: 2 additions & 0 deletions config/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ mqttserver:
port: 1883
user: "admin"
pass: "admin"
usetls: false
insecure_tls: true
subscriptionRequests:
- topic: 'chat/+/room/+'
qos: 2
Expand Down
28 changes: 27 additions & 1 deletion mqttclient/mqtt_client.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package mqttclient

import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"sync"
"time"

Expand Down Expand Up @@ -41,6 +44,7 @@ func (mc *MqttClient) setConfigurationDefaults() {
viper.SetDefault("mqttserver.user", "admin")
viper.SetDefault("mqttserver.pass", "admin")
viper.SetDefault("mqttserver.subscriptions", []map[string]string{})
viper.SetDefault("mqttserver.ca_cert_file", "")
}

func (mc *MqttClient) configureClient() {
Expand All @@ -51,7 +55,29 @@ func (mc *MqttClient) configureClient() {
func (mc *MqttClient) start(onConnectHandler mqtt.OnConnectHandler) {
logger.Logger.Debug("Initializing mqtt client")

opts := mqtt.NewClientOptions().AddBroker(fmt.Sprintf("tcp://%s:%d", mc.MqttServerHost, mc.MqttServerPort)).SetClientID("mqttbot")
useTls := viper.GetBool("mqttserver.usetls")
protocol := "tcp"
if useTls {
protocol = "ssl"
}

opts := mqtt.NewClientOptions().AddBroker(fmt.Sprintf("%s://%s:%d", protocol, mc.MqttServerHost, mc.MqttServerPort)).SetClientID("mqttbot")

if useTls {
logger.Logger.Info("mqttclient using tls")
certpool := x509.NewCertPool()
if viper.GetString("mqttserver.ca_cert_file") != "" {
pemCerts, err := ioutil.ReadFile(viper.GetString("mqttserver.ca_cert_file"))
if err == nil {
certpool.AppendCertsFromPEM(pemCerts)
} else {
logger.Logger.Error(err.Error())
}
}
tlsConfig := &tls.Config{InsecureSkipVerify: viper.GetBool("mqttserver.insecure_tls"), ClientAuth: tls.NoClientCert, RootCAs: certpool}
opts.SetTLSConfig(tlsConfig)
}

opts.SetUsername(viper.GetString("mqttserver.user"))
opts.SetPassword(viper.GetString("mqttserver.pass"))
opts.SetKeepAlive(3 * time.Second)
Expand Down

0 comments on commit f791c6f

Please sign in to comment.