-
Notifications
You must be signed in to change notification settings - Fork 1
/
conn_test.go
577 lines (513 loc) · 15 KB
/
conn_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
// based on https://github.com/golang/net/blob/1d1ef9303861d099ec7e69ccb17377e0c443542d/nettest/conntest_test.go
package rwconn
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
)
var (
aLongTimeAgo = time.Unix(233431200, 0)
neverTimeout = time.Time{}
)
// MakePipe creates a connection between two endpoints and returns the pair
// as c1 and c2, such that anything written to c1 is read by c2 and vice-versa.
// The stop function closes all resources, including c1, c2, and the underlying
// net.Listener (if there is one), and should not be nil.
type MakePipe func() (c1, c2 net.Conn, stop func(), err error)
// TestConn tests that a net.Conn implementation properly satisfies the interface.
// The tests should not produce any false positives, but may experience
// false negatives. Thus, some issues may only be detected when the test is
// run multiple times. For maximal effectiveness, run the tests under the
// race detector.
func TestRWConn(t *testing.T) {
mp := func() (c1, c2 net.Conn, stop func(), err error) {
pr1, pw1 := io.Pipe()
pr2, pw2 := io.Pipe()
c1 = NewConn(pr1, pw2)
c2 = NewConn(pr2, pw1)
stop = func() {
c1.Close()
c2.Close()
}
return
}
t.Run("BasicIO", func(t *testing.T) { timeoutWrapper(t, mp, testBasicIO) })
t.Run("PingPong", func(t *testing.T) { timeoutWrapper(t, mp, testPingPong) })
t.Run("RacyRead", func(t *testing.T) { timeoutWrapper(t, mp, testRacyRead) })
t.Run("RacyWrite", func(t *testing.T) { timeoutWrapper(t, mp, testRacyWrite) })
t.Run("ReadTimeout", func(t *testing.T) { timeoutWrapper(t, mp, testReadTimeout) })
t.Run("PastTimeout", func(t *testing.T) { timeoutWrapper(t, mp, testPastTimeout) })
t.Run("WriteTimeout", func(t *testing.T) { timeoutWrapper(t, mp, testWriteTimeout) })
t.Run("CloseTimeout", func(t *testing.T) { timeoutWrapper(t, mp, testCloseTimeout) })
t.Run("PresentTimeout", func(t *testing.T) { timeoutWrapper(t, mp, testPresentTimeout) })
t.Run("FutureTimeout", func(t *testing.T) { timeoutWrapper(t, mp, testFutureTimeout) })
t.Run("ConcurrentMethods", func(t *testing.T) { timeoutWrapper(t, mp, testConcurrentMethods) })
}
type flushWrite struct {
w io.Writer
f http.Flusher
}
func (w *flushWrite) Write(data []byte) (int, error) {
n, err := w.w.Write(data)
w.f.Flush()
return n, err
}
func (w *flushWrite) Close() error {
return nil
}
func TestHTTPRWConn(t *testing.T) {
mp := func() (c1, c2 net.Conn, stop func(), err error) {
readyCh := make(chan struct{})
srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
panic("flusher not support")
}
w.WriteHeader(http.StatusOK)
flusher.Flush()
fw := &flushWrite{w: w, f: flusher}
doneCh := make(chan struct{})
c2 = NewConn(r.Body, fw, SetWriteDelay(500*time.Millisecond), SetCloseHook(func() {
// exit the handler
close(doneCh)
}))
// signal connection is ready
close(readyCh)
// wait until the connection is closed to stop the handler
<-doneCh
}))
srv.EnableHTTP2 = true
srv.StartTLS()
pr, pw := io.Pipe()
client := srv.Client()
// Create a request object to send to the server
req, err := http.NewRequest(http.MethodGet, srv.URL, pr)
if err != nil {
return nil, nil, nil, err
}
// Perform the request
resp, err := client.Do(req)
if err != nil {
return nil, nil, nil, err
}
if resp.StatusCode != 200 {
return nil, nil, nil, fmt.Errorf("wrong status code")
}
c1 = NewConn(resp.Body, pw)
stop = func() {
c1.Close()
c2.Close()
srv.Close()
}
<-readyCh
return
}
t.Run("BasicIO", func(t *testing.T) { timeoutWrapper(t, mp, testBasicIO) })
t.Run("PingPong", func(t *testing.T) { timeoutWrapper(t, mp, testPingPong) })
t.Run("RacyRead", func(t *testing.T) { timeoutWrapper(t, mp, testRacyRead) })
t.Run("RacyWrite", func(t *testing.T) { timeoutWrapper(t, mp, testRacyWrite) })
t.Run("ReadTimeout", func(t *testing.T) { timeoutWrapper(t, mp, testReadTimeout) })
t.Run("PastTimeout", func(t *testing.T) { timeoutWrapper(t, mp, testPastTimeout) })
t.Run("WriteTimeout", func(t *testing.T) { timeoutWrapper(t, mp, testWriteTimeout) })
t.Run("CloseTimeout", func(t *testing.T) { timeoutWrapper(t, mp, testCloseTimeout) })
t.Run("PresentTimeout", func(t *testing.T) { timeoutWrapper(t, mp, testPresentTimeout) })
t.Run("FutureTimeout", func(t *testing.T) { timeoutWrapper(t, mp, testFutureTimeout) })
t.Run("ConcurrentMethods", func(t *testing.T) { timeoutWrapper(t, mp, testConcurrentMethods) })
}
type connTester func(t *testing.T, c1, c2 net.Conn)
func timeoutWrapper(t *testing.T, mp MakePipe, f connTester) {
t.Helper()
c1, c2, stop, err := mp()
if err != nil {
t.Fatalf("unable to make pipe: %v", err)
}
var once sync.Once
defer once.Do(func() { stop() })
timer := time.AfterFunc(time.Minute, func() {
once.Do(func() {
t.Error("test timed out; terminating pipe")
stop()
})
})
defer timer.Stop()
f(t, c1, c2)
}
// testBasicIO tests that the data sent on c1 is properly received on c2.
func testBasicIO(t *testing.T, c1, c2 net.Conn) {
want := make([]byte, 1<<20)
rand.New(rand.NewSource(0)).Read(want)
dataCh := make(chan []byte)
go func() {
rd := bytes.NewReader(want)
if err := chunkedCopy(c1, rd); err != nil {
t.Errorf("unexpected c1.Write error: %v", err)
}
if err := c1.Close(); err != nil {
t.Errorf("unexpected c1.Close error: %v", err)
}
}()
go func() {
wr := new(bytes.Buffer)
if err := chunkedCopy(wr, c2); err != nil {
t.Errorf("unexpected c2.Read error: %v", err)
}
if err := c2.Close(); err != nil {
t.Errorf("unexpected c2.Close error: %v", err)
}
dataCh <- wr.Bytes()
}()
if got := <-dataCh; !bytes.Equal(got, want) {
t.Error("transmitted data differs")
}
}
// testPingPong tests that the two endpoints can synchronously send data to
// each other in a typical request-response pattern.
func testPingPong(t *testing.T, c1, c2 net.Conn) {
var wg sync.WaitGroup
defer wg.Wait()
pingPonger := func(c net.Conn) {
defer wg.Done()
buf := make([]byte, 8)
var prev uint64
for {
if _, err := io.ReadFull(c, buf); err != nil {
if err == io.EOF {
break
}
t.Errorf("unexpected Read error: %v", err)
}
v := binary.LittleEndian.Uint64(buf)
binary.LittleEndian.PutUint64(buf, v+1)
if prev != 0 && prev+2 != v {
t.Errorf("mismatching value: got %d, want %d", v, prev+2)
}
prev = v
if v == 1000 {
break
}
if _, err := c.Write(buf); err != nil {
t.Errorf("unexpected Write error: %v", err)
break
}
}
if err := c.Close(); err != nil {
t.Errorf("unexpected Close error: %v", err)
}
}
wg.Add(2)
go pingPonger(c1)
go pingPonger(c2)
// Start off the chain reaction.
if _, err := c1.Write(make([]byte, 8)); err != nil {
t.Errorf("unexpected c1.Write error: %v", err)
}
}
// testRacyRead tests that it is safe to mutate the input Read buffer
// immediately after cancelation has occurred.
func testRacyRead(t *testing.T, c1, c2 net.Conn) {
go chunkedCopy(c2, rand.New(rand.NewSource(0)))
var wg sync.WaitGroup
defer wg.Wait()
c1.SetReadDeadline(time.Now().Add(time.Millisecond))
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
b1 := make([]byte, 1024)
b2 := make([]byte, 1024)
for j := 0; j < 100; j++ {
_, err := c1.Read(b1)
copy(b1, b2) // Mutate b1 to trigger potential race
if err != nil {
checkForTimeoutError(t, err)
c1.SetReadDeadline(time.Now().Add(time.Millisecond))
}
}
}()
}
}
// testRacyWrite tests that it is safe to mutate the input Write buffer
// immediately after cancelation has occurred.
func testRacyWrite(t *testing.T, c1, c2 net.Conn) {
go chunkedCopy(ioutil.Discard, c2)
var wg sync.WaitGroup
defer wg.Wait()
c1.SetWriteDeadline(time.Now().Add(time.Millisecond))
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
b1 := make([]byte, 1024)
b2 := make([]byte, 1024)
for j := 0; j < 100; j++ {
_, err := c1.Write(b1)
copy(b1, b2) // Mutate b1 to trigger potential race
if err != nil {
checkForTimeoutError(t, err)
c1.SetWriteDeadline(time.Now().Add(time.Millisecond))
}
}
}()
}
}
// testReadTimeout tests that Read timeouts do not affect Write.
func testReadTimeout(t *testing.T, c1, c2 net.Conn) {
go chunkedCopy(ioutil.Discard, c2)
c1.SetReadDeadline(aLongTimeAgo)
_, err := c1.Read(make([]byte, 1024))
checkForTimeoutError(t, err)
if _, err := c1.Write(make([]byte, 1024)); err != nil {
t.Errorf("unexpected Write error: %v", err)
}
}
// testWriteTimeout tests that Write timeouts do not affect Read.
func testWriteTimeout(t *testing.T, c1, c2 net.Conn) {
go chunkedCopy(c2, rand.New(rand.NewSource(0)))
c1.SetWriteDeadline(aLongTimeAgo)
_, err := c1.Write(make([]byte, 1024))
checkForTimeoutError(t, err)
if _, err := c1.Read(make([]byte, 1024)); err != nil {
t.Errorf("unexpected Read error: %v", err)
}
}
// testPastTimeout tests that a deadline set in the past immediately times out
// Read and Write requests.
func testPastTimeout(t *testing.T, c1, c2 net.Conn) {
go chunkedCopy(c2, c2)
testRoundtrip(t, c1)
c1.SetDeadline(aLongTimeAgo)
n, err := c1.Write(make([]byte, 1024))
if n != 0 {
t.Errorf("unexpected Write count: got %d, want 0", n)
}
checkForTimeoutError(t, err)
n, err = c1.Read(make([]byte, 1024))
if n != 0 {
t.Errorf("unexpected Read count: got %d, want 0", n)
}
checkForTimeoutError(t, err)
testRoundtrip(t, c1)
}
// testPresentTimeout tests that a past deadline set while there are pending
// Read and Write operations immediately times out those operations.
func testPresentTimeout(t *testing.T, c1, c2 net.Conn) {
var wg sync.WaitGroup
defer wg.Wait()
wg.Add(3)
deadlineSet := make(chan bool, 1)
go func() {
defer wg.Done()
time.Sleep(100 * time.Millisecond)
deadlineSet <- true
c1.SetReadDeadline(aLongTimeAgo)
c1.SetWriteDeadline(aLongTimeAgo)
}()
go func() {
defer wg.Done()
n, err := c1.Read(make([]byte, 1024))
if n != 0 {
t.Errorf("unexpected Read count: got %d, want 0", n)
}
checkForTimeoutError(t, err)
if len(deadlineSet) == 0 {
t.Error("Read timed out before deadline is set")
}
}()
go func() {
defer wg.Done()
var err error
for err == nil {
_, err = c1.Write(make([]byte, 1024))
}
checkForTimeoutError(t, err)
if len(deadlineSet) == 0 {
t.Error("Write timed out before deadline is set")
}
}()
}
// testFutureTimeout tests that a future deadline will eventually time out
// Read and Write operations.
func testFutureTimeout(t *testing.T, c1, c2 net.Conn) {
var wg sync.WaitGroup
wg.Add(2)
c1.SetDeadline(time.Now().Add(100 * time.Millisecond))
go func() {
defer wg.Done()
_, err := c1.Read(make([]byte, 1024))
checkForTimeoutError(t, err)
}()
go func() {
defer wg.Done()
var err error
for err == nil {
_, err = c1.Write(make([]byte, 1024))
}
checkForTimeoutError(t, err)
}()
wg.Wait()
go chunkedCopy(c2, c2)
resyncConn(t, c1)
testRoundtrip(t, c1)
}
// testCloseTimeout tests that calling Close immediately times out pending
// Read and Write operations.
func testCloseTimeout(t *testing.T, c1, c2 net.Conn) {
go chunkedCopy(c2, c2)
var wg sync.WaitGroup
defer wg.Wait()
wg.Add(3)
// Test for cancelation upon connection closure.
c1.SetDeadline(neverTimeout)
go func() {
defer wg.Done()
time.Sleep(100 * time.Millisecond)
c1.Close()
}()
go func() {
defer wg.Done()
var err error
buf := make([]byte, 1024)
for err == nil {
_, err = c1.Read(buf)
}
}()
go func() {
defer wg.Done()
var err error
buf := make([]byte, 1024)
for err == nil {
_, err = c1.Write(buf)
}
}()
}
// testConcurrentMethods tests that the methods of net.Conn can safely
// be called concurrently.
func testConcurrentMethods(t *testing.T, c1, c2 net.Conn) {
go chunkedCopy(c2, c2)
// The results of the calls may be nonsensical, but this should
// not trigger a race detector warning.
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
wg.Add(7)
go func() {
defer wg.Done()
c1.Read(make([]byte, 1024))
}()
go func() {
defer wg.Done()
c1.Write(make([]byte, 1024))
}()
go func() {
defer wg.Done()
c1.SetDeadline(time.Now().Add(10 * time.Millisecond))
}()
go func() {
defer wg.Done()
c1.SetReadDeadline(aLongTimeAgo)
}()
go func() {
defer wg.Done()
c1.SetWriteDeadline(aLongTimeAgo)
}()
go func() {
defer wg.Done()
c1.LocalAddr()
}()
go func() {
defer wg.Done()
c1.RemoteAddr()
}()
}
wg.Wait() // At worst, the deadline is set 10ms into the future
resyncConn(t, c1)
testRoundtrip(t, c1)
}
// checkForTimeoutError checks that the error satisfies the Error interface
// and that Timeout returns true.
func checkForTimeoutError(t *testing.T, err error) {
t.Helper()
if nerr, ok := err.(net.Error); ok {
if !nerr.Timeout() {
t.Errorf("err.Timeout() = false, want true")
}
} else {
t.Errorf("got %T, want net.Error", err)
}
}
// testRoundtrip writes something into c and reads it back.
// It assumes that everything written into c is echoed back to itself.
func testRoundtrip(t *testing.T, c net.Conn) {
t.Helper()
if err := c.SetDeadline(neverTimeout); err != nil {
t.Errorf("roundtrip SetDeadline error: %v", err)
}
const s = "Hello, world!"
buf := []byte(s)
if _, err := c.Write(buf); err != nil {
t.Errorf("roundtrip Write error: %v", err)
}
if _, err := io.ReadFull(c, buf); err != nil {
t.Errorf("roundtrip Read error: %v", err)
}
if string(buf) != s {
t.Errorf("roundtrip data mismatch: got %q, want %q", buf, s)
}
}
// resyncConn resynchronizes the connection into a sane state.
// It assumes that everything written into c is echoed back to itself.
// It assumes that 0xff is not currently on the wire or in the read buffer.
func resyncConn(t *testing.T, c net.Conn) {
t.Helper()
c.SetDeadline(neverTimeout)
errCh := make(chan error)
go func() {
_, err := c.Write([]byte{0xff})
errCh <- err
}()
buf := make([]byte, 1024)
for {
n, err := c.Read(buf)
if n > 0 && bytes.IndexByte(buf[:n], 0xff) == n-1 {
break
}
if err != nil {
t.Errorf("unexpected Read error: %v", err)
break
}
}
if err := <-errCh; err != nil {
t.Errorf("unexpected Write error: %v", err)
}
}
// chunkedCopy copies from r to w in fixed-width chunks to avoid
// causing a Write that exceeds the maximum packet size for packet-based
// connections like "unixpacket".
// We assume that the maximum packet size is at least 1024.
func chunkedCopy(w io.Writer, r io.Reader) error {
b := make([]byte, 1024)
_, err := io.CopyBuffer(struct{ io.Writer }{w}, struct{ io.Reader }{r}, b)
return err
}
func TestCloseError(t *testing.T) {
w := new(bytes.Buffer)
c1 := NewConn(w, w)
c1.Close()
if _, err := c1.Read(nil); err != io.ErrClosedPipe {
t.Errorf("c1.Read() = %v, want io.ErrClosedPipe", err)
}
if _, err := c1.Write(nil); err != io.ErrClosedPipe {
t.Errorf("c1.Write() = %v, want io.ErrClosedPipe", err)
}
if err := c1.SetDeadline(time.Time{}); err != io.ErrClosedPipe {
t.Errorf("c1.SetDeadline() = %v, want io.ErrClosedPipe", err)
}
}