From ea72bc33da6220684e51e438475acd59e10898f5 Mon Sep 17 00:00:00 2001 From: Holger Cremer Date: Tue, 16 Jan 2018 21:38:07 +0100 Subject: [PATCH] adds a dynamic part in the client id --- mqtt/mqtt.go | 8 +++++--- mqtt/utils.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 3 deletions(-) create mode 100644 mqtt/utils.go diff --git a/mqtt/mqtt.go b/mqtt/mqtt.go index b8b0f83..327db1f 100644 --- a/mqtt/mqtt.go +++ b/mqtt/mqtt.go @@ -12,7 +12,7 @@ import ( log "github.com/sirupsen/logrus" ) -const CLIENT_ID = "spaceDevices2" +const CLIENT_ID = "spaceDevicesGo" var mqttLogger = log.WithField("where", "mqtt") @@ -21,6 +21,7 @@ type MqttHandler struct { newDataChan chan []byte sessionTopic string devicesTopic string + } //func init() { @@ -63,12 +64,13 @@ func NewMqttHandler(conf conf.MqttConf) *MqttHandler { } opts.SetTLSConfig(tlsConf) - opts.SetClientID(CLIENT_ID) + opts.SetClientID(CLIENT_ID + GenerateRandomString(4)) opts.SetAutoReconnect(true) opts.SetKeepAlive(10 * time.Second) opts.SetMaxReconnectInterval(5 * time.Minute) opts.SetWill(conf.DevicesTopic, emptyPeopleAndDevices(), 0, true) + handler := MqttHandler{newDataChan: make(chan []byte), devicesTopic: conf.DevicesTopic, sessionTopic: conf.SessionTopic} opts.SetOnConnectHandler(handler.onConnect) opts.SetConnectionLostHandler(handler.onConnectionLost) @@ -98,7 +100,7 @@ func (h *MqttHandler) SendPeopleAndDevices(data PeopleAndDevices) { token := h.client.Publish(h.devicesTopic, 0, true, string(bytes)) ok := token.WaitTimeout(time.Duration(time.Second * 10)) if !ok { - mqttLogger.Warn("Error sending devices to:", h.devicesTopic) + mqttLogger.WithError(token.Error()).WithField("topic", h.devicesTopic).Warn("Error sending devices.") return } } diff --git a/mqtt/utils.go b/mqtt/utils.go new file mode 100644 index 0000000..8c407db --- /dev/null +++ b/mqtt/utils.go @@ -0,0 +1,31 @@ +package mqtt + +import ( + "crypto/rand" + "github.com/sirupsen/logrus" + "encoding/base64" +) + +// https://elithrar.github.io/article/generating-secure-random-numbers-crypto-rand/ + +// GenerateRandomBytes returns securely generated random bytes. +// It will fail with a fatal log if the system's secure random +// number generator fails to function correctly +func GenerateRandomBytes(n int) []byte { + b := make([]byte, n) + if _, err := rand.Read(b); err != nil { + // Note that err == nil only if we read len(b) bytes. + logrus.Fatal("Could not read random bytes") + } + + return b +} + +// GenerateRandomString returns a URL-safe, base64 encoded +// securely generated random string. +// It will fail with a fatal log if the system's secure random +// number generator fails to function correctly +func GenerateRandomString(s int) string { + b := GenerateRandomBytes(s) + return base64.URLEncoding.EncodeToString(b) +}