-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtransport_test.go
444 lines (390 loc) · 12.9 KB
/
transport_test.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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
package quic
import (
"bytes"
"context"
"crypto/rand"
"errors"
"net"
"syscall"
"time"
tls "github.com/refraction-networking/utls"
mocklogging "github.com/refraction-networking/uquic/internal/mocks/logging"
"github.com/refraction-networking/uquic/internal/protocol"
"github.com/refraction-networking/uquic/internal/wire"
"github.com/refraction-networking/uquic/logging"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"go.uber.org/mock/gomock"
)
var _ = Describe("Transport", func() {
type packetToRead struct {
addr net.Addr
data []byte
err error
}
getPacketWithPacketType := func(connID protocol.ConnectionID, t protocol.PacketType, length protocol.ByteCount) []byte {
b, err := (&wire.ExtendedHeader{
Header: wire.Header{
Type: t,
DestConnectionID: connID,
Length: length,
Version: protocol.Version1,
},
PacketNumberLen: protocol.PacketNumberLen2,
}).Append(nil, protocol.Version1)
Expect(err).ToNot(HaveOccurred())
return b
}
getPacket := func(connID protocol.ConnectionID) []byte {
return getPacketWithPacketType(connID, protocol.PacketTypeHandshake, 2)
}
newMockPacketConn := func(packetChan <-chan packetToRead) *MockPacketConn {
conn := NewMockPacketConn(mockCtrl)
conn.EXPECT().LocalAddr().Return(&net.UDPAddr{}).AnyTimes()
conn.EXPECT().ReadFrom(gomock.Any()).DoAndReturn(func(b []byte) (int, net.Addr, error) {
p, ok := <-packetChan
if !ok {
return 0, nil, errors.New("closed")
}
return copy(b, p.data), p.addr, p.err
}).AnyTimes()
// for shutdown
conn.EXPECT().SetReadDeadline(gomock.Any()).AnyTimes()
return conn
}
It("handles packets for different packet handlers on the same packet conn", func() {
packetChan := make(chan packetToRead)
tr := &Transport{Conn: newMockPacketConn(packetChan)}
tr.init(true)
phm := NewMockPacketHandlerManager(mockCtrl)
tr.handlerMap = phm
connID1 := protocol.ParseConnectionID([]byte{1, 2, 3, 4, 5, 6, 7, 8})
connID2 := protocol.ParseConnectionID([]byte{8, 7, 6, 5, 4, 3, 2, 1})
handled := make(chan struct{}, 2)
phm.EXPECT().Get(connID1).DoAndReturn(func(protocol.ConnectionID) (packetHandler, bool) {
h := NewMockPacketHandler(mockCtrl)
h.EXPECT().handlePacket(gomock.Any()).Do(func(p receivedPacket) {
defer GinkgoRecover()
connID, err := wire.ParseConnectionID(p.data, 0)
Expect(err).ToNot(HaveOccurred())
Expect(connID).To(Equal(connID1))
handled <- struct{}{}
})
return h, true
})
phm.EXPECT().Get(connID2).DoAndReturn(func(protocol.ConnectionID) (packetHandler, bool) {
h := NewMockPacketHandler(mockCtrl)
h.EXPECT().handlePacket(gomock.Any()).Do(func(p receivedPacket) {
defer GinkgoRecover()
connID, err := wire.ParseConnectionID(p.data, 0)
Expect(err).ToNot(HaveOccurred())
Expect(connID).To(Equal(connID2))
handled <- struct{}{}
})
return h, true
})
packetChan <- packetToRead{data: getPacket(connID1)}
packetChan <- packetToRead{data: getPacket(connID2)}
Eventually(handled).Should(Receive())
Eventually(handled).Should(Receive())
// shutdown
phm.EXPECT().Close(gomock.Any())
close(packetChan)
tr.Close()
})
It("closes listeners", func() {
packetChan := make(chan packetToRead)
tr := &Transport{Conn: newMockPacketConn(packetChan)}
defer tr.Close()
ln, err := tr.Listen(&tls.Config{}, nil)
Expect(err).ToNot(HaveOccurred())
phm := NewMockPacketHandlerManager(mockCtrl)
tr.handlerMap = phm
Expect(ln.Close()).To(Succeed())
// shutdown
phm.EXPECT().Close(gomock.Any())
close(packetChan)
tr.Close()
})
It("closes transport concurrently with listener", func() {
// try 10 times to trigger race conditions
for i := 0; i < 10; i++ {
packetChan := make(chan packetToRead)
tr := &Transport{Conn: newMockPacketConn(packetChan)}
ln, err := tr.Listen(&tls.Config{}, nil)
Expect(err).ToNot(HaveOccurred())
ch := make(chan bool)
// Close transport and listener concurrently.
go func() {
ch <- true
Expect(ln.Close()).To(Succeed())
ch <- true
}()
<-ch
close(packetChan)
Expect(tr.Close()).To(Succeed())
<-ch
}
})
It("drops unparseable QUIC packets", func() {
addr := &net.UDPAddr{IP: net.IPv4(9, 8, 7, 6), Port: 1234}
packetChan := make(chan packetToRead)
t, tracer := mocklogging.NewMockTracer(mockCtrl)
tr := &Transport{
Conn: newMockPacketConn(packetChan),
ConnectionIDLength: 10,
Tracer: t,
}
tr.init(true)
dropped := make(chan struct{})
tracer.EXPECT().DroppedPacket(addr, logging.PacketTypeNotDetermined, protocol.ByteCount(4), logging.PacketDropHeaderParseError).Do(func(net.Addr, logging.PacketType, protocol.ByteCount, logging.PacketDropReason) { close(dropped) })
packetChan <- packetToRead{
addr: addr,
data: []byte{0x40 /* set the QUIC bit */, 1, 2, 3},
}
Eventually(dropped).Should(BeClosed())
// shutdown
tracer.EXPECT().Close()
close(packetChan)
tr.Close()
})
It("closes when reading from the conn fails", func() {
packetChan := make(chan packetToRead)
tr := Transport{Conn: newMockPacketConn(packetChan)}
defer tr.Close()
phm := NewMockPacketHandlerManager(mockCtrl)
tr.init(true)
tr.handlerMap = phm
done := make(chan struct{})
phm.EXPECT().Close(gomock.Any()).Do(func(error) { close(done) })
packetChan <- packetToRead{err: errors.New("read failed")}
Eventually(done).Should(BeClosed())
// shutdown
close(packetChan)
tr.Close()
})
It("continues listening after temporary errors", func() {
packetChan := make(chan packetToRead)
tr := Transport{Conn: newMockPacketConn(packetChan)}
defer tr.Close()
phm := NewMockPacketHandlerManager(mockCtrl)
tr.init(true)
tr.handlerMap = phm
tempErr := deadlineError{}
Expect(tempErr.Temporary()).To(BeTrue())
packetChan <- packetToRead{err: tempErr}
// don't expect any calls to phm.Close
time.Sleep(50 * time.Millisecond)
// shutdown
phm.EXPECT().Close(gomock.Any())
close(packetChan)
tr.Close()
})
It("handles short header packets resets", func() {
connID := protocol.ParseConnectionID([]byte{2, 3, 4, 5})
packetChan := make(chan packetToRead)
tr := Transport{
Conn: newMockPacketConn(packetChan),
ConnectionIDLength: connID.Len(),
}
tr.init(true)
defer tr.Close()
phm := NewMockPacketHandlerManager(mockCtrl)
tr.handlerMap = phm
var token protocol.StatelessResetToken
rand.Read(token[:])
var b []byte
b, err := wire.AppendShortHeader(b, connID, 1337, 2, protocol.KeyPhaseOne)
Expect(err).ToNot(HaveOccurred())
b = append(b, token[:]...)
conn := NewMockPacketHandler(mockCtrl)
gomock.InOrder(
phm.EXPECT().Get(connID).Return(conn, true),
conn.EXPECT().handlePacket(gomock.Any()).Do(func(p receivedPacket) {
Expect(p.data).To(Equal(b))
Expect(p.rcvTime).To(BeTemporally("~", time.Now(), time.Second))
}),
)
packetChan <- packetToRead{data: b}
// shutdown
phm.EXPECT().Close(gomock.Any())
close(packetChan)
tr.Close()
})
It("handles stateless resets", func() {
connID := protocol.ParseConnectionID([]byte{2, 3, 4, 5})
packetChan := make(chan packetToRead)
tr := Transport{
Conn: newMockPacketConn(packetChan),
ConnectionIDLength: connID.Len(),
}
tr.init(true)
defer tr.Close()
phm := NewMockPacketHandlerManager(mockCtrl)
tr.handlerMap = phm
var token protocol.StatelessResetToken
rand.Read(token[:])
var b []byte
b, err := wire.AppendShortHeader(b, connID, 1337, 2, protocol.KeyPhaseOne)
Expect(err).ToNot(HaveOccurred())
b = append(b, token[:]...)
conn := NewMockPacketHandler(mockCtrl)
destroyed := make(chan struct{})
gomock.InOrder(
phm.EXPECT().Get(connID),
phm.EXPECT().GetByResetToken(token).Return(conn, true),
conn.EXPECT().destroy(gomock.Any()).Do(func(err error) {
Expect(err).To(MatchError(&StatelessResetError{Token: token}))
close(destroyed)
}),
)
packetChan <- packetToRead{data: b}
Eventually(destroyed).Should(BeClosed())
// shutdown
phm.EXPECT().Close(gomock.Any())
close(packetChan)
tr.Close()
})
It("sends stateless resets", func() {
connID := protocol.ParseConnectionID([]byte{2, 3, 4, 5})
packetChan := make(chan packetToRead)
conn := newMockPacketConn(packetChan)
tr := Transport{
Conn: conn,
StatelessResetKey: &StatelessResetKey{1, 2, 3, 4},
ConnectionIDLength: connID.Len(),
}
tr.init(true)
defer tr.Close()
phm := NewMockPacketHandlerManager(mockCtrl)
tr.handlerMap = phm
var b []byte
b, err := wire.AppendShortHeader(b, connID, 1337, 2, protocol.KeyPhaseOne)
Expect(err).ToNot(HaveOccurred())
b = append(b, make([]byte, protocol.MinStatelessResetSize-len(b)+1)...)
var token protocol.StatelessResetToken
rand.Read(token[:])
written := make(chan struct{})
gomock.InOrder(
phm.EXPECT().Get(connID),
phm.EXPECT().GetByResetToken(gomock.Any()),
phm.EXPECT().GetStatelessResetToken(connID).Return(token),
conn.EXPECT().WriteTo(gomock.Any(), gomock.Any()).Do(func(b []byte, _ net.Addr) (int, error) {
defer close(written)
Expect(bytes.Contains(b, token[:])).To(BeTrue())
return len(b), nil
}),
)
packetChan <- packetToRead{data: b}
Eventually(written).Should(BeClosed())
// shutdown
phm.EXPECT().Close(gomock.Any())
close(packetChan)
tr.Close()
})
It("closes uninitialized Transport and closes underlying PacketConn", func() {
packetChan := make(chan packetToRead)
pconn := newMockPacketConn(packetChan)
tr := &Transport{
Conn: pconn,
createdConn: true, // owns pconn
}
// NO init
// shutdown
close(packetChan)
pconn.EXPECT().Close()
Expect(tr.Close()).To(Succeed())
})
It("doesn't add the PacketConn to the multiplexer if (*Transport).init fails", func() {
packetChan := make(chan packetToRead)
pconn := newMockPacketConn(packetChan)
syscallconn := &mockSyscallConn{pconn}
tr := &Transport{
Conn: syscallconn,
}
err := tr.init(false)
Expect(err).To(HaveOccurred())
conns := getMultiplexer().(*connMultiplexer).conns
Expect(len(conns)).To(BeZero())
})
It("allows receiving non-QUIC packets", func() {
remoteAddr := &net.UDPAddr{IP: net.IPv4(9, 8, 7, 6), Port: 1234}
packetChan := make(chan packetToRead)
tr := &Transport{
Conn: newMockPacketConn(packetChan),
ConnectionIDLength: 10,
}
tr.init(true)
receivedPacketChan := make(chan []byte)
go func() {
defer GinkgoRecover()
b := make([]byte, 100)
n, addr, err := tr.ReadNonQUICPacket(context.Background(), b)
Expect(err).ToNot(HaveOccurred())
Expect(addr).To(Equal(remoteAddr))
receivedPacketChan <- b[:n]
}()
// Receiving of non-QUIC packets is enabled when ReadNonQUICPacket is called.
// Give the Go routine some time to spin up.
time.Sleep(scaleDuration(50 * time.Millisecond))
packetChan <- packetToRead{
addr: remoteAddr,
data: []byte{0 /* don't set the QUIC bit */, 1, 2, 3},
}
Eventually(receivedPacketChan).Should(Receive(Equal([]byte{0, 1, 2, 3})))
// shutdown
close(packetChan)
tr.Close()
})
It("drops non-QUIC packet if the application doesn't process them quickly enough", func() {
remoteAddr := &net.UDPAddr{IP: net.IPv4(9, 8, 7, 6), Port: 1234}
packetChan := make(chan packetToRead)
t, tracer := mocklogging.NewMockTracer(mockCtrl)
tr := &Transport{
Conn: newMockPacketConn(packetChan),
ConnectionIDLength: 10,
Tracer: t,
}
tr.init(true)
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, _, err := tr.ReadNonQUICPacket(ctx, make([]byte, 10))
Expect(err).To(MatchError(context.Canceled))
for i := 0; i < maxQueuedNonQUICPackets; i++ {
packetChan <- packetToRead{
addr: remoteAddr,
data: []byte{0 /* don't set the QUIC bit */, 1, 2, 3},
}
}
done := make(chan struct{})
tracer.EXPECT().DroppedPacket(remoteAddr, logging.PacketTypeNotDetermined, protocol.ByteCount(4), logging.PacketDropDOSPrevention).Do(func(net.Addr, logging.PacketType, protocol.ByteCount, logging.PacketDropReason) {
close(done)
})
packetChan <- packetToRead{
addr: remoteAddr,
data: []byte{0 /* don't set the QUIC bit */, 1, 2, 3},
}
Eventually(done).Should(BeClosed())
// shutdown
tracer.EXPECT().Close()
close(packetChan)
tr.Close()
})
remoteAddr := &net.UDPAddr{IP: net.IPv4(1, 3, 5, 7), Port: 1234}
DescribeTable("setting the tls.Config.ServerName",
func(expected string, conf *tls.Config, addr net.Addr, host string) {
setTLSConfigServerName(conf, addr, host)
Expect(conf.ServerName).To(Equal(expected))
},
Entry("uses the value from the config", "foo.bar", &tls.Config{ServerName: "foo.bar"}, remoteAddr, "baz.foo"),
Entry("uses the hostname", "golang.org", &tls.Config{}, remoteAddr, "golang.org"),
Entry("removes the port from the hostname", "golang.org", &tls.Config{}, remoteAddr, "golang.org:1234"),
Entry("uses the IP", "1.3.5.7", &tls.Config{}, remoteAddr, ""),
)
})
type mockSyscallConn struct {
net.PacketConn
}
func (c *mockSyscallConn) SyscallConn() (syscall.RawConn, error) {
return nil, errors.New("mocked")
}