/
listener.go
202 lines (181 loc) · 4.72 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
package webt
import (
"context"
"crypto/tls"
"fmt"
"net"
"net/http"
"sync"
"sync/atomic"
"time"
"github.com/getlantern/ops"
"github.com/getlantern/quicwrapper"
"github.com/prometheus/client_golang/prometheus"
"github.com/quic-go/quic-go"
"github.com/quic-go/quic-go/http3"
"github.com/quic-go/webtransport-go"
)
var (
connectionCounts = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "webt_connections",
Help: "Connections that web transport is currently tracking",
},
[]string{"type"},
)
)
type ListenOptions struct {
Addr string
Path string
TLSConfig *tls.Config
QuicConfig *quic.Config
Handler *http.ServeMux
}
// ListenAddr creates an HTTP/3 server listening on a given address.
// The net.Conn instances returned by the net.Listener may be multiplexed connections.
func ListenAddr(options *ListenOptions) (net.Listener, error) {
mux := options.Handler
if mux == nil {
mux = http.NewServeMux()
}
server := &webtransport.Server{
H3: http3.Server{
Handler: mux,
Addr: options.Addr,
TLSConfig: options.TLSConfig,
QuicConfig: options.QuicConfig,
},
}
udpAddr, err := net.ResolveUDPAddr("udp", options.Addr)
if err != nil {
return nil, err
}
conn, err := net.ListenUDP("udp", udpAddr)
if err != nil {
return nil, err
}
l := &listener{
server: server,
conn: conn,
connections: make(chan net.Conn, 1000),
acceptError: make(chan error, 1),
closedSignal: make(chan struct{}),
}
path := fmt.Sprintf("/%s/", options.Path)
mux.HandleFunc(path, l.handleUpgrade)
ops.Go(l.listenAndServe)
ops.Go(l.logStats)
return l, nil
}
var _ net.Listener = &listener{}
// wraps quic.Listener to create a net.Listener
type listener struct {
numConnections int64
numVirtualConnections int64
server *webtransport.Server
conn net.PacketConn
connections chan net.Conn
acceptError chan error
closedSignal chan struct{}
closeErr error
closeOnce sync.Once
}
// implements net.Listener.Accept
func (l *listener) Accept() (net.Conn, error) {
select {
case conn, ok := <-l.connections:
if !ok {
return nil, quicwrapper.ErrListenerClosed
}
return conn, nil
case err, ok := <-l.acceptError:
if !ok {
return nil, quicwrapper.ErrListenerClosed
}
return nil, err
case <-l.closedSignal:
return nil, quicwrapper.ErrListenerClosed
}
}
// implements net.Listener.Close
// Shut down the WebTransport listener.
func (l *listener) Close() error {
l.closeOnce.Do(func() {
close(l.closedSignal)
l.closeErr = l.server.Close()
})
return l.closeErr
}
func (l *listener) isClosed() bool {
select {
case <-l.closedSignal:
return true
default:
return false
}
}
// implements net.Listener.Addr
func (l *listener) Addr() net.Addr {
return l.conn.LocalAddr()
}
func (l *listener) listenAndServe() {
err := l.server.Serve(l.conn)
if err != nil {
if !l.isClosed() {
l.acceptError <- err
}
}
}
func (l *listener) handleUpgrade(w http.ResponseWriter, r *http.Request) {
session, err := l.server.Upgrade(w, r)
if err != nil {
fmt.Printf("upgrading failed: %s", err)
w.WriteHeader(500)
return
}
atomic.AddInt64(&l.numConnections, 1)
l.handleSession(session)
// session closes if this handler returns.
atomic.AddInt64(&l.numConnections, -1)
}
func (l *listener) handleSession(session *webtransport.Session) {
for {
stream, err := session.AcceptStream(context.Background())
if err != nil {
if quicwrapper.IsPeerGoingAway(err) {
log.Tracef("Accepting stream: Peer going away (%v)", err)
return
} else if ce, ok := err.(*webtransport.ConnectionError); ok && ce.Remote {
log.Tracef("Accepting stream: webtransport.ConnectionError remote=%v message=%v", ce.Remote, ce.Message)
return
} else {
log.Errorf("Accepting stream: %v", err)
return
}
} else {
atomic.AddInt64(&l.numVirtualConnections, 1)
conn := NewConn(stream, session, nil, func() {
atomic.AddInt64(&l.numVirtualConnections, -1)
})
l.connections <- conn
}
}
}
func (l *listener) logStats() {
for {
select {
case <-time.After(5 * time.Second):
if !l.isClosed() {
log.Debugf("Connections: %d Virtual: %d", atomic.LoadInt64(&l.numConnections), atomic.LoadInt64(&l.numVirtualConnections))
connectionCounts.WithLabelValues("connections").Set(float64(atomic.LoadInt64(&l.numConnections)))
connectionCounts.WithLabelValues("virtual").Set(float64(atomic.LoadInt64(&l.numVirtualConnections)))
}
case <-l.closedSignal:
log.Debugf("Connections: %d Virtual: %d", atomic.LoadInt64(&l.numConnections), atomic.LoadInt64(&l.numVirtualConnections))
log.Debug("Done logging stats.")
connectionCounts.WithLabelValues("connections").Set(0)
connectionCounts.WithLabelValues("virtual").Set(0)
return
}
}
}