forked from golang/net
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransport_test.go
6372 lines (5916 loc) · 163 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
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
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package http2
import (
"bufio"
"bytes"
"compress/gzip"
"context"
"crypto/tls"
"encoding/hex"
"errors"
"flag"
"fmt"
"io"
"io/fs"
"io/ioutil"
"log"
"math/rand"
"net"
"net/http"
"net/http/httptest"
"net/http/httptrace"
"net/textproto"
"net/url"
"os"
"reflect"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"golang.org/x/net/http2/hpack"
)
var (
extNet = flag.Bool("extnet", false, "do external network tests")
transportHost = flag.String("transporthost", "http2.golang.org", "hostname to use for TestTransport")
insecure = flag.Bool("insecure", false, "insecure TLS dials") // TODO: dead code. remove?
)
var tlsConfigInsecure = &tls.Config{InsecureSkipVerify: true}
var canceledCtx context.Context
func init() {
ctx, cancel := context.WithCancel(context.Background())
cancel()
canceledCtx = ctx
}
func TestTransportExternal(t *testing.T) {
if !*extNet {
t.Skip("skipping external network test")
}
req, _ := http.NewRequest("GET", "https://"+*transportHost+"/", nil)
rt := &Transport{TLSClientConfig: tlsConfigInsecure}
res, err := rt.RoundTrip(req)
if err != nil {
t.Fatalf("%v", err)
}
res.Write(os.Stdout)
}
type fakeTLSConn struct {
net.Conn
}
func (c *fakeTLSConn) ConnectionState() tls.ConnectionState {
return tls.ConnectionState{
Version: tls.VersionTLS12,
CipherSuite: cipher_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
}
}
func startH2cServer(t *testing.T) net.Listener {
h2Server := &Server{}
l := newLocalListener(t)
go func() {
conn, err := l.Accept()
if err != nil {
t.Error(err)
return
}
h2Server.ServeConn(&fakeTLSConn{conn}, &ServeConnOpts{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %v, http: %v", r.URL.Path, r.TLS == nil)
})})
}()
return l
}
func TestTransportH2c(t *testing.T) {
l := startH2cServer(t)
defer l.Close()
req, err := http.NewRequest("GET", "http://"+l.Addr().String()+"/foobar", nil)
if err != nil {
t.Fatal(err)
}
var gotConnCnt int32
trace := &httptrace.ClientTrace{
GotConn: func(connInfo httptrace.GotConnInfo) {
if !connInfo.Reused {
atomic.AddInt32(&gotConnCnt, 1)
}
},
}
req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
tr := &Transport{
AllowHTTP: true,
DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) {
return net.Dial(network, addr)
},
}
res, err := tr.RoundTrip(req)
if err != nil {
t.Fatal(err)
}
if res.ProtoMajor != 2 {
t.Fatal("proto not h2c")
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
if got, want := string(body), "Hello, /foobar, http: true"; got != want {
t.Fatalf("response got %v, want %v", got, want)
}
if got, want := gotConnCnt, int32(1); got != want {
t.Errorf("Too many got connections: %d", gotConnCnt)
}
}
func TestTransport(t *testing.T) {
const body = "sup"
st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, body)
}, optOnlyServer)
defer st.Close()
tr := &Transport{TLSClientConfig: tlsConfigInsecure}
defer tr.CloseIdleConnections()
u, err := url.Parse(st.ts.URL)
if err != nil {
t.Fatal(err)
}
for i, m := range []string{"GET", ""} {
req := &http.Request{
Method: m,
URL: u,
}
res, err := tr.RoundTrip(req)
if err != nil {
t.Fatalf("%d: %s", i, err)
}
t.Logf("%d: Got res: %+v", i, res)
if g, w := res.StatusCode, 200; g != w {
t.Errorf("%d: StatusCode = %v; want %v", i, g, w)
}
if g, w := res.Status, "200 OK"; g != w {
t.Errorf("%d: Status = %q; want %q", i, g, w)
}
wantHeader := http.Header{
"Content-Length": []string{"3"},
"Content-Type": []string{"text/plain; charset=utf-8"},
"Date": []string{"XXX"}, // see cleanDate
}
cleanDate(res)
if !reflect.DeepEqual(res.Header, wantHeader) {
t.Errorf("%d: res Header = %v; want %v", i, res.Header, wantHeader)
}
if res.Request != req {
t.Errorf("%d: Response.Request = %p; want %p", i, res.Request, req)
}
if res.TLS == nil {
t.Errorf("%d: Response.TLS = nil; want non-nil", i)
}
slurp, err := ioutil.ReadAll(res.Body)
if err != nil {
t.Errorf("%d: Body read: %v", i, err)
} else if string(slurp) != body {
t.Errorf("%d: Body = %q; want %q", i, slurp, body)
}
res.Body.Close()
}
}
func testTransportReusesConns(t *testing.T, useClient, wantSame bool, modReq func(*http.Request)) {
st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, r.RemoteAddr)
}, optOnlyServer, func(c net.Conn, st http.ConnState) {
t.Logf("conn %v is now state %v", c.RemoteAddr(), st)
})
defer st.Close()
tr := &Transport{TLSClientConfig: tlsConfigInsecure}
if useClient {
tr.ConnPool = noDialClientConnPool{new(clientConnPool)}
}
defer tr.CloseIdleConnections()
get := func() string {
req, err := http.NewRequest("GET", st.ts.URL, nil)
if err != nil {
t.Fatal(err)
}
modReq(req)
var res *http.Response
if useClient {
c := st.ts.Client()
ConfigureTransports(c.Transport.(*http.Transport))
res, err = c.Do(req)
} else {
res, err = tr.RoundTrip(req)
}
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
slurp, err := ioutil.ReadAll(res.Body)
if err != nil {
t.Fatalf("Body read: %v", err)
}
addr := strings.TrimSpace(string(slurp))
if addr == "" {
t.Fatalf("didn't get an addr in response")
}
return addr
}
first := get()
second := get()
if got := first == second; got != wantSame {
t.Errorf("first and second responses on same connection: %v; want %v", got, wantSame)
}
}
func TestTransportReusesConns(t *testing.T) {
for _, test := range []struct {
name string
modReq func(*http.Request)
wantSame bool
}{{
name: "ReuseConn",
modReq: func(*http.Request) {},
wantSame: true,
}, {
name: "RequestClose",
modReq: func(r *http.Request) { r.Close = true },
wantSame: false,
}, {
name: "ConnClose",
modReq: func(r *http.Request) { r.Header.Set("Connection", "close") },
wantSame: false,
}} {
t.Run(test.name, func(t *testing.T) {
t.Run("Transport", func(t *testing.T) {
const useClient = false
testTransportReusesConns(t, useClient, test.wantSame, test.modReq)
})
t.Run("Client", func(t *testing.T) {
const useClient = true
testTransportReusesConns(t, useClient, test.wantSame, test.modReq)
})
})
}
}
func TestTransportGetGotConnHooks_HTTP2Transport(t *testing.T) {
testTransportGetGotConnHooks(t, false)
}
func TestTransportGetGotConnHooks_Client(t *testing.T) { testTransportGetGotConnHooks(t, true) }
func testTransportGetGotConnHooks(t *testing.T, useClient bool) {
st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, r.RemoteAddr)
}, func(s *httptest.Server) {
s.EnableHTTP2 = true
}, optOnlyServer)
defer st.Close()
tr := &Transport{TLSClientConfig: tlsConfigInsecure}
client := st.ts.Client()
ConfigureTransports(client.Transport.(*http.Transport))
var (
getConns int32
gotConns int32
)
for i := 0; i < 2; i++ {
trace := &httptrace.ClientTrace{
GetConn: func(hostport string) {
atomic.AddInt32(&getConns, 1)
},
GotConn: func(connInfo httptrace.GotConnInfo) {
got := atomic.AddInt32(&gotConns, 1)
wantReused, wantWasIdle := false, false
if got > 1 {
wantReused, wantWasIdle = true, true
}
if connInfo.Reused != wantReused || connInfo.WasIdle != wantWasIdle {
t.Errorf("GotConn %v: Reused=%v (want %v), WasIdle=%v (want %v)", i, connInfo.Reused, wantReused, connInfo.WasIdle, wantWasIdle)
}
},
}
req, err := http.NewRequest("GET", st.ts.URL, nil)
if err != nil {
t.Fatal(err)
}
req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
var res *http.Response
if useClient {
res, err = client.Do(req)
} else {
res, err = tr.RoundTrip(req)
}
if err != nil {
t.Fatal(err)
}
res.Body.Close()
if get := atomic.LoadInt32(&getConns); get != int32(i+1) {
t.Errorf("after request %v, %v calls to GetConns: want %v", i, get, i+1)
}
if got := atomic.LoadInt32(&gotConns); got != int32(i+1) {
t.Errorf("after request %v, %v calls to GotConns: want %v", i, got, i+1)
}
}
}
type testNetConn struct {
net.Conn
closed bool
onClose func()
}
func (c *testNetConn) Close() error {
if !c.closed {
// We can call Close multiple times on the same net.Conn.
c.onClose()
}
c.closed = true
return c.Conn.Close()
}
// Tests that the Transport only keeps one pending dial open per destination address.
// https://golang.org/issue/13397
func TestTransportGroupsPendingDials(t *testing.T) {
st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
}, optOnlyServer)
defer st.Close()
var (
mu sync.Mutex
dialCount int
closeCount int
)
tr := &Transport{
TLSClientConfig: tlsConfigInsecure,
DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) {
mu.Lock()
dialCount++
mu.Unlock()
c, err := tls.Dial(network, addr, cfg)
return &testNetConn{
Conn: c,
onClose: func() {
mu.Lock()
closeCount++
mu.Unlock()
},
}, err
},
}
defer tr.CloseIdleConnections()
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
req, err := http.NewRequest("GET", st.ts.URL, nil)
if err != nil {
t.Error(err)
return
}
res, err := tr.RoundTrip(req)
if err != nil {
t.Error(err)
return
}
res.Body.Close()
}()
}
wg.Wait()
tr.CloseIdleConnections()
if dialCount != 1 {
t.Errorf("saw %d dials; want 1", dialCount)
}
if closeCount != 1 {
t.Errorf("saw %d closes; want 1", closeCount)
}
}
func retry(tries int, delay time.Duration, fn func() error) error {
var err error
for i := 0; i < tries; i++ {
err = fn()
if err == nil {
return nil
}
time.Sleep(delay)
}
return err
}
func TestTransportAbortClosesPipes(t *testing.T) {
shutdown := make(chan struct{})
st := newServerTester(t,
func(w http.ResponseWriter, r *http.Request) {
w.(http.Flusher).Flush()
<-shutdown
},
optOnlyServer,
)
defer st.Close()
defer close(shutdown) // we must shutdown before st.Close() to avoid hanging
errCh := make(chan error)
go func() {
defer close(errCh)
tr := &Transport{TLSClientConfig: tlsConfigInsecure}
req, err := http.NewRequest("GET", st.ts.URL, nil)
if err != nil {
errCh <- err
return
}
res, err := tr.RoundTrip(req)
if err != nil {
errCh <- err
return
}
defer res.Body.Close()
st.closeConn()
_, err = ioutil.ReadAll(res.Body)
if err == nil {
errCh <- errors.New("expected error from res.Body.Read")
return
}
}()
select {
case err := <-errCh:
if err != nil {
t.Fatal(err)
}
// deadlock? that's a bug.
case <-time.After(3 * time.Second):
t.Fatal("timeout")
}
}
// TODO: merge this with TestTransportBody to make TestTransportRequest? This
// could be a table-driven test with extra goodies.
func TestTransportPath(t *testing.T) {
gotc := make(chan *url.URL, 1)
st := newServerTester(t,
func(w http.ResponseWriter, r *http.Request) {
gotc <- r.URL
},
optOnlyServer,
)
defer st.Close()
tr := &Transport{TLSClientConfig: tlsConfigInsecure}
defer tr.CloseIdleConnections()
const (
path = "/testpath"
query = "q=1"
)
surl := st.ts.URL + path + "?" + query
req, err := http.NewRequest("POST", surl, nil)
if err != nil {
t.Fatal(err)
}
c := &http.Client{Transport: tr}
res, err := c.Do(req)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
got := <-gotc
if got.Path != path {
t.Errorf("Read Path = %q; want %q", got.Path, path)
}
if got.RawQuery != query {
t.Errorf("Read RawQuery = %q; want %q", got.RawQuery, query)
}
}
func randString(n int) string {
rnd := rand.New(rand.NewSource(int64(n)))
b := make([]byte, n)
for i := range b {
b[i] = byte(rnd.Intn(256))
}
return string(b)
}
type panicReader struct{}
func (panicReader) Read([]byte) (int, error) { panic("unexpected Read") }
func (panicReader) Close() error { panic("unexpected Close") }
func TestActualContentLength(t *testing.T) {
tests := []struct {
req *http.Request
want int64
}{
// Verify we don't read from Body:
0: {
req: &http.Request{Body: panicReader{}},
want: -1,
},
// nil Body means 0, regardless of ContentLength:
1: {
req: &http.Request{Body: nil, ContentLength: 5},
want: 0,
},
// ContentLength is used if set.
2: {
req: &http.Request{Body: panicReader{}, ContentLength: 5},
want: 5,
},
// http.NoBody means 0, not -1.
3: {
req: &http.Request{Body: http.NoBody},
want: 0,
},
}
for i, tt := range tests {
got := actualContentLength(tt.req)
if got != tt.want {
t.Errorf("test[%d]: got %d; want %d", i, got, tt.want)
}
}
}
func TestTransportBody(t *testing.T) {
bodyTests := []struct {
body string
noContentLen bool
}{
{body: "some message"},
{body: "some message", noContentLen: true},
{body: strings.Repeat("a", 1<<20), noContentLen: true},
{body: strings.Repeat("a", 1<<20)},
{body: randString(16<<10 - 1)},
{body: randString(16 << 10)},
{body: randString(16<<10 + 1)},
{body: randString(512<<10 - 1)},
{body: randString(512 << 10)},
{body: randString(512<<10 + 1)},
{body: randString(1<<20 - 1)},
{body: randString(1 << 20)},
{body: randString(1<<20 + 2)},
}
type reqInfo struct {
req *http.Request
slurp []byte
err error
}
gotc := make(chan reqInfo, 1)
st := newServerTester(t,
func(w http.ResponseWriter, r *http.Request) {
slurp, err := ioutil.ReadAll(r.Body)
if err != nil {
gotc <- reqInfo{err: err}
} else {
gotc <- reqInfo{req: r, slurp: slurp}
}
},
optOnlyServer,
)
defer st.Close()
for i, tt := range bodyTests {
tr := &Transport{TLSClientConfig: tlsConfigInsecure}
defer tr.CloseIdleConnections()
var body io.Reader = strings.NewReader(tt.body)
if tt.noContentLen {
body = struct{ io.Reader }{body} // just a Reader, hiding concrete type and other methods
}
req, err := http.NewRequest("POST", st.ts.URL, body)
if err != nil {
t.Fatalf("#%d: %v", i, err)
}
c := &http.Client{Transport: tr}
res, err := c.Do(req)
if err != nil {
t.Fatalf("#%d: %v", i, err)
}
defer res.Body.Close()
ri := <-gotc
if ri.err != nil {
t.Errorf("#%d: read error: %v", i, ri.err)
continue
}
if got := string(ri.slurp); got != tt.body {
t.Errorf("#%d: Read body mismatch.\n got: %q (len %d)\nwant: %q (len %d)", i, shortString(got), len(got), shortString(tt.body), len(tt.body))
}
wantLen := int64(len(tt.body))
if tt.noContentLen && tt.body != "" {
wantLen = -1
}
if ri.req.ContentLength != wantLen {
t.Errorf("#%d. handler got ContentLength = %v; want %v", i, ri.req.ContentLength, wantLen)
}
}
}
func shortString(v string) string {
const maxLen = 100
if len(v) <= maxLen {
return v
}
return fmt.Sprintf("%v[...%d bytes omitted...]%v", v[:maxLen/2], len(v)-maxLen, v[len(v)-maxLen/2:])
}
func TestTransportDialTLS(t *testing.T) {
var mu sync.Mutex // guards following
var gotReq, didDial bool
ts := newServerTester(t,
func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
gotReq = true
mu.Unlock()
},
optOnlyServer,
)
defer ts.Close()
tr := &Transport{
DialTLS: func(netw, addr string, cfg *tls.Config) (net.Conn, error) {
mu.Lock()
didDial = true
mu.Unlock()
cfg.InsecureSkipVerify = true
c, err := tls.Dial(netw, addr, cfg)
if err != nil {
return nil, err
}
return c, c.Handshake()
},
}
defer tr.CloseIdleConnections()
client := &http.Client{Transport: tr}
res, err := client.Get(ts.ts.URL)
if err != nil {
t.Fatal(err)
}
res.Body.Close()
mu.Lock()
if !gotReq {
t.Error("didn't get request")
}
if !didDial {
t.Error("didn't use dial hook")
}
}
func TestConfigureTransport(t *testing.T) {
t1 := &http.Transport{}
err := ConfigureTransport(t1)
if err != nil {
t.Fatal(err)
}
if got := fmt.Sprintf("%#v", t1); !strings.Contains(got, `"h2"`) {
// Laziness, to avoid buildtags.
t.Errorf("stringification of HTTP/1 transport didn't contain \"h2\": %v", got)
}
wantNextProtos := []string{"h2", "http/1.1"}
if t1.TLSClientConfig == nil {
t.Errorf("nil t1.TLSClientConfig")
} else if !reflect.DeepEqual(t1.TLSClientConfig.NextProtos, wantNextProtos) {
t.Errorf("TLSClientConfig.NextProtos = %q; want %q", t1.TLSClientConfig.NextProtos, wantNextProtos)
}
if err := ConfigureTransport(t1); err == nil {
t.Error("unexpected success on second call to ConfigureTransport")
}
// And does it work?
st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, r.Proto)
}, optOnlyServer)
defer st.Close()
t1.TLSClientConfig.InsecureSkipVerify = true
c := &http.Client{Transport: t1}
res, err := c.Get(st.ts.URL)
if err != nil {
t.Fatal(err)
}
slurp, err := ioutil.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
if got, want := string(slurp), "HTTP/2.0"; got != want {
t.Errorf("body = %q; want %q", got, want)
}
}
type capitalizeReader struct {
r io.Reader
}
func (cr capitalizeReader) Read(p []byte) (n int, err error) {
n, err = cr.r.Read(p)
for i, b := range p[:n] {
if b >= 'a' && b <= 'z' {
p[i] = b - ('a' - 'A')
}
}
return
}
type flushWriter struct {
w io.Writer
}
func (fw flushWriter) Write(p []byte) (n int, err error) {
n, err = fw.w.Write(p)
if f, ok := fw.w.(http.Flusher); ok {
f.Flush()
}
return
}
type clientTester struct {
t *testing.T
tr *Transport
sc, cc net.Conn // server and client conn
fr *Framer // server's framer
settings *SettingsFrame
client func() error
server func() error
}
func newClientTester(t *testing.T) *clientTester {
var dialOnce struct {
sync.Mutex
dialed bool
}
ct := &clientTester{
t: t,
}
ct.tr = &Transport{
TLSClientConfig: tlsConfigInsecure,
DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) {
dialOnce.Lock()
defer dialOnce.Unlock()
if dialOnce.dialed {
return nil, errors.New("only one dial allowed in test mode")
}
dialOnce.dialed = true
return ct.cc, nil
},
}
ln := newLocalListener(t)
cc, err := net.Dial("tcp", ln.Addr().String())
if err != nil {
t.Fatal(err)
}
sc, err := ln.Accept()
if err != nil {
t.Fatal(err)
}
ln.Close()
ct.cc = cc
ct.sc = sc
ct.fr = NewFramer(sc, sc)
return ct
}
func newLocalListener(t *testing.T) net.Listener {
ln, err := net.Listen("tcp4", "127.0.0.1:0")
if err == nil {
return ln
}
ln, err = net.Listen("tcp6", "[::1]:0")
if err != nil {
t.Fatal(err)
}
return ln
}
func (ct *clientTester) greet(settings ...Setting) {
buf := make([]byte, len(ClientPreface))
_, err := io.ReadFull(ct.sc, buf)
if err != nil {
ct.t.Fatalf("reading client preface: %v", err)
}
f, err := ct.fr.ReadFrame()
if err != nil {
ct.t.Fatalf("Reading client settings frame: %v", err)
}
var ok bool
if ct.settings, ok = f.(*SettingsFrame); !ok {
ct.t.Fatalf("Wanted client settings frame; got %v", f)
}
if err := ct.fr.WriteSettings(settings...); err != nil {
ct.t.Fatal(err)
}
if err := ct.fr.WriteSettingsAck(); err != nil {
ct.t.Fatal(err)
}
}
func (ct *clientTester) readNonSettingsFrame() (Frame, error) {
for {
f, err := ct.fr.ReadFrame()
if err != nil {
return nil, err
}
if _, ok := f.(*SettingsFrame); ok {
continue
}
return f, nil
}
}
// writeReadPing sends a PING and immediately reads the PING ACK.
// It will fail if any other unread data was pending on the connection,
// aside from SETTINGS frames.
func (ct *clientTester) writeReadPing() error {
data := [8]byte{1, 2, 3, 4, 5, 6, 7, 8}
if err := ct.fr.WritePing(false, data); err != nil {
return fmt.Errorf("Error writing PING: %v", err)
}
f, err := ct.readNonSettingsFrame()
if err != nil {
return err
}
p, ok := f.(*PingFrame)
if !ok {
return fmt.Errorf("got a %v, want a PING ACK", f)
}
if p.Flags&FlagPingAck == 0 {
return fmt.Errorf("got a PING, want a PING ACK")
}
if p.Data != data {
return fmt.Errorf("got PING data = %x, want %x", p.Data, data)
}
return nil
}
func (ct *clientTester) inflowWindow(streamID uint32) int32 {
pool := ct.tr.connPoolOrDef.(*clientConnPool)
pool.mu.Lock()
defer pool.mu.Unlock()
if n := len(pool.keys); n != 1 {
ct.t.Errorf("clientConnPool contains %v keys, expected 1", n)
return -1
}
for cc := range pool.keys {
cc.mu.Lock()
defer cc.mu.Unlock()
if streamID == 0 {
return cc.inflow.avail + cc.inflow.unsent
}
cs := cc.streams[streamID]
if cs == nil {
ct.t.Errorf("no stream with id %v", streamID)
return -1
}
return cs.inflow.avail + cs.inflow.unsent
}
return -1
}
func (ct *clientTester) cleanup() {
ct.tr.CloseIdleConnections()
// close both connections, ignore the error if its already closed
ct.sc.Close()
ct.cc.Close()
}
func (ct *clientTester) run() {
var errOnce sync.Once
var wg sync.WaitGroup
run := func(which string, fn func() error) {
defer wg.Done()
if err := fn(); err != nil {
errOnce.Do(func() {
ct.t.Errorf("%s: %v", which, err)
ct.cleanup()
})
}
}
wg.Add(2)
go run("client", ct.client)
go run("server", ct.server)
wg.Wait()
errOnce.Do(ct.cleanup) // clean up if no error
}
func (ct *clientTester) readFrame() (Frame, error) {
return ct.fr.ReadFrame()
}
func (ct *clientTester) firstHeaders() (*HeadersFrame, error) {
for {
f, err := ct.readFrame()
if err != nil {
return nil, fmt.Errorf("ReadFrame while waiting for Headers: %v", err)
}
switch f.(type) {
case *WindowUpdateFrame, *SettingsFrame:
continue
}
hf, ok := f.(*HeadersFrame)
if !ok {
return nil, fmt.Errorf("Got %T; want HeadersFrame", f)
}
return hf, nil
}
}
type countingReader struct {
n *int64
}
func (r countingReader) Read(p []byte) (n int, err error) {
for i := range p {
p[i] = byte(i)
}
atomic.AddInt64(r.n, int64(len(p)))
return len(p), err
}
func TestTransportReqBodyAfterResponse_200(t *testing.T) { testTransportReqBodyAfterResponse(t, 200) }
func TestTransportReqBodyAfterResponse_403(t *testing.T) { testTransportReqBodyAfterResponse(t, 403) }
func testTransportReqBodyAfterResponse(t *testing.T, status int) {
const bodySize = 10 << 20
clientDone := make(chan struct{})
ct := newClientTester(t)
recvLen := make(chan int64, 1)
ct.client = func() error {
defer ct.cc.(*net.TCPConn).CloseWrite()
if runtime.GOOS == "plan9" {
// CloseWrite not supported on Plan 9; Issue 17906
defer ct.cc.(*net.TCPConn).Close()
}
defer close(clientDone)
body := &pipe{b: new(bytes.Buffer)}
io.Copy(body, io.LimitReader(neverEnding('A'), bodySize/2))
req, err := http.NewRequest("PUT", "https://dummy.tld/", body)
if err != nil {
return err
}
res, err := ct.tr.RoundTrip(req)
if err != nil {
return fmt.Errorf("RoundTrip: %v", err)
}
if res.StatusCode != status {
return fmt.Errorf("status code = %v; want %v", res.StatusCode, status)
}
io.Copy(body, io.LimitReader(neverEnding('A'), bodySize/2))
body.CloseWithError(io.EOF)
slurp, err := ioutil.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("Slurp: %v", err)
}
if len(slurp) > 0 {
return fmt.Errorf("unexpected body: %q", slurp)
}
res.Body.Close()
if status == 200 {
if got := <-recvLen; got != bodySize {
return fmt.Errorf("For 200 response, Transport wrote %d bytes; want %d", got, bodySize)
}
} else {
if got := <-recvLen; got == 0 || got >= bodySize {
return fmt.Errorf("For %d response, Transport wrote %d bytes; want (0,%d) exclusive", status, got, bodySize)
}
}
return nil
}