-
-
Notifications
You must be signed in to change notification settings - Fork 116
/
dtlslistener.go
196 lines (177 loc) · 4.06 KB
/
dtlslistener.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
package net
import (
"context"
"errors"
"fmt"
"net"
"sync"
"time"
dtls "github.com/pion/dtls/v2"
"github.com/pion/dtls/v2/pkg/protocol"
"github.com/pion/dtls/v2/pkg/protocol/recordlayer"
"github.com/pion/transport/v2/udp"
"go.uber.org/atomic"
)
type GoPoolFunc = func(f func()) error
var DefaultDTLSListenerConfig = DTLSListenerConfig{
GoPool: func(f func()) error {
go f()
return nil
},
}
type DTLSListenerConfig struct {
GoPool GoPoolFunc
}
type acceptedConn struct {
conn net.Conn
err error
}
// DTLSListener is a DTLS listener that provides accept with context.
type DTLSListener struct {
listener net.Listener
config *dtls.Config
closed atomic.Bool
goPool GoPoolFunc
acceptedConnChan chan acceptedConn
wg sync.WaitGroup
done chan struct{}
}
func tlsPacketFilter(packet []byte) bool {
pkts, err := recordlayer.UnpackDatagram(packet)
if err != nil || len(pkts) < 1 {
return false
}
h := &recordlayer.Header{}
if err := h.Unmarshal(pkts[0]); err != nil {
return false
}
return h.ContentType == protocol.ContentTypeHandshake
}
// NewDTLSListener creates dtls listener.
// Known networks are "udp", "udp4" (IPv4-only), "udp6" (IPv6-only).
func NewDTLSListener(network string, addr string, dtlsCfg *dtls.Config, opts ...DTLSListenerOption) (*DTLSListener, error) {
a, err := net.ResolveUDPAddr(network, addr)
if err != nil {
return nil, fmt.Errorf("cannot resolve address: %w", err)
}
cfg := DefaultDTLSListenerConfig
for _, o := range opts {
o.ApplyDTLS(&cfg)
}
if cfg.GoPool == nil {
return nil, fmt.Errorf("empty go pool")
}
l := DTLSListener{
goPool: cfg.GoPool,
config: dtlsCfg,
acceptedConnChan: make(chan acceptedConn, 256),
done: make(chan struct{}),
}
connectContextMaker := dtlsCfg.ConnectContextMaker
if connectContextMaker == nil {
connectContextMaker = func() (context.Context, func()) {
return context.WithTimeout(context.Background(), 30*time.Second)
}
}
dtlsCfg.ConnectContextMaker = func() (context.Context, func()) {
ctx, cancel := connectContextMaker()
if l.closed.Load() {
cancel()
}
return ctx, cancel
}
lc := udp.ListenConfig{
AcceptFilter: tlsPacketFilter,
}
l.listener, err = lc.Listen(network, a)
if err != nil {
return nil, err
}
l.wg.Add(1)
go l.run()
return &l, nil
}
func (l *DTLSListener) send(conn net.Conn, err error) {
select {
case <-l.done:
case l.acceptedConnChan <- acceptedConn{
conn: conn,
err: err,
}:
}
}
func (l *DTLSListener) accept() error {
c, err := l.listener.Accept()
if err != nil {
l.send(nil, err)
return err
}
err = l.goPool(func() {
l.send(dtls.Server(c, l.config))
})
if err != nil {
_ = c.Close()
}
return err
}
func (l *DTLSListener) run() {
defer l.wg.Done()
for {
if l.closed.Load() {
return
}
err := l.accept()
if errors.Is(err, udp.ErrClosedListener) {
return
}
}
}
// AcceptWithContext waits with context for a generic Conn.
func (l *DTLSListener) AcceptWithContext(ctx context.Context) (net.Conn, error) {
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
if l.closed.Load() {
return nil, ErrListenerIsClosed
}
for {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-l.done:
return nil, ErrListenerIsClosed
case d := <-l.acceptedConnChan:
err := d.err
if errors.Is(err, context.DeadlineExceeded) {
// we don't want to report error handshake deadline exceeded
continue
}
if errors.Is(err, udp.ErrClosedListener) {
return nil, ErrListenerIsClosed
}
if err != nil {
return nil, err
}
return d.conn, nil
}
}
}
// Accept waits for a generic Conn.
func (l *DTLSListener) Accept() (net.Conn, error) {
return l.AcceptWithContext(context.Background())
}
// Close closes the connection.
func (l *DTLSListener) Close() error {
if !l.closed.CompareAndSwap(false, true) {
return nil
}
close(l.done)
defer l.wg.Wait()
return l.listener.Close()
}
// Addr represents a network end point address.
func (l *DTLSListener) Addr() net.Addr {
return l.listener.Addr()
}