-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmqtt.go
101 lines (83 loc) · 2.54 KB
/
mqtt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package mqttcli
import (
"crypto/tls"
"crypto/x509"
"fmt"
"log"
"net/http"
"os"
mqtt "github.com/eclipse/paho.mqtt.golang"
)
func init() {
if os.Getenv("MQTT_DEBUG") != "" {
mqtt.DEBUG = log.New(os.Stderr, "MQTT_DEBUG ", log.LstdFlags)
}
}
// NewMQTTClientOptions returns a MQTT client option structure, prepopulated
// with values read from the flag variables. It is an error to call this
// function before parsing flags.
func NewMQTTClientOptions() (*mqtt.ClientOptions, error) {
opts := mqtt.NewClientOptions()
opts.SetOrderMatters(false)
opts.AddBroker(Broker)
opts.SetClientID(ClientID)
opts.SetCleanSession(Clean)
opts.SetConnectRetry(ConnectRetry)
opts.SetConnectRetryInterval(ConnectRetryInterval)
opts.SetAutoReconnect(AutoReconnect)
switch {
case Username != "" && Password != "" && CertFile.Value != "" && KeyFile.Value != "":
return nil, fmt.Errorf("authentication can only be one of username/password or cert-file/key-file")
case Username != "" && Password != "":
opts.SetUsername(Username)
opts.SetPassword(Password)
case CertFile.Value != "" && KeyFile.Value != "":
config := &tls.Config{}
certData, err := os.ReadFile(CertFile.Value)
if err != nil {
return nil, fmt.Errorf("cannot read cert-file: %w", err)
}
keyData, err := os.ReadFile(KeyFile.Value)
if err != nil {
return nil, fmt.Errorf("cannot read key-file: %w", err)
}
cert, err := tls.X509KeyPair(certData, keyData)
if err != nil {
return nil, fmt.Errorf("cannot create certificate: %w", err)
}
config.Certificates = append(config.Certificates, cert)
if CARoot != "" {
pool, err := x509.SystemCertPool()
if err != nil {
return nil, fmt.Errorf("cannot get system certificate pool: %w", err)
}
data, err := os.ReadFile(CARoot)
if err != nil {
return nil, fmt.Errorf("cannot read file: %w", err)
}
pool.AppendCertsFromPEM(data)
config.RootCAs = pool
}
config.NextProtos = TLSALPN.Values
opts.SetTLSConfig(config)
default:
if Username != "" && Password == "" {
return nil, fmt.Errorf("password required when using username")
}
if Username == "" && Password != "" {
return nil, fmt.Errorf("username required when using password")
}
if CertFile.Value != "" && KeyFile.Value == "" {
return nil, fmt.Errorf("key-file required when using cert-file")
}
if CertFile.Value == "" && KeyFile.Value != "" {
return nil, fmt.Errorf("cert-file required when using key-file")
}
}
h := make(http.Header)
for k, v := range Headers.Values {
h.Add(k, v)
}
opts.SetHTTPHeaders(h)
return opts, nil
}