/
listener.go
340 lines (282 loc) · 7.8 KB
/
listener.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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
// This package is responsible for server-side of NAT Punching Protocol.
// TODO: Check for reuseport available. If not - do not try to punch the NAT.
package npp
import (
"context"
"fmt"
"net"
"time"
"github.com/sonm-io/core/insonmnia/npp/relay"
"go.uber.org/zap"
)
type connSource int
func (m connSource) String() string {
switch m {
case sourceDirectConnection:
return "direct"
case sourceNPPConnection:
return "NPP"
case sourceRelayedConnection:
return "relay"
default:
return "unknown source"
}
}
const (
sourceError connSource = iota
sourceDirectConnection
sourceNPPConnection
sourceRelayedConnection
)
type connTuple struct {
conn net.Conn
err error
}
func newConnTuple(conn net.Conn, err error) connTuple {
return connTuple{conn, err}
}
func (m *connTuple) RemoteAddr() net.Addr {
if m == nil || m.conn == nil {
return nil
}
return m.conn.RemoteAddr()
}
func (m *connTuple) Close() error {
if m == nil || m.conn == nil {
return nil
}
return m.conn.Close()
}
func (m *connTuple) Error() error {
return m.err
}
func (m *connTuple) IsRendezvousError() bool {
if m.err == nil {
return false
}
_, ok := m.err.(*rendezvousError)
return ok
}
func (m *connTuple) unwrap() (net.Conn, error) {
return m.conn, m.err
}
func (m *connTuple) unwrapWithSource(source connSource) (net.Conn, connSource, error) {
return m.conn, source, m.err
}
// Listener specifies a net.Listener wrapper that is aware of NAT Punching
// Protocol and can switch to it when it's required to establish a connection.
//
// Options are: rendezvous server, private IPs usage, relay server(s) if any.
type Listener struct {
ctx context.Context
metrics *metrics
log *zap.Logger
listener net.Listener
listenerChannel chan connTuple
puncher NATPuncher
puncherNew func() (NATPuncher, error)
nppChannel chan connTuple
relayListener *relay.Listener
relayChannel chan connTuple
minBackoffInterval time.Duration
maxBackoffInterval time.Duration
}
// NewListener constructs a new NPP listener that will listen the specified
// network address with TCP protocol, switching to the NPP when there is no
// pending connections available.
func NewListener(ctx context.Context, addr string, options ...Option) (*Listener, error) {
opts := newOptions(ctx)
for _, o := range options {
if err := o(opts); err != nil {
return nil, err
}
}
channel := make(chan connTuple, 1)
listener, err := net.Listen(protocol, addr)
if err != nil {
return nil, err
}
m := &Listener{
ctx: ctx,
metrics: newMetrics(),
log: opts.log,
listenerChannel: channel,
listener: listener,
puncher: opts.puncher,
puncherNew: opts.puncherNew,
nppChannel: make(chan connTuple, opts.nppBacklog),
relayListener: opts.relayListener,
relayChannel: make(chan connTuple, opts.nppBacklog),
minBackoffInterval: opts.nppMinBackoffInterval,
maxBackoffInterval: opts.nppMaxBackoffInterval,
}
go m.listen(ctx)
go m.listenPuncher(ctx)
go m.listenRelay(ctx)
return m, nil
}
func (m *Listener) listen(ctx context.Context) {
for {
conn, err := m.listener.Accept()
select {
case m.listenerChannel <- newConnTuple(conn, err):
case <-ctx.Done():
m.log.Info("finished listening due to cancellation", zap.Error(ctx.Err()))
return
}
if err != nil {
m.log.Info("finished listening on Accept error", zap.Error(err))
return
}
}
}
func (m *Listener) listenPuncher(ctx context.Context) error {
if m.puncherNew == nil {
return nil
}
defer m.log.Info("finished listening NPP")
timeout := m.minBackoffInterval
for {
timer := time.NewTimer(timeout)
select {
case <-ctx.Done():
timer.Stop()
return ctx.Err()
case <-timer.C:
// Okay, let's go.
}
if m.puncher == nil {
m.log.Debug("constructing new puncher")
puncher, err := m.puncherNew()
if err != nil {
m.log.Warn("failed to construct a puncher", zap.Error(err))
if timeout < m.maxBackoffInterval {
timeout = 2 * timeout
}
continue
}
m.log.Debug("puncher has been constructed", zap.Stringer("remote", puncher.RemoteAddr()))
m.puncher = puncher
timeout = m.minBackoffInterval
}
m.nppChannel <- newConnTuple(m.puncher.AcceptContext(ctx))
}
}
func (m *Listener) listenRelay(ctx context.Context) error {
if m.relayListener == nil {
return nil
}
defer m.log.Info("finished listening Relay")
timeout := m.minBackoffInterval
for {
timer := time.NewTimer(timeout)
select {
case <-ctx.Done():
timer.Stop()
return ctx.Err()
case <-timer.C:
}
m.log.Debug("connecting using relay")
conn, err := m.relayListener.Accept()
if err != nil {
m.log.Warn("failed to relay", zap.Error(err))
if timeout < m.maxBackoffInterval {
timeout = 2 * timeout
}
} else {
timeout = m.minBackoffInterval
}
m.relayChannel <- newConnTuple(conn, newRelayError(err))
}
}
// Accept waits for and returns the next connection to the listener.
//
// This method will firstly check whether there are pending sockets in the
// listener, returning immediately if so.
// Then an attempt to communicate with the Rendezvous server occurs by
// publishing server's ID to check if there are someone wanted to connect with
// us.
// Simultaneously additional sockets are constructed after resolution to make
// punching mechanism work. This can consume a meaningful amount of file
// descriptors, so be prepared to enlarge your limits.
func (m *Listener) Accept() (net.Conn, error) {
conn, source, err := m.accept()
if err != nil {
m.log.Warn("failed to accept peer", zap.Error(err))
return nil, err
}
m.log.Info("accepted peer", zap.Stringer("source", source), zap.Stringer("remote", conn.RemoteAddr()))
switch source {
case sourceDirectConnection:
m.metrics.NumConnectionsDirect.Inc()
case sourceNPPConnection:
m.metrics.NumConnectionsNAT.Inc()
case sourceRelayedConnection:
m.metrics.NumConnectionsRelay.Inc()
default:
return nil, fmt.Errorf("unknown connection source")
}
return conn, nil
}
// Note: this function only listens for multiple channels and transforms the
// result from a single-value to multiple values, due to weird Go type system.
func (m *Listener) accept() (net.Conn, connSource, error) {
// Act as a listener if there is no puncher specified.
// Check for acceptor listenerChannel, if there is a connection - return immediately.
select {
case conn := <-m.listenerChannel:
return conn.unwrapWithSource(sourceDirectConnection)
default:
}
// Otherwise block when either a new connection arrives or NPP does its job.
for {
select {
case <-m.ctx.Done():
return nil, sourceError, m.ctx.Err()
case conn := <-m.listenerChannel:
return conn.unwrapWithSource(sourceDirectConnection)
case conn := <-m.nppChannel:
// In case of any rendezvous errors it's better to reconnect.
// Just in case.
if conn.IsRendezvousError() {
m.puncher.Close()
m.puncher = nil
} else {
return conn.unwrapWithSource(sourceNPPConnection)
}
case conn := <-m.relayChannel:
return conn.unwrapWithSource(sourceRelayedConnection)
}
}
}
func (m *Listener) Close() error {
var errs []error
if err := m.listener.Close(); err != nil {
errs = append(errs, err)
}
if m.puncher != nil {
if err := m.puncher.Close(); err != nil {
errs = append(errs, err)
}
}
if len(errs) > 0 {
return fmt.Errorf("failed to close listener: %+v", errs)
} else {
return nil
}
}
func (m *Listener) Addr() net.Addr {
return m.listener.Addr()
}
func (m *Listener) Metrics() ListenerMetrics {
var rendezvousAddr net.Addr
if m.puncher != nil {
rendezvousAddr = m.puncher.RemoteAddr()
}
return ListenerMetrics{
RendezvousAddr: rendezvousAddr,
NumConnectionsDirect: m.metrics.NumConnectionsDirect.Load(),
NumConnectionsNAT: m.metrics.NumConnectionsNAT.Load(),
NumConnectionsRelay: m.metrics.NumConnectionsRelay.Load(),
}
}