-
Notifications
You must be signed in to change notification settings - Fork 4
/
dialer.go
247 lines (217 loc) · 6.24 KB
/
dialer.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
// Copyright 2019 The mqtt-go authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package mqtt
import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"io/ioutil"
"net"
"net/url"
"sync"
"golang.org/x/net/websocket"
)
var defaultPorts = map[string]uint16{
"mqtt": 1883,
"mqtts": 8883,
"wss": 443,
"ws": 80,
}
// ErrUnsupportedProtocol means that the specified scheme in the URL is not supported.
var ErrUnsupportedProtocol = errors.New("unsupported protocol")
// Dialer is an interface to create connection.
type Dialer interface {
DialContext(context.Context) (*BaseClient, error)
}
// DialerFunc type is an adapter to use functions as MQTT connection dialer.
type DialerFunc func(ctx context.Context) (*BaseClient, error)
// DialContext calls d().
func (d DialerFunc) DialContext(ctx context.Context) (*BaseClient, error) {
return d(ctx)
}
// NoContextDialerIface is a Dialer interface of mqtt-go<1.14.
type NoContextDialerIface interface {
Dial() (*BaseClient, error)
}
// NoContextDialer is a wrapper to use Dialer of mqtt-go<1.14 as mqtt-go>=1.14 Dialer.
//
// WARNING: passed context is ignored by NoContextDialer. Make sure timeout is handled inside NoContextDialer.
type NoContextDialer struct {
NoContextDialerIface
}
// DialContext wraps Dial without context.
//
// WARNING: passed context is ignored by NoContextDialer. Make sure timeout is handled inside NoContextDialer.
func (d *NoContextDialer) DialContext(context.Context) (*BaseClient, error) {
return d.Dial()
}
// URLDialer is a Dialer using URL string.
type URLDialer struct {
URL string
Options []DialOption
}
// DialContext creates connection using its values.
func (d *URLDialer) DialContext(ctx context.Context) (*BaseClient, error) {
return DialContext(ctx, d.URL, d.Options...)
}
// DialContext creates MQTT client using URL string.
func DialContext(ctx context.Context, urlStr string, opts ...DialOption) (*BaseClient, error) {
u, err := url.Parse(urlStr)
if err != nil {
return nil, err
}
o := &DialOptions{
Dialer: &net.Dialer{},
}
switch u.Scheme {
case "tls", "ssl", "mqtts", "wss":
o.TLSConfig = &tls.Config{
ServerName: u.Hostname(),
}
}
for _, opt := range opts {
if err := opt(o); err != nil {
return nil, err
}
}
return o.dial(ctx, u)
}
// DialOption sets option for Dial.
type DialOption func(*DialOptions) error
// DialOptions stores options for Dial.
type DialOptions struct {
Dialer *net.Dialer
TLSConfig *tls.Config
ConnState func(ConnState, error)
MaxPayloadLen int
}
// WithDialer sets dialer.
func WithDialer(dialer *net.Dialer) DialOption {
return func(o *DialOptions) error {
o.Dialer = dialer
return nil
}
}
// WithTLSConfig sets TLS configuration.
func WithTLSConfig(config *tls.Config) DialOption {
return func(o *DialOptions) error {
o.TLSConfig = config
return nil
}
}
// WithTLSCertFiles loads certificate files
func WithTLSCertFiles(host, caFile, certFile, privateKeyFile string) DialOption {
return func(o *DialOptions) error {
certpool := x509.NewCertPool()
cas, err := ioutil.ReadFile(caFile)
if err != nil {
return err
}
certpool.AppendCertsFromPEM(cas)
cert, err := tls.LoadX509KeyPair(certFile, privateKeyFile)
if err != nil {
return err
}
if o.TLSConfig == nil {
o.TLSConfig = &tls.Config{}
}
o.TLSConfig.ServerName = host
o.TLSConfig.RootCAs = certpool
o.TLSConfig.Certificates = []tls.Certificate{cert}
return nil
}
}
// WithMaxPayloadLen sets maximum payload length of the BaseClient.
func WithMaxPayloadLen(l int) DialOption {
return func(o *DialOptions) error {
o.MaxPayloadLen = l
return nil
}
}
// WithConnStateHandler sets connection state change handler.
func WithConnStateHandler(handler func(ConnState, error)) DialOption {
return func(o *DialOptions) error {
o.ConnState = handler
return nil
}
}
func (d *DialOptions) dial(ctx context.Context, u *url.URL) (*BaseClient, error) {
c := &BaseClient{
ConnState: d.ConnState,
MaxPayloadLen: d.MaxPayloadLen,
}
switch u.Scheme {
case "tcp", "mqtt", "tls", "ssl", "mqtts", "wss", "ws":
default:
return nil, wrapErrorf(ErrUnsupportedProtocol, "protocol %s", u.Scheme)
}
hostWithPort := u.Host
if u.Port() == "" {
if port, ok := defaultPorts[u.Scheme]; ok {
hostWithPort += fmt.Sprintf(":%d", port)
}
}
baseConn, err := d.Dialer.DialContext(ctx, "tcp", hostWithPort)
if err != nil {
return nil, wrapError(err, "dialing tcp")
}
switch u.Scheme {
case "tcp", "mqtt":
c.Transport = baseConn
case "tls", "ssl", "mqtts":
c.Transport = tls.Client(baseConn, d.TLSConfig)
case "wss":
baseConn = tls.Client(baseConn, d.TLSConfig)
fallthrough
case "ws":
wsc, err := websocket.NewConfig(u.String(), fmt.Sprintf("https://%s", u.Host))
if err != nil {
return nil, wrapError(err, "configuring websocket")
}
wsc.Protocol = append(wsc.Protocol, "mqtt")
wsc.TlsConfig = d.TLSConfig
ws, err := websocket.NewClient(wsc, baseConn)
if err != nil {
return nil, wrapError(err, "dialing websocket")
}
ws.PayloadType = websocket.BinaryFrame
c.Transport = ws
}
return c, nil
}
// BaseClientStoreDialer is a dialer wrapper which stores the latest BaseClient.
type BaseClientStoreDialer struct {
// Dialer is a wrapped dialer. Valid Dialer must be set before use.
Dialer
mu sync.RWMutex
baseClient *BaseClient
}
// DialContext creates a new BaseClient.
func (d *BaseClientStoreDialer) DialContext(ctx context.Context) (*BaseClient, error) {
cli, err := d.Dialer.DialContext(ctx)
d.mu.Lock()
d.baseClient = cli
d.mu.Unlock()
return cli, err
}
// BaseClient returns latest BaseClient created by the dialer.
// It returns nil before the first call of Dial.
func (d *BaseClientStoreDialer) BaseClient() *BaseClient {
d.mu.RLock()
cli := d.baseClient
d.mu.RUnlock()
return cli
}