-
Notifications
You must be signed in to change notification settings - Fork 1
/
dawdle_test.go
707 lines (598 loc) · 15.1 KB
/
dawdle_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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package dawdle
import (
"bytes"
"context"
"crypto/rand"
"errors"
"fmt"
"io"
"net"
"os"
"sync"
"testing"
"time"
)
type testTcpServer struct {
ln net.Listener
reader *io.PipeReader
writer *io.PipeWriter
buf *bytes.Buffer
bufLock *sync.RWMutex
}
func runTestTcpServer(t *testing.T) *testTcpServer {
t.Helper()
s := &testTcpServer{
buf: new(bytes.Buffer),
bufLock: new(sync.RWMutex),
}
s.reader, s.writer = io.Pipe()
var err error
s.ln, err = net.Listen("tcp", ":0")
if err != nil {
t.Fatal(err)
}
go func() {
for {
conn, err := s.ln.Accept()
if err != nil {
if !errors.Is(err, net.ErrClosed) {
panic(err)
}
return
}
go func(c net.Conn) {
io.Copy(s.writer, c)
c.Close()
}(conn)
go func() {
buf := make([]byte, 1)
var err error
for {
_, err = s.reader.Read(buf)
if err != nil {
if err == io.EOF {
return
}
panic(err)
}
s.bufLock.Lock()
_, err := s.buf.Write(buf)
s.bufLock.Unlock()
if err != nil {
panic(err)
}
}
}()
}
}()
return s
}
func (s *testTcpServer) Close() {
s.ln.Close()
}
func (s *testTcpServer) Addr() string {
return s.ln.Addr().String()
}
func (s *testTcpServer) BufLen() int {
s.bufLock.RLock()
defer s.bufLock.RUnlock()
return s.buf.Len()
}
func (s *testTcpServer) BufBytes() []byte {
s.bufLock.RLock()
defer s.bufLock.RUnlock()
return s.buf.Bytes()
}
func (s *testTcpServer) WaitBuffer(expected []byte) error {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
doneCh := make(chan struct{})
go func() {
for {
if ctx.Err() != nil {
return
}
if bytes.Equal(s.BufBytes(), expected) {
close(doneCh)
return
}
// Sleep 10ms to keep things relatively sane
time.Sleep(time.Millisecond * 10)
}
}()
var err error
select {
case <-doneCh:
case <-ctx.Done():
close(doneCh)
err = ctx.Err()
}
if err != nil {
return fmt.Errorf("error waiting for buffer, expectedlen=%d,actuallen=%d, err: %s", len(expected), s.BufLen(), err)
}
return nil
}
func TestTestTcpServer(t *testing.T) {
ts := runTestTcpServer(t)
if ts.BufLen() != 0 {
t.Fatal("test buffer should be zero")
}
defer ts.Close()
// Test sending some data and check buffer
conn, err := net.Dial("tcp", ts.Addr())
if err != nil {
t.Fatal(err)
}
expected := "foobar"
if _, err := conn.Write([]byte(expected)); err != nil {
t.Fatal(err)
}
conn.Close()
// Wait for a non-zero buffer length.
if err := ts.WaitBuffer([]byte(expected)); err != nil {
t.Fatal(err)
}
if string(ts.BufBytes()) != expected {
t.Fatalf("expected buffer to have %v, got %v", expected, string(ts.BufBytes()))
}
}
func TestProxy(t *testing.T) {
ts := runTestTcpServer(t)
if ts.BufLen() != 0 {
t.Fatal("test buffer should be zero")
}
defer ts.Close()
// Create the proxy
proxy, err := NewProxy("tcp", ":0", ts.Addr())
if err != nil {
t.Fatal(err)
}
defer proxy.Close()
proxy.Start()
// Connect to the proxy. Disable the connection's write buffer so
// that it's not interfering with our test father down (we can
// always expect the proxy buffer to be the only buffer we need to
// care about).
conn, err := net.Dial("tcp", proxy.ListenerAddr())
if err != nil {
t.Fatal(err)
}
if err := conn.(*net.TCPConn).SetWriteBuffer(1); err != nil {
t.Fatal(err)
}
// Start writing bytes (not string), and checking bytes here. We
// want a size that is going to exhaust the proxy buffer, so we
// create a buffer of default size * 2.
writeBuffer := make([]byte, defaultBufferSize*2)
var expectedB []byte
// ***********************
// ** Normal write test **
// ***********************
// Perform this test twice to do a standard test of the proxy.
for i := 1; i < 3; i++ {
actualN, err := rand.Read(writeBuffer)
if err != nil {
t.Fatalf("basic write %d: err: %s", i, err)
}
if actualN != len(writeBuffer) {
t.Fatalf("basic write %d: expected to read %d bytes, got %d", i, len(writeBuffer), actualN)
}
expectedB = append(expectedB, writeBuffer...)
actualN, err = conn.Write(writeBuffer)
if err != nil {
t.Fatalf("basic write %d: err: %s", i, err)
}
if actualN != len(writeBuffer) {
t.Fatalf("basic write %d: expected to write %d bytes, got %d", i, len(writeBuffer), actualN)
}
if err := ts.WaitBuffer(expectedB); err != nil {
t.Fatalf("basic write %d: err: %s", i, err)
}
}
// ***********
// ** Pause **
// ***********
// Pause the connection, and set a deadline. We expect this to
// fail, with the write maxing out the buffer before hanging.
proxy.Pause()
conn.SetWriteDeadline(time.Now().Add(time.Second))
actualN, err := rand.Read(writeBuffer)
if err != nil {
t.Fatal(err)
}
if actualN != len(writeBuffer) {
t.Fatalf("expected to read %d bytes, got %d", len(writeBuffer), actualN)
}
actualN, err = conn.Write(writeBuffer)
if err == nil {
t.Fatal("expected error, got none, bytes written: ", actualN)
} else {
if !errors.Is(err, os.ErrDeadlineExceeded) {
// Unexpected error
t.Fatal(err)
}
}
// Even though we've set the write buffer on the socket to 1, this
// still does not seem to be enough to get a full even write, so we
// are going to have to determine the remainder of what we did not
// write to see what else we need to write to get the complete
// picture when we resume.
//
// First test to see that we at least wrote out our proxy buffer
if actualN < len(writeBuffer)/2 {
t.Fatalf("expected to write at least %d bytes, got %d", len(writeBuffer)/2, actualN)
}
// Save bytes remaining
remainder := writeBuffer[actualN:]
// Expect first half of buffer to be written
expectedB = append(expectedB, writeBuffer[:defaultBufferSize]...)
if err := ts.WaitBuffer(expectedB); err != nil {
t.Fatal(err)
}
// ************
// ** Resume **
// ************
// Resume the connection. First we do a write out of our remaining
// bytes, if any, and test that everything made it (including any
// still in the OS buffer). Then we perform a final regular write
// to ensure everything is functional.
conn.SetWriteDeadline(time.Time{})
proxy.Resume()
if len(remainder) > 0 {
actualN, err = conn.Write(remainder)
if err != nil {
t.Fatal(err)
}
if actualN != len(remainder) {
t.Fatalf("expected to write %d bytes, got %d", len(remainder), actualN)
}
}
// Expect second half of buffer from pause step to now be written
expectedB = append(expectedB, writeBuffer[defaultBufferSize:]...)
if err := ts.WaitBuffer(expectedB); err != nil {
t.Fatal(err)
}
// Final write starts here.
actualN, err = rand.Read(writeBuffer)
if err != nil {
t.Fatal(err)
}
if actualN != len(writeBuffer) {
t.Fatalf("expected to read %d bytes, got %d", len(writeBuffer), actualN)
}
actualN, err = conn.Write(writeBuffer)
if err != nil {
t.Fatal(err)
}
if actualN != len(writeBuffer) {
t.Fatalf("expected to write %d bytes, got %d", len(writeBuffer), actualN)
}
expectedB = append(expectedB, writeBuffer...)
if err := ts.WaitBuffer(expectedB); err != nil {
t.Fatal(err)
}
}
func TestNewProxyBadTCPAddress(t *testing.T) {
_, err := NewProxy("tcp", "", "bad+addr")
if err == nil {
t.Fatal("expected error, got none")
}
if err.Error() != "error creating proxy: address bad+addr: missing port in address" {
t.Fatalf("unexpected error: %s", err)
}
}
func TestNewProxyBadProto(t *testing.T) {
_, err := NewProxy("bad", "", "")
if err == nil {
t.Fatal("expected error, got none")
}
if err.Error() != "error creating proxy: unsupported protocol bad" {
t.Fatalf("unexpected error: %s", err)
}
}
func TestNewProxyBuffers(t *testing.T) {
ts := runTestTcpServer(t)
if ts.BufLen() != 0 {
t.Fatal("test buffer should be zero")
}
defer ts.Close()
// Create the proxy
proxy, err := NewProxy("tcp", ":0", ts.Addr(), WithRbufSize(1), WithWbufSize(2))
if err != nil {
t.Fatal(err)
}
defer proxy.Close()
if proxy.rbufSize != 1 {
t.Fatalf("expected rbufSize=1, got %d", proxy.rbufSize)
}
if proxy.wbufSize != 2 {
t.Fatalf("expected wbufSize=2, got %d", proxy.wbufSize)
}
}
func testWithBadOpt() func(p *proxy) error {
return func(p *proxy) error {
return errors.New("foobar")
}
}
func TestNewProxyBadOpt(t *testing.T) {
_, err := NewProxy("tcp", "", "localhost:12345", testWithBadOpt())
if err == nil {
t.Fatal("expected error, got none")
}
if err.Error() != "error creating proxy: foobar" {
t.Fatalf("unexpected error: %s", err)
}
}
func TestNewProxyListenErr(t *testing.T) {
proxy, err := NewProxy("tcp", "bad+addr", "localhost:12345")
if err != nil {
t.Fatal(err)
}
defer proxy.Close()
err = proxy.Start()
if err == nil {
t.Fatal("expected error, got none")
}
if err.Error() != "error starting listener: listen tcp: address bad+addr: missing port in address" {
t.Fatalf("unexpected error: %s", err)
}
}
func TestNewProxyWithListener(t *testing.T) {
ln, err := net.Listen("tcp", ":0")
if err != nil {
t.Fatal(err)
}
proxy, err := NewProxy("tcp", "bad+addr", "localhost:12345", WithListener(ln))
if err != nil {
t.Fatal(err)
}
defer proxy.Close()
err = proxy.Start()
if err == nil {
t.Fatal("expected error, got none")
}
if err.Error() != "error starting listener: listener already started" {
t.Fatalf("unexpected error: %s", err)
}
if proxy.ln != ln {
t.Fatal("unexpected listener set")
}
}
// TODO: Fix this so that it works. Timing/buffering issues make this
// frustratingly impossible.
//
// func TestProxyRemoteConnectErr(t *testing.T) {
// proxy, err := NewProxy("tcp", ":0", "localhost:0", WithLogger(log.Default()))
// if err != nil {
// t.Fatal(err)
// }
// defer proxy.Close()
//
// if err := proxy.Start(); err != nil {
// t.Fatal(err)
// }
//
// conn, err := net.Dial("tcp", proxy.ListenerAddr())
// if err != nil {
// t.Fatal(err)
// }
// defer conn.Close()
//
// n, err := conn.Write([]byte("foobar"))
// if err == nil {
// t.Fatal("expected error, got none")
// }
//
// // Connection should have closed right away
// if n != 0 {
// t.Fatalf("expected 0 bytes written")
// }
// }
func TestProxyConnMap(t *testing.T) {
ts := runTestTcpServer(t)
if ts.BufLen() != 0 {
t.Fatal("test buffer should be zero")
}
defer ts.Close()
// Create the proxy
proxy, err := NewProxy("tcp", ":0", ts.Addr())
if err != nil {
t.Fatal(err)
}
defer proxy.Close()
proxy.Start()
// Create two connections
c1, err := net.Dial("tcp", proxy.ListenerAddr())
if err != nil {
t.Fatal(err)
}
defer c1.Close()
// Create two connections
c2, err := net.Dial("tcp", proxy.ListenerAddr())
if err != nil {
t.Fatal(err)
}
defer c2.Close()
// Expect entires in the map
c1addr := c1.LocalAddr().String()
c2addr := c2.LocalAddr().String()
proxy.conns.RLock()
if lenM := len(proxy.conns.m); lenM != 2 {
proxy.conns.RUnlock()
t.Fatalf("expected connection map to have 2 entries, got %d", lenM)
}
if _, ok := proxy.conns.m[c1addr]; !ok {
proxy.conns.RUnlock()
t.Fatalf("connection key %s not in map", c1addr)
}
if _, ok := proxy.conns.m[c2addr]; !ok {
proxy.conns.RUnlock()
t.Fatalf("connection key %s not in map", c2addr)
}
proxy.conns.RUnlock()
// Close a connection
c1.Close()
if err := waitConnMapLen(proxy.conns, 1); err != nil {
t.Fatal(err)
}
proxy.conns.RLock()
if _, ok := proxy.conns.m[c1addr]; ok {
proxy.conns.RUnlock()
t.Fatalf("connection key %s should not be in map", c1addr)
}
proxy.conns.RUnlock()
// Close the other
c2.Close()
if err := waitConnMapLen(proxy.conns, 0); err != nil {
t.Fatal(err)
}
proxy.conns.RLock()
if _, ok := proxy.conns.m[c2addr]; ok {
proxy.conns.RUnlock()
t.Fatalf("connection key %s should not be in map", c1addr)
}
proxy.conns.RUnlock()
}
func waitConnMapLen(cm *connMap, expected int) error {
var lenM int
for i := 0; i < 100; i++ {
cm.RLock()
lenM = len(cm.m)
cm.RUnlock()
if lenM == expected {
return nil
}
time.Sleep(time.Millisecond * 10)
}
return fmt.Errorf("timeout waiting for map to be len=%d, got %d", expected, lenM)
}
func TestProxyCloseConnections(t *testing.T) {
ts := runTestTcpServer(t)
if ts.BufLen() != 0 {
t.Fatal("test buffer should be zero")
}
defer ts.Close()
// Create the proxy
proxy, err := NewProxy("tcp", ":0", ts.Addr())
if err != nil {
t.Fatal(err)
}
defer proxy.Close()
proxy.Start()
// Create two connections
c1, err := net.Dial("tcp", proxy.ListenerAddr())
if err != nil {
t.Fatal(err)
}
defer c1.Close()
// Create two connections
c2, err := net.Dial("tcp", proxy.ListenerAddr())
if err != nil {
t.Fatal(err)
}
defer c2.Close()
// Expect entires in the map
c1addr := c1.LocalAddr().String()
c2addr := c2.LocalAddr().String()
if err := waitConnMapLen(proxy.conns, 2); err != nil {
t.Fatal(err)
}
if _, ok := proxy.conns.m[c1addr]; !ok {
t.Fatalf("connection key %s not in map", c1addr)
}
if _, ok := proxy.conns.m[c2addr]; !ok {
t.Fatalf("connection key %s not in map", c2addr)
}
// Start reads in goroutines, these should block until we kill them
var wg sync.WaitGroup
wg.Add(2)
var b1, b2 []byte
go func() {
b1, _ = io.ReadAll(c1)
wg.Done()
}()
go func() {
b2, _ = io.ReadAll(c2)
wg.Done()
}()
// Kill all connections and wait
if err := proxy.CloseConnections(); err != nil {
t.Fatal(err)
}
wg.Wait()
// Assert 0 bytes read
if len(b1) != 0 {
t.Error("should have read 0 bytes from c1")
}
if len(b2) != 0 {
t.Error("should have read 0 bytes from c2")
}
// Assert errors. TODO: Fix this, or remove it... apparently this is giving
// nil, not too sure why.
//
// if !errors.Is(err1, net.ErrClosed) {
// t.Errorf("expected err1 to be net.ErrClosed, got %s", err)
// }
// if !errors.Is(err2, net.ErrClosed) {
// t.Errorf("expected err2 to be net.ErrClosed, got %s", err)
// }
// Assert we have an empty map
if err := waitConnMapLen(proxy.conns, 0); err != nil {
t.Fatal(err)
}
// Finally assert that killing current connections did not break ability to
// create a new connection.
c3, err := net.Dial("tcp", proxy.ListenerAddr())
if err != nil {
t.Fatal(err)
}
defer c3.Close()
if _, err := io.WriteString(c3, "foobar"); err != nil {
t.Fatal(err)
}
c3.Close()
if err := ts.WaitBuffer([]byte("foobar")); err != nil {
t.Fatal(err)
}
}
func TestProxyPauseNewConn(t *testing.T) {
ts := runTestTcpServer(t)
if ts.BufLen() != 0 {
t.Fatal("test buffer should be zero")
}
defer ts.Close()
// Create the proxy
proxy, err := NewProxy("tcp", ":0", ts.Addr())
if err != nil {
t.Fatal(err)
}
defer proxy.Close()
proxy.Start()
// Pause immediately
proxy.Pause()
// Connect
conn, err := net.Dial("tcp", proxy.ListenerAddr())
if err != nil {
t.Fatal(err)
}
defer conn.Close()
// This should succeed, due to buffering on the OS side (we can fix it if the
// test ever fails)
if _, err := io.WriteString(conn, "foobar"); err != nil {
t.Fatal(err)
}
// ... but should not have made it to the buffer
if err := ts.WaitBuffer([]byte("foobar")); err == nil {
t.Fatal("expected no update to test server buffer")
}
if ts.BufLen() != 0 {
t.Fatal("expected zero buffer size")
}
// Unpause, this should send the data
proxy.Resume()
if err := ts.WaitBuffer([]byte("foobar")); err != nil {
t.Fatal(err)
}
}