Added MQTT tls/cert options

Closes #340
This commit is contained in:
tidwall 2018-08-04 13:32:53 -07:00
parent 3573223b9a
commit f8fc7645d1
2 changed files with 54 additions and 17 deletions

View File

@ -81,6 +81,9 @@ type Endpoint struct {
QueueName string QueueName string
Qos byte Qos byte
Retained bool Retained bool
CACertFile string
CertFile string
KeyFile string
} }
SQS struct { SQS struct {
@ -406,6 +409,12 @@ func parseEndpoint(s string) (Endpoint, error) {
if n == 1 { if n == 1 {
endpoint.MQTT.Retained = true endpoint.MQTT.Retained = true
} }
case "cacert":
endpoint.MQTT.CACertFile = val[0]
case "cert":
endpoint.MQTT.CertFile = val[0]
case "key":
endpoint.MQTT.KeyFile = val[0]
} }
} }
} }

View File

@ -1,7 +1,10 @@
package endpoint package endpoint
import ( import (
"crypto/tls"
"crypto/x509"
"fmt" "fmt"
"io/ioutil"
"sync" "sync"
"time" "time"
@ -56,7 +59,31 @@ func (conn *MQTTConn) Send(msg string) error {
if conn.conn == nil { if conn.conn == nil {
uri := fmt.Sprintf("tcp://%s:%d", conn.ep.MQTT.Host, conn.ep.MQTT.Port) uri := fmt.Sprintf("tcp://%s:%d", conn.ep.MQTT.Host, conn.ep.MQTT.Port)
ops := paho.NewClientOptions().SetClientID("tile38").AddBroker(uri) ops := paho.NewClientOptions()
if conn.ep.MQTT.CertFile != "" || conn.ep.MQTT.KeyFile != "" ||
conn.ep.MQTT.CACertFile != "" {
var config tls.Config
if conn.ep.MQTT.CertFile != "" || conn.ep.MQTT.KeyFile != "" {
cert, err := tls.LoadX509KeyPair(conn.ep.MQTT.CertFile,
conn.ep.MQTT.KeyFile)
if err != nil {
return err
}
config.Certificates = append(config.Certificates, cert)
}
if conn.ep.MQTT.CACertFile != "" {
// Load CA cert
caCert, err := ioutil.ReadFile(conn.ep.MQTT.CACertFile)
if err != nil {
return err
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
config.RootCAs = caCertPool
}
ops = ops.SetTLSConfig(&config)
}
ops = ops.SetClientID("tile38").AddBroker(uri)
c := paho.NewClient(ops) c := paho.NewClient(ops)
if token := c.Connect(); token.Wait() && token.Error() != nil { if token := c.Connect(); token.Wait() && token.Error() != nil {
@ -66,7 +93,8 @@ func (conn *MQTTConn) Send(msg string) error {
conn.conn = c conn.conn = c
} }
t := conn.conn.Publish(conn.ep.MQTT.QueueName, conn.ep.MQTT.Qos, conn.ep.MQTT.Retained, msg) t := conn.conn.Publish(conn.ep.MQTT.QueueName, conn.ep.MQTT.Qos,
conn.ep.MQTT.Retained, msg)
t.Wait() t.Wait()
if t.Error() != nil { if t.Error() != nil {