11package mqttpubsub
22
33import (
4+ "crypto/tls"
5+ "crypto/x509"
6+ "io/ioutil"
47 "encoding/json"
58 "fmt"
69 "sync"
@@ -21,7 +24,7 @@ type Backend struct {
2124}
2225
2326// NewBackend creates a new Backend.
24- func NewBackend (server , username , password string ) (* Backend , error ) {
27+ func NewBackend (server , username , password , cafile string ) (* Backend , error ) {
2528 b := Backend {
2629 txPacketChan : make (chan gw.TXPacketBytes ),
2730 gateways : make (map [lorawan.EUI64 ]struct {}),
@@ -33,7 +36,14 @@ func NewBackend(server, username, password string) (*Backend, error) {
3336 opts .SetPassword (password )
3437 opts .SetOnConnectHandler (b .onConnected )
3538 opts .SetConnectionLostHandler (b .onConnectionLost )
36-
39+
40+ if cafile != "" {
41+ tlsconfig , err := NewTLSConfig (cafile )
42+ if err == nil {
43+ opts .SetTLSConfig (tlsconfig )
44+ }
45+ }
46+
3747 log .WithField ("server" , server ).Info ("backend: connecting to mqtt broker" )
3848 b .conn = mqtt .NewClient (opts )
3949 if token := b .conn .Connect (); token .Wait () && token .Error () != nil {
@@ -43,6 +53,26 @@ func NewBackend(server, username, password string) (*Backend, error) {
4353 return & b , nil
4454}
4555
56+ // NewTLSConfig returns the TLS configuration.
57+ func NewTLSConfig (cafile string ) (* tls.Config , error ) {
58+ // Import trusted certificates from CAfile.pem.
59+
60+ cert , err := ioutil .ReadFile (cafile )
61+ if err != nil {
62+ log .Errorf ("backend: couldn't load cafile: %s" , err )
63+ return nil , err
64+ }
65+
66+ certpool := x509 .NewCertPool ()
67+ certpool .AppendCertsFromPEM (cert )
68+
69+ // Create tls.Config with desired tls properties
70+ return & tls.Config {
71+ // RootCAs = certs used to verify server cert.
72+ RootCAs : certpool ,
73+ }, nil
74+ }
75+
4676// Close closes the backend.
4777func (b * Backend ) Close () {
4878 b .conn .Disconnect (250 ) // wait 250 milisec to complete pending actions
0 commit comments