Source file
src/net/http/transport.go
1
2
3
4
5
6
7
8
9
10 package http
11
12 import (
13 "bufio"
14 "context"
15 "crypto/tls"
16 "errors"
17 "fmt"
18 "internal/godebug"
19 "io"
20 "log"
21 "maps"
22 "math/rand/v2"
23 "net"
24 "net/http/httptrace"
25 "net/http/internal"
26 "net/http/internal/ascii"
27 "net/http/internal/httpcommon"
28 "net/textproto"
29 "net/url"
30 "reflect"
31 "strings"
32 "sync"
33 "sync/atomic"
34 "time"
35 _ "unsafe"
36
37 "golang.org/x/net/http/httpguts"
38 "golang.org/x/net/http/httpproxy"
39 )
40
41
42
43
44
45
46
47 var DefaultTransport RoundTripper = &Transport{
48 Proxy: ProxyFromEnvironment,
49 DialContext: defaultTransportDialContext(&net.Dialer{
50 Timeout: 30 * time.Second,
51 KeepAlive: 30 * time.Second,
52 }),
53 ForceAttemptHTTP2: true,
54 MaxIdleConns: 100,
55 IdleConnTimeout: 90 * time.Second,
56 TLSHandshakeTimeout: 10 * time.Second,
57 ExpectContinueTimeout: 1 * time.Second,
58 }
59
60
61
62 const DefaultMaxIdleConnsPerHost = 2
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 type Transport struct {
99 pool clientConnPool
100
101 altMu sync.Mutex
102 altProto atomic.Value
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118 Proxy func(*Request) (*url.URL, error)
119
120
121
122
123 OnProxyConnectResponse func(ctx context.Context, proxyURL *url.URL, connectReq *Request, connectRes *Response) error
124
125
126
127
128
129
130
131
132
133 DialContext func(ctx context.Context, network, addr string) (net.Conn, error)
134
135
136
137
138
139
140
141
142
143
144
145 Dial func(network, addr string) (net.Conn, error)
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160 DialTLSContext func(ctx context.Context, network, addr string) (net.Conn, error)
161
162
163
164
165
166
167
168 DialTLS func(network, addr string) (net.Conn, error)
169
170
171
172
173
174 TLSClientConfig *tls.Config
175
176
177
178 TLSHandshakeTimeout time.Duration
179
180
181
182
183
184
185 DisableKeepAlives bool
186
187
188
189
190
191
192
193
194
195 DisableCompression bool
196
197
198
199 MaxIdleConns int
200
201
202
203
204 MaxIdleConnsPerHost int
205
206
207
208
209
210
211 MaxConnsPerHost int
212
213
214
215
216
217 IdleConnTimeout time.Duration
218
219
220
221
222
223 ResponseHeaderTimeout time.Duration
224
225
226
227
228
229
230
231
232 ExpectContinueTimeout time.Duration
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247 TLSNextProto map[string]func(authority string, c *tls.Conn) RoundTripper
248
249
250
251
252 ProxyConnectHeader Header
253
254
255
256
257
258
259
260
261 GetProxyConnectHeader func(ctx context.Context, proxyURL *url.URL, target string) (Header, error)
262
263
264
265
266
267
268 MaxResponseHeaderBytes int64
269
270
271
272
273 WriteBufferSize int
274
275
276
277
278 ReadBufferSize int
279
280
281
282 nextProtoOnce sync.Once
283 closeIdleFunc closeIdleConnectionser
284 h2Transport *http2Transport
285 h2Config http2ExternalTransportConfig
286 h3Transport http3Transport
287 tlsNextProtoWasNil bool
288
289
290
291
292
293
294 ForceAttemptHTTP2 bool
295
296
297 HTTP2 *HTTP2Config
298
299
300
301
302
303
304
305
306
307 Protocols *Protocols
308 }
309
310 func (t *Transport) writeBufferSize() int {
311 if t.WriteBufferSize > 0 {
312 return t.WriteBufferSize
313 }
314 return 4 << 10
315 }
316
317 func (t *Transport) readBufferSize() int {
318 if t.ReadBufferSize > 0 {
319 return t.ReadBufferSize
320 }
321 return 4 << 10
322 }
323
324 func (t *Transport) maxHeaderResponseSize() int64 {
325 if t.MaxResponseHeaderBytes > 0 {
326 return t.MaxResponseHeaderBytes
327 }
328 return 10 << 20
329 }
330
331
332 func (t *Transport) Clone() *Transport {
333 t.nextProtoOnce.Do(t.onceSetNextProtoDefaults)
334 t2 := &Transport{
335 Proxy: t.Proxy,
336 OnProxyConnectResponse: t.OnProxyConnectResponse,
337 DialContext: t.DialContext,
338 Dial: t.Dial,
339 DialTLS: t.DialTLS,
340 DialTLSContext: t.DialTLSContext,
341 TLSHandshakeTimeout: t.TLSHandshakeTimeout,
342 DisableKeepAlives: t.DisableKeepAlives,
343 DisableCompression: t.DisableCompression,
344 MaxIdleConns: t.MaxIdleConns,
345 MaxIdleConnsPerHost: t.MaxIdleConnsPerHost,
346 MaxConnsPerHost: t.MaxConnsPerHost,
347 IdleConnTimeout: t.IdleConnTimeout,
348 ResponseHeaderTimeout: t.ResponseHeaderTimeout,
349 ExpectContinueTimeout: t.ExpectContinueTimeout,
350 ProxyConnectHeader: t.ProxyConnectHeader.Clone(),
351 GetProxyConnectHeader: t.GetProxyConnectHeader,
352 MaxResponseHeaderBytes: t.MaxResponseHeaderBytes,
353 ForceAttemptHTTP2: t.ForceAttemptHTTP2,
354 WriteBufferSize: t.WriteBufferSize,
355 ReadBufferSize: t.ReadBufferSize,
356 }
357 if t.TLSClientConfig != nil {
358 t2.TLSClientConfig = t.TLSClientConfig.Clone()
359 }
360 if t.HTTP2 != nil {
361 t2.HTTP2 = &HTTP2Config{}
362 *t2.HTTP2 = *t.HTTP2
363 }
364 if t.Protocols != nil {
365 t2.Protocols = &Protocols{}
366 *t2.Protocols = *t.Protocols
367 }
368 if !t.tlsNextProtoWasNil {
369 npm := maps.Clone(t.TLSNextProto)
370 if npm == nil {
371 npm = make(map[string]func(authority string, c *tls.Conn) RoundTripper)
372 }
373 t2.TLSNextProto = npm
374 }
375 return t2
376 }
377
378 type closeIdleConnectionser interface {
379
380
381
382
383
384
385
386
387
388 CloseIdleConnections()
389 }
390
391 func (t *Transport) hasCustomTLSDialer() bool {
392 return t.DialTLS != nil || t.DialTLSContext != nil
393 }
394
395 var http2client = godebug.New("http2client")
396
397
398
399 func (t *Transport) onceSetNextProtoDefaults() {
400 t.tlsNextProtoWasNil = (t.TLSNextProto == nil)
401 if http2client.Value() == "0" {
402 http2client.IncNonDefault()
403 return
404 }
405
406
407
408
409
410
411 altProto, _ := t.altProto.Load().(map[string]RoundTripper)
412 if rv := reflect.ValueOf(altProto["https"]); rv.IsValid() && rv.Type().Kind() == reflect.Struct && rv.Type().NumField() == 1 {
413 if v := rv.Field(0); v.CanInterface() {
414 if h2i, ok := v.Interface().(closeIdleConnectionser); ok {
415 t.closeIdleFunc = h2i
416 return
417 }
418 }
419 }
420
421 if _, ok := t.TLSNextProto["h2"]; ok {
422
423 return
424 }
425 protocols := t.protocols()
426 if !protocols.HTTP2() && !protocols.UnencryptedHTTP2() {
427 return
428 }
429 if omitHTTP2Client {
430 return
431 }
432
433 t.configureHTTP2(protocols)
434 }
435
436 func (t *Transport) protocols() Protocols {
437 if t.Protocols != nil {
438 return *t.Protocols
439 }
440 var p Protocols
441 p.SetHTTP1(true)
442 switch {
443 case t.TLSNextProto != nil:
444
445
446 if t.TLSNextProto["h2"] != nil {
447 p.SetHTTP2(true)
448 }
449 case !t.ForceAttemptHTTP2 && (t.TLSClientConfig != nil || t.Dial != nil || t.DialContext != nil || t.hasCustomTLSDialer()):
450
451
452
453
454
455
456 case http2client.Value() == "0":
457 default:
458 p.SetHTTP2(true)
459 }
460 return p
461 }
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480 func ProxyFromEnvironment(req *Request) (*url.URL, error) {
481 return envProxyFunc()(req.URL)
482 }
483
484
485
486 func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, error) {
487 return func(*Request) (*url.URL, error) {
488 return fixedURL, nil
489 }
490 }
491
492
493
494
495 type transportRequest struct {
496 *Request
497 extra Header
498 trace *httptrace.ClientTrace
499
500 ctx context.Context
501 cancel context.CancelCauseFunc
502
503 mu sync.Mutex
504 err error
505 }
506
507 func (tr *transportRequest) extraHeaders() Header {
508 if tr.extra == nil {
509 tr.extra = make(Header)
510 }
511 return tr.extra
512 }
513
514 func (tr *transportRequest) setError(err error) {
515 tr.mu.Lock()
516 if tr.err == nil {
517 tr.err = err
518 }
519 tr.mu.Unlock()
520 }
521
522
523
524 func (t *Transport) useRegisteredProtocol(req *Request) bool {
525 if req.URL.Scheme == "https" && req.requiresHTTP1() {
526
527
528
529
530 return false
531 }
532 return true
533 }
534
535
536
537
538 func (t *Transport) alternateRoundTripper(req *Request) RoundTripper {
539 if !t.useRegisteredProtocol(req) {
540 return nil
541 }
542 if req.URL.Scheme == "https" && t.h2Config != nil && t.h2Config.ExternalRoundTrip() {
543
544
545
546
547
548
549 return t.h2Config
550 }
551 altProto, _ := t.altProto.Load().(map[string]RoundTripper)
552 return altProto[req.URL.Scheme]
553 }
554
555 func validateTrailers(hdrs Header) string {
556 return validateHeaderFields(hdrs, false)
557 }
558
559 func validateHeadersWithProtocol(hdrs Header) string {
560 return validateHeaderFields(hdrs, true)
561 }
562
563 func validateHeaderFields(hdrs Header, allowProtocol bool) string {
564 for k, vv := range hdrs {
565 if !httpguts.ValidHeaderFieldName(k) && !(allowProtocol && k == ":protocol") {
566 return fmt.Sprintf("field name %q", k)
567 }
568 for _, v := range vv {
569 if !httpguts.ValidHeaderFieldValue(v) {
570
571
572 return fmt.Sprintf("field value for %q", k)
573 }
574 }
575 }
576 return ""
577 }
578
579
580 func (t *Transport) roundTrip(req *Request) (_ *Response, err error) {
581 t.nextProtoOnce.Do(t.onceSetNextProtoDefaults)
582 ctx := req.Context()
583
584 if req.URL == nil {
585 req.closeBody()
586 return nil, errors.New("http: nil Request.URL")
587 }
588 if req.Header == nil {
589 req.closeBody()
590 return nil, errors.New("http: nil Request.Header")
591 }
592 scheme := req.URL.Scheme
593 isHTTP := scheme == "http" || scheme == "https"
594 if isHTTP {
595
596
597 if err := validateHeadersWithProtocol(req.Header); err != "" {
598 req.closeBody()
599 return nil, fmt.Errorf("net/http: invalid header %s", err)
600 }
601
602
603 if err := validateTrailers(req.Trailer); err != "" {
604 req.closeBody()
605 return nil, fmt.Errorf("net/http: invalid trailer %s", err)
606 }
607 }
608
609 origReq := req
610 req = setupRewindBody(req)
611
612 retry := 0
613 if altRT := t.alternateRoundTripper(req); altRT != nil {
614 if resp, err := altRT.RoundTrip(req); err != ErrSkipAltProtocol {
615 return resp, err
616 }
617 req, err = rewindBody(req)
618 if err != nil {
619 return nil, err
620 }
621 }
622 if !isHTTP {
623 req.closeBody()
624 return nil, badStringError("unsupported protocol scheme", scheme)
625 }
626 if req.Method != "" && !validMethod(req.Method) {
627 req.closeBody()
628 return nil, fmt.Errorf("net/http: invalid method %q", req.Method)
629 }
630 if req.URL.Host == "" {
631 req.closeBody()
632 return nil, errors.New("http: no Host in request URL")
633 }
634
635
636
637
638
639
640 ctx, cancel := context.WithCancelCause(req.Context())
641
642
643 if origReq.Cancel != nil {
644 go awaitLegacyCancel(ctx, cancel, origReq)
645 }
646
647 defer func() {
648 if err != nil {
649 cancel(err)
650 } else {
651 cancel(errRequestDone)
652 }
653 }()
654
655 for {
656 select {
657 case <-ctx.Done():
658 req.closeBody()
659 return nil, context.Cause(ctx)
660 default:
661 }
662
663 cm, err := t.connectMethodForRequest(req)
664 if err != nil {
665 req.closeBody()
666 return nil, err
667 }
668
669
670
671
672
673 pconn, canRetry, err := t.getConn(ctx, cm, req.wantsClose())
674 if err != nil {
675 req.closeBody()
676 return nil, err
677 }
678
679 resp, err := pconn.cc.RoundTrip(req)
680 if err == nil {
681 resp.Request = origReq
682 return resp, nil
683 }
684
685
686 var shouldRetry, backoff bool
687 if http2isNoCachedConnError(err) {
688
689 shouldRetry = true
690 backoff = false
691 t.poolRemoveConn(pconn)
692 } else {
693 shouldRetry, backoff = shouldRetryRequest(retry, canRetry, req, err)
694 }
695 if !shouldRetry {
696
697
698 if e, ok := err.(nothingWrittenError); ok {
699 err = e.error
700 }
701 if e, ok := err.(transportReadFromServerError); ok {
702 err = e.err
703 }
704 if b, ok := req.Body.(*readTrackingBody); ok && !b.didClose.Load() {
705
706
707
708 req.closeBody()
709 }
710 return nil, err
711 }
712 testHookRoundTripRetried()
713
714
715 req, err = rewindBody(req)
716 if err != nil {
717 return nil, err
718 }
719
720 if !backoff {
721 continue
722 }
723 if pconn.cc.Proto() >= 2 && retry > 0 {
724
725 backoff := float64(uint(1) << (uint(retry) - 1))
726 backoff += backoff * (0.1 * rand.Float64())
727 d := time.Duration(float64(time.Second) * backoff)
728 select {
729 case <-time.After(d):
730 case <-ctx.Done():
731 req.closeBody()
732 return nil, context.Cause(ctx)
733 }
734 }
735 retry++
736 }
737 }
738
739 func http2isNoCachedConnError(err error) bool {
740 _, ok := err.(interface{ IsHTTP2NoCachedConnError() })
741 return ok
742 }
743
744 func awaitLegacyCancel(ctx context.Context, cancel context.CancelCauseFunc, req *Request) {
745 select {
746 case <-req.Cancel:
747 cancel(errRequestCanceled)
748 case <-ctx.Done():
749 }
750 }
751
752 var errCannotRewind = errors.New("net/http: cannot rewind body after connection loss")
753
754 type readTrackingBody struct {
755 io.ReadCloser
756 didRead bool
757 didClose atomic.Bool
758 }
759
760 func (r *readTrackingBody) Read(data []byte) (int, error) {
761 r.didRead = true
762 return r.ReadCloser.Read(data)
763 }
764
765 func (r *readTrackingBody) Close() error {
766 if !r.didClose.CompareAndSwap(false, true) {
767 return nil
768 }
769 return r.ReadCloser.Close()
770 }
771
772
773
774
775
776 func setupRewindBody(req *Request) *Request {
777 if req.Body == nil || req.Body == NoBody {
778 return req
779 }
780 newReq := *req
781 newReq.Body = &readTrackingBody{ReadCloser: req.Body}
782 return &newReq
783 }
784
785
786
787
788
789 func rewindBody(req *Request) (rewound *Request, err error) {
790 if req.Body == nil || req.Body == NoBody || (!req.Body.(*readTrackingBody).didRead && !req.Body.(*readTrackingBody).didClose.Load()) {
791 return req, nil
792 }
793 if !req.Body.(*readTrackingBody).didClose.Load() {
794 req.closeBody()
795 }
796 if req.GetBody == nil {
797 return nil, errCannotRewind
798 }
799 body, err := req.GetBody()
800 if err != nil {
801 return nil, err
802 }
803 newReq := *req
804 newReq.Body = &readTrackingBody{ReadCloser: body}
805 return &newReq, nil
806 }
807
808
809
810
811 func shouldRetryRequest(retry int, canRetry bool, req *Request, err error) (shouldRetry, backoff bool) {
812 if retry > 6 {
813 return false, false
814 }
815 if http2isNoCachedConnError(err) {
816
817
818
819
820
821
822 return true, false
823 }
824 if err == errMissingHost {
825
826 return false, false
827 }
828 if e, ok := errors.AsType[internal.RetryableError](err); ok {
829
830
831
832
833
834
835 return true, e.Backoff
836 }
837 if !canRetry {
838
839
840
841
842
843
844
845 return false, false
846 }
847 if _, ok := err.(nothingWrittenError); ok {
848
849
850 return req.outgoingLength() == 0 || req.GetBody != nil, false
851 }
852 if !req.isReplayable() {
853
854 return false, false
855 }
856 if _, ok := err.(transportReadFromServerError); ok {
857
858
859 return true, false
860 }
861 if err == errServerClosedIdle {
862
863
864
865 return true, false
866 }
867 return false, false
868 }
869
870
871 var ErrSkipAltProtocol = internal.ErrSkipAltProtocol
872
873
874
875
876
877
878
879
880
881
882
883 func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper) {
884 if err := t.registerProtocol(scheme, rt); err != nil {
885 panic(err)
886 }
887 }
888
889 func (t *Transport) registerProtocol(scheme string, rt RoundTripper) error {
890 t.altMu.Lock()
891 defer t.altMu.Unlock()
892
893 if scheme == "http/2" {
894 if t.h2Config != nil {
895 panic("http: HTTP/2 Transport already registered")
896 }
897 var ok bool
898 if t.h2Config, ok = rt.(http2ExternalTransportConfig); !ok {
899 panic("http: HTTP/2 configuration does not implement ExternalTransportConfig")
900 }
901 t.registerHTTP2Config()
902 }
903
904 if scheme == "http/3" {
905 if t.h3Transport != nil {
906 panic("http: HTTP/3 Transport already registered")
907 }
908 var ok bool
909 if t.h3Transport, ok = rt.(http3Transport); !ok {
910 panic("http: HTTP/3 RoundTripper does not implement DialClientConn")
911 }
912
913
914 if r, ok := rt.(interface {
915 Registered(*Transport)
916 }); ok {
917 r.Registered(t)
918 }
919 return nil
920 }
921
922 oldMap, _ := t.altProto.Load().(map[string]RoundTripper)
923 if _, exists := oldMap[scheme]; exists {
924 return errors.New("protocol " + scheme + " already registered")
925 }
926 newMap := maps.Clone(oldMap)
927 if newMap == nil {
928 newMap = make(map[string]RoundTripper)
929 }
930 newMap[scheme] = rt
931 t.altProto.Store(newMap)
932 return nil
933 }
934
935
936
937
938
939 func (t *Transport) CloseIdleConnections() {
940 t.nextProtoOnce.Do(t.onceSetNextProtoDefaults)
941
942 t.poolCloseIdleConnections()
943
944
945
946
947
948
949
950 if t2 := t.closeIdleFunc; t2 != nil {
951 t2.CloseIdleConnections()
952 }
953
954 if cc, ok := t.h3Transport.(closeIdleConnectionser); ok {
955 cc.CloseIdleConnections()
956 }
957 }
958
959
960
961
962
963 func (t *Transport) CancelRequest(req *Request) {
964 }
965
966
967
968
969
970 var (
971 envProxyOnce sync.Once
972 envProxyFuncValue func(*url.URL) (*url.URL, error)
973 )
974
975
976
977 func envProxyFunc() func(*url.URL) (*url.URL, error) {
978 envProxyOnce.Do(func() {
979 envProxyFuncValue = httpproxy.FromEnvironment().ProxyFunc()
980 })
981 return envProxyFuncValue
982 }
983
984
985 func resetProxyConfig() {
986 envProxyOnce = sync.Once{}
987 envProxyFuncValue = nil
988 }
989
990 func (t *Transport) connectMethodForRequest(req *Request) (cm connectMethod, err error) {
991 cm.targetScheme = req.URL.Scheme
992 cm.targetAddr = canonicalAddr(req.URL)
993 if t.Proxy != nil {
994 cm.proxyURL, err = t.Proxy(req)
995 }
996 cm.onlyH1 = req.requiresHTTP1()
997 return cm, err
998 }
999
1000
1001
1002 func (cm *connectMethod) proxyAuth() string {
1003 if cm.proxyURL == nil {
1004 return ""
1005 }
1006 if u := cm.proxyURL.User; u != nil {
1007 username := u.Username()
1008 password, _ := u.Password()
1009 return "Basic " + basicAuth(username, password)
1010 }
1011 return ""
1012 }
1013
1014
1015 var (
1016 errKeepAlivesDisabled = errors.New("http: keep alives disabled")
1017 errConnBroken = errors.New("http: connection is in bad state")
1018 errCloseIdle = errors.New("http: CloseIdleConnections was called")
1019 errCloseOnIdle = errors.New("http: connection marked as close-on-idle")
1020 errTooManyIdle = errors.New("http: too many idle connections")
1021 errTooManyIdleHost = errors.New("http: too many idle connections for host")
1022 errReadLoopExiting = errors.New("http: persistConn.readLoop exiting")
1023 errIdleConnTimeout = errors.New("http: idle connection timeout")
1024
1025
1026
1027
1028
1029 errServerClosedIdle = errors.New("http: server closed idle connection")
1030 )
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040 type transportReadFromServerError struct {
1041 err error
1042 }
1043
1044 func (e transportReadFromServerError) Unwrap() error { return e.err }
1045
1046 func (e transportReadFromServerError) Error() string {
1047 return fmt.Sprintf("net/http: Transport failed to read from server: %v", e.err)
1048 }
1049
1050 func (t *Transport) maxIdleConnsPerHost() int {
1051 if v := t.MaxIdleConnsPerHost; v != 0 {
1052 return v
1053 }
1054 return DefaultMaxIdleConnsPerHost
1055 }
1056
1057
1058
1059 func (pc *persistConn) roundTripDone(trace *httptrace.ClientTrace) error {
1060 putIdle := func(err error) {
1061 if !pc.isClientConn && trace != nil && trace.PutIdleConn != nil && err != errKeepAlivesDisabled && err != errCloseIdle && !pc.t.closeConnsOnIdle() {
1062 trace.PutIdleConn(err)
1063 }
1064 }
1065 if err := func() error {
1066 pc.mu.Lock()
1067 defer pc.mu.Unlock()
1068 if pc.closed != nil {
1069 return errConnBroken
1070 }
1071 if !pc.inFlight {
1072 panic("pconn is not in flight")
1073 }
1074 pc.inFlight = false
1075 select {
1076 case pc.availch <- struct{}{}:
1077 default:
1078 panic("unable to make pconn available")
1079 }
1080 return nil
1081 }(); err != nil {
1082 putIdle(err)
1083 return err
1084 }
1085 var err error
1086 if pc.internalStateHook != nil {
1087 err = pc.internalStateHook()
1088 }
1089 putIdle(err)
1090 if err != nil {
1091 return err
1092 }
1093
1094
1095 pc.mu.Lock()
1096 defer pc.mu.Unlock()
1097 return pc.closed
1098 }
1099
1100 var zeroDialer net.Dialer
1101
1102 func (t *Transport) dial(ctx context.Context, network, addr string) (net.Conn, error) {
1103 if t.DialContext != nil {
1104 c, err := t.DialContext(ctx, network, addr)
1105 if c == nil && err == nil {
1106 err = errors.New("net/http: Transport.DialContext hook returned (nil, nil)")
1107 }
1108 return c, err
1109 }
1110 if t.Dial != nil {
1111 c, err := t.Dial(network, addr)
1112 if c == nil && err == nil {
1113 err = errors.New("net/http: Transport.Dial hook returned (nil, nil)")
1114 }
1115 return c, err
1116 }
1117 return zeroDialer.DialContext(ctx, network, addr)
1118 }
1119
1120 func (t *Transport) customDialTLS(ctx context.Context, network, addr string) (conn net.Conn, err error) {
1121 if t.DialTLSContext != nil {
1122 conn, err = t.DialTLSContext(ctx, network, addr)
1123 } else {
1124 conn, err = t.DialTLS(network, addr)
1125 }
1126 if conn == nil && err == nil {
1127 err = errors.New("net/http: Transport.DialTLS or DialTLSContext returned (nil, nil)")
1128 }
1129 return
1130 }
1131
1132
1133
1134
1135
1136 func (t *Transport) getConn(ctx context.Context, cm connectMethod, connClose bool) (_ *poolConn, canRetry bool, err error) {
1137 trace := httptrace.ContextClientTrace(ctx)
1138 if trace != nil && trace.GetConn != nil {
1139 trace.GetConn(cm.addr())
1140 }
1141
1142 pconn, info, err := t.poolGetConn(ctx, cm, connClose)
1143 if err != nil {
1144 return nil, false, err
1145 }
1146 info.Reused = pconn.reused.Swap(true)
1147 if !pconn.isAlt() && trace != nil && trace.GotConn != nil {
1148 trace.GotConn(info)
1149 }
1150 canRetry = info.Reused || info.WasIdle
1151 return pconn, canRetry, nil
1152 }
1153
1154 func (t *Transport) tlsConfigForDial(host string) (*tls.Config, error) {
1155 firstTLSHost, _, err := net.SplitHostPort(host)
1156 if err != nil {
1157 return nil, err
1158 }
1159 cfg := cloneTLSConfig(t.TLSClientConfig)
1160 if cfg.ServerName == "" {
1161 cfg.ServerName = firstTLSHost
1162 }
1163 return cfg, nil
1164 }
1165
1166
1167
1168
1169 func (pconn *persistConn) addTLS(ctx context.Context, addr string, onlyH1 bool, trace *httptrace.ClientTrace) error {
1170 cfg, err := pconn.t.tlsConfigForDial(addr)
1171 if err != nil {
1172 pconn.conn.Close()
1173 return err
1174 }
1175 if pconn.cacheKey.onlyH1 || onlyH1 {
1176 cfg.NextProtos = nil
1177 }
1178 plainConn := pconn.conn
1179 tlsConn := tls.Client(plainConn, cfg)
1180 errc := make(chan error, 2)
1181 var timer *time.Timer
1182 if d := pconn.t.TLSHandshakeTimeout; d != 0 {
1183 timer = time.AfterFunc(d, func() {
1184 errc <- tlsHandshakeTimeoutError{}
1185 })
1186 }
1187 go func() {
1188 if trace != nil && trace.TLSHandshakeStart != nil {
1189 trace.TLSHandshakeStart()
1190 }
1191 err := tlsConn.HandshakeContext(ctx)
1192 if timer != nil {
1193 timer.Stop()
1194 }
1195 errc <- err
1196 }()
1197 if err := <-errc; err != nil {
1198 plainConn.Close()
1199 if err == (tlsHandshakeTimeoutError{}) {
1200
1201
1202 <-errc
1203 }
1204 if trace != nil && trace.TLSHandshakeDone != nil {
1205 trace.TLSHandshakeDone(tls.ConnectionState{}, err)
1206 }
1207 return err
1208 }
1209 cs := tlsConn.ConnectionState()
1210 if trace != nil && trace.TLSHandshakeDone != nil {
1211 trace.TLSHandshakeDone(cs, nil)
1212 }
1213 pconn.tlsState = &cs
1214 pconn.conn = tlsConn
1215 return nil
1216 }
1217
1218 type erringRoundTripper interface {
1219 RoundTripErr() error
1220 }
1221
1222 var testHookProxyConnectTimeout = context.WithTimeout
1223
1224 func (t *Transport) dialConn(ctx context.Context, cm connectMethod, isClientConn bool, internalStateHook func() error) (_ genericClientConn, err error) {
1225
1226
1227
1228
1229 if p := t.protocols(); p.http3() {
1230 if p.HTTP1() || p.HTTP2() || p.UnencryptedHTTP2() {
1231 return nil, errors.New("http: when using HTTP3, Transport.Protocols must contain only HTTP3")
1232 }
1233 if t.h3Transport == nil {
1234 return nil, errors.New("http: Transport.Protocols contains HTTP3, but Transport does not support HTTP/3")
1235 }
1236 tlsConfig, err := t.tlsConfigForDial(cm.addr())
1237 if err != nil {
1238 return nil, err
1239 }
1240 tlsConfig.NextProtos = []string{"h3"}
1241 rt, err := t.h3Transport.DialClientConn(ctx, cm.addr(), cm.proxyURL, tlsConfig, internalStateHook)
1242 if err != nil {
1243 return nil, err
1244 }
1245 return rt.(genericClientConn), nil
1246 }
1247
1248
1249 pconn := &persistConn{
1250 t: t,
1251 cacheKey: cm.key(),
1252 reqch: make(chan requestAndChan, 1),
1253 writech: make(chan writeRequest, 1),
1254 closech: make(chan struct{}),
1255 writeErrCh: make(chan error, 1),
1256 writeLoopDone: make(chan struct{}),
1257 isClientConn: isClientConn,
1258 internalStateHook: internalStateHook,
1259 }
1260 trace := httptrace.ContextClientTrace(ctx)
1261 wrapErr := func(err error) error {
1262 if cm.proxyURL != nil {
1263
1264 return &net.OpError{Op: "proxyconnect", Net: "tcp", Err: err}
1265 }
1266 return err
1267 }
1268
1269 if cc, err := t.http2ExternalDial(ctx, cm, isClientConn, internalStateHook); err != errors.ErrUnsupported {
1270 if err != nil {
1271 return nil, err
1272 }
1273 return cc, nil
1274 }
1275
1276 if cm.scheme() == "https" && t.hasCustomTLSDialer() {
1277 var err error
1278 pconn.conn, err = t.customDialTLS(ctx, "tcp", cm.addr())
1279 if err != nil {
1280 return nil, wrapErr(err)
1281 }
1282 type connectionStater interface {
1283 ConnectionState() tls.ConnectionState
1284 }
1285 type handshaker interface {
1286 HandshakeContext(context.Context) error
1287 }
1288 if cstater, ok := pconn.conn.(connectionStater); ok {
1289 if trace != nil && trace.TLSHandshakeStart != nil {
1290 trace.TLSHandshakeStart()
1291 }
1292 if handshaker, ok := cstater.(handshaker); ok {
1293
1294
1295 if err := handshaker.HandshakeContext(ctx); err != nil {
1296 go pconn.conn.Close()
1297 if trace != nil && trace.TLSHandshakeDone != nil {
1298 trace.TLSHandshakeDone(tls.ConnectionState{}, err)
1299 }
1300 return nil, err
1301 }
1302 }
1303 cs := cstater.ConnectionState()
1304 if trace != nil && trace.TLSHandshakeDone != nil {
1305 trace.TLSHandshakeDone(cs, nil)
1306 }
1307 pconn.tlsState = &cs
1308 }
1309 } else {
1310 conn, err := t.dial(ctx, "tcp", cm.addr())
1311 if err != nil {
1312 return nil, wrapErr(err)
1313 }
1314 pconn.conn = conn
1315 if cm.scheme() == "https" {
1316 onlyH1 := cm.proxyURL != nil
1317 if err = pconn.addTLS(ctx, cm.addr(), onlyH1, trace); err != nil {
1318 return nil, wrapErr(err)
1319 }
1320 }
1321 }
1322
1323
1324 switch {
1325 case cm.proxyURL == nil:
1326
1327 case cm.proxyURL.Scheme == "socks5" || cm.proxyURL.Scheme == "socks5h":
1328 conn := pconn.conn
1329 d := socksNewDialer("tcp", conn.RemoteAddr().String())
1330 if u := cm.proxyURL.User; u != nil {
1331 auth := &socksUsernamePassword{
1332 Username: u.Username(),
1333 }
1334 auth.Password, _ = u.Password()
1335 d.AuthMethods = []socksAuthMethod{
1336 socksAuthMethodNotRequired,
1337 socksAuthMethodUsernamePassword,
1338 }
1339 d.Authenticate = auth.Authenticate
1340 }
1341 if _, err := d.DialWithConn(ctx, conn, "tcp", cm.targetAddr); err != nil {
1342 conn.Close()
1343 return nil, err
1344 }
1345 case cm.targetScheme == "http":
1346 pconn.isProxy = true
1347 if pa := cm.proxyAuth(); pa != "" {
1348 pconn.mutateHeaderFunc = func(h Header) {
1349 h.Set("Proxy-Authorization", pa)
1350 }
1351 }
1352 case cm.targetScheme == "https":
1353 conn := pconn.conn
1354 var hdr Header
1355 if t.GetProxyConnectHeader != nil {
1356 var err error
1357 hdr, err = t.GetProxyConnectHeader(ctx, cm.proxyURL, cm.targetAddr)
1358 if err != nil {
1359 conn.Close()
1360 return nil, err
1361 }
1362 } else {
1363 hdr = t.ProxyConnectHeader
1364 }
1365 if hdr == nil {
1366 hdr = make(Header)
1367 }
1368 if pa := cm.proxyAuth(); pa != "" {
1369 hdr = hdr.Clone()
1370 hdr.Set("Proxy-Authorization", pa)
1371 }
1372 connectReq := &Request{
1373 Method: "CONNECT",
1374 URL: &url.URL{Opaque: cm.targetAddr},
1375 Host: cm.targetAddr,
1376 Header: hdr,
1377 }
1378
1379
1380
1381
1382 connectCtx, cancel := testHookProxyConnectTimeout(ctx, 1*time.Minute)
1383 defer cancel()
1384
1385 didReadResponse := make(chan struct{})
1386 var (
1387 resp *Response
1388 err error
1389 )
1390
1391 go func() {
1392 defer close(didReadResponse)
1393 err = connectReq.Write(conn)
1394 if err != nil {
1395 return
1396 }
1397
1398
1399 br := bufio.NewReader(&io.LimitedReader{R: conn, N: t.maxHeaderResponseSize()})
1400 resp, err = ReadResponse(br, connectReq)
1401 }()
1402 select {
1403 case <-connectCtx.Done():
1404 conn.Close()
1405 <-didReadResponse
1406 return nil, connectCtx.Err()
1407 case <-didReadResponse:
1408
1409 }
1410 if err != nil {
1411 conn.Close()
1412 return nil, err
1413 }
1414
1415 if t.OnProxyConnectResponse != nil {
1416 err = t.OnProxyConnectResponse(ctx, cm.proxyURL, connectReq, resp)
1417 if err != nil {
1418 conn.Close()
1419 return nil, err
1420 }
1421 }
1422
1423 if resp.StatusCode != 200 {
1424 _, text, ok := strings.Cut(resp.Status, " ")
1425 conn.Close()
1426 if !ok {
1427 return nil, errors.New("unknown status code")
1428 }
1429 return nil, errors.New(text)
1430 }
1431 }
1432
1433 if cm.proxyURL != nil && cm.targetScheme == "https" {
1434 const onlyH1 = false
1435 if err := pconn.addTLS(ctx, cm.targetAddr, onlyH1, trace); err != nil {
1436 return nil, err
1437 }
1438 }
1439
1440
1441 if !pconn.isProxy {
1442
1443 unencryptedHTTP2 := pconn.tlsState == nil &&
1444 t.Protocols != nil &&
1445 t.Protocols.UnencryptedHTTP2() &&
1446 !t.Protocols.HTTP1()
1447
1448 http2 := unencryptedHTTP2 ||
1449 (pconn.tlsState != nil && pconn.tlsState.NegotiatedProtocol == "h2")
1450
1451 if http2 && t.h2Transport != nil {
1452
1453 cc, err := t.http2NewClientConn(pconn.conn, isClientConn, internalStateHook)
1454 if err == nil {
1455 return cc, nil
1456 }
1457 if err != errors.ErrUnsupported {
1458 return nil, err
1459 }
1460 }
1461
1462 if isClientConn && (unencryptedHTTP2 || (pconn.tlsState != nil && pconn.tlsState.NegotiatedProtocol == "h2")) {
1463
1464
1465 altProto, _ := t.altProto.Load().(map[string]RoundTripper)
1466 h2, ok := altProto["https"].(newClientConner)
1467 if !ok {
1468 return nil, errors.New("http: HTTP/2 implementation does not support NewClientConn (update golang.org/x/net?)")
1469 }
1470 var stateHook func()
1471 if internalStateHook != nil {
1472 stateHook = func() { internalStateHook() }
1473 }
1474 rt, err := h2.NewClientConn(pconn.conn, stateHook)
1475 if err != nil {
1476 pconn.conn.Close()
1477 return nil, err
1478 }
1479 cc, ok := rt.(externalClientConn)
1480 if !ok {
1481 return nil, errors.New("http: NewClientConn returned something that is not a ClientConn")
1482 }
1483 return externalHTTP2Conn{cc}, nil
1484 }
1485
1486 wrapTLSNextProtoRoundTripper := func(rt RoundTripper) (genericClientConn, error) {
1487 if e, ok := rt.(erringRoundTripper); ok {
1488
1489 return nil, e.RoundTripErr()
1490 }
1491 return &altClientConn{rt: rt}, nil
1492 }
1493 if unencryptedHTTP2 {
1494
1495 next, ok := t.TLSNextProto[nextProtoUnencryptedHTTP2]
1496 if !ok {
1497 return nil, errors.New("http: Transport does not support unencrypted HTTP/2")
1498 }
1499 alt := next(cm.targetAddr, unencryptedTLSConn(pconn.conn))
1500 return wrapTLSNextProtoRoundTripper(alt)
1501 }
1502
1503 if s := pconn.tlsState; s != nil && s.NegotiatedProtocolIsMutual && s.NegotiatedProtocol != "" {
1504
1505 tlsConn, tlsConnOK := pconn.conn.(*tls.Conn)
1506 if next, ok := t.TLSNextProto[s.NegotiatedProtocol]; tlsConnOK && ok {
1507 alt := next(cm.targetAddr, tlsConn)
1508 return wrapTLSNextProtoRoundTripper(alt)
1509 }
1510 }
1511 }
1512
1513
1514 pconn.availch = make(chan struct{}, 1)
1515 pconn.availch <- struct{}{}
1516 pconn.br = bufio.NewReaderSize(pconn, t.readBufferSize())
1517 pconn.bw = bufio.NewWriterSize(persistConnWriter{pconn}, t.writeBufferSize())
1518
1519 go pconn.readLoop()
1520 go pconn.writeLoop()
1521 return pconn, nil
1522 }
1523
1524
1525
1526
1527
1528
1529
1530 type persistConnWriter struct {
1531 pc *persistConn
1532 }
1533
1534 func (w persistConnWriter) Write(p []byte) (n int, err error) {
1535 n, err = w.pc.conn.Write(p)
1536 w.pc.nwrite += int64(n)
1537 return
1538 }
1539
1540
1541
1542
1543 func (w persistConnWriter) ReadFrom(r io.Reader) (n int64, err error) {
1544 n, err = io.Copy(w.pc.conn, r)
1545 w.pc.nwrite += n
1546 return
1547 }
1548
1549 var _ io.ReaderFrom = (*persistConnWriter)(nil)
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567 type connectMethod struct {
1568 _ incomparable
1569 proxyURL *url.URL
1570 targetScheme string
1571
1572
1573
1574 targetAddr string
1575 onlyH1 bool
1576 }
1577
1578 func (cm *connectMethod) key() connectMethodKey {
1579 proxyStr := ""
1580 targetAddr := cm.targetAddr
1581 if cm.proxyURL != nil {
1582 proxyStr = cm.proxyURL.String()
1583 if (cm.proxyURL.Scheme == "http" || cm.proxyURL.Scheme == "https") && cm.targetScheme == "http" {
1584 targetAddr = ""
1585 }
1586 }
1587 return connectMethodKey{
1588 proxy: proxyStr,
1589 scheme: cm.targetScheme,
1590 addr: targetAddr,
1591 onlyH1: cm.onlyH1,
1592 }
1593 }
1594
1595
1596 func (cm *connectMethod) scheme() string {
1597 if cm.proxyURL != nil {
1598 return cm.proxyURL.Scheme
1599 }
1600 return cm.targetScheme
1601 }
1602
1603
1604 func (cm *connectMethod) addr() string {
1605 if cm.proxyURL != nil {
1606 return canonicalAddr(cm.proxyURL)
1607 }
1608 return cm.targetAddr
1609 }
1610
1611
1612
1613
1614 type connectMethodKey struct {
1615 proxy, scheme, addr string
1616 onlyH1 bool
1617 }
1618
1619 func (k connectMethodKey) String() string {
1620
1621 var h1 string
1622 if k.onlyH1 {
1623 h1 = ",h1"
1624 }
1625 return fmt.Sprintf("%s|%s%s|%s", k.proxy, k.scheme, h1, k.addr)
1626 }
1627
1628
1629
1630 type persistConn struct {
1631 t *Transport
1632 cacheKey connectMethodKey
1633 conn net.Conn
1634 tlsState *tls.ConnectionState
1635 br *bufio.Reader
1636 bw *bufio.Writer
1637 nwrite int64
1638 reqch chan requestAndChan
1639 writech chan writeRequest
1640 closech chan struct{}
1641 availch chan struct{}
1642 isProxy bool
1643 isClientConn bool
1644 sawEOF bool
1645 readLimit int64
1646
1647
1648
1649
1650 writeErrCh chan error
1651
1652 writeLoopDone chan struct{}
1653
1654 mu sync.Mutex
1655 numExpectedResponses int
1656 closed error
1657 canceledErr error
1658 reserved bool
1659 inFlight bool
1660 internalStateHook func() error
1661
1662
1663
1664
1665 mutateHeaderFunc func(Header)
1666 }
1667
1668 func (pc *persistConn) maxHeaderResponseSize() int64 {
1669 return pc.t.maxHeaderResponseSize()
1670 }
1671
1672 func (pc *persistConn) Read(p []byte) (n int, err error) {
1673 if pc.readLimit <= 0 {
1674 return 0, fmt.Errorf("read limit of %d bytes exhausted", pc.maxHeaderResponseSize())
1675 }
1676 if int64(len(p)) > pc.readLimit {
1677 p = p[:pc.readLimit]
1678 }
1679 n, err = pc.conn.Read(p)
1680 if err == io.EOF {
1681 pc.sawEOF = true
1682 }
1683 pc.readLimit -= int64(n)
1684 return
1685 }
1686
1687
1688 func (pc *persistConn) isBroken() bool {
1689 pc.mu.Lock()
1690 b := pc.closed != nil
1691 pc.mu.Unlock()
1692 return b
1693 }
1694
1695
1696 func (pc *persistConn) canceled() error {
1697 pc.mu.Lock()
1698 defer pc.mu.Unlock()
1699 return pc.canceledErr
1700 }
1701
1702 func (pc *persistConn) cancelRequest(err error) {
1703 pc.mu.Lock()
1704 defer pc.mu.Unlock()
1705 pc.canceledErr = err
1706 pc.closeLocked(errRequestCanceled)
1707 }
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717 func (pc *persistConn) mapRoundTripError(req *transportRequest, startBytesWritten int64, err error) error {
1718 if err == nil {
1719 return nil
1720 }
1721
1722
1723
1724
1725
1726
1727
1728
1729 <-pc.writeLoopDone
1730
1731
1732
1733
1734 if cerr := pc.canceled(); cerr != nil {
1735 return cerr
1736 }
1737
1738
1739 req.mu.Lock()
1740 reqErr := req.err
1741 req.mu.Unlock()
1742 if reqErr != nil {
1743 return reqErr
1744 }
1745
1746 if err == errServerClosedIdle {
1747
1748 return err
1749 }
1750
1751 if _, ok := err.(transportReadFromServerError); ok {
1752 if pc.nwrite == startBytesWritten {
1753 return nothingWrittenError{err}
1754 }
1755
1756 return err
1757 }
1758 if pc.isBroken() {
1759 if pc.nwrite == startBytesWritten {
1760 return nothingWrittenError{err}
1761 }
1762 return fmt.Errorf("net/http: HTTP/1.x transport connection broken: %w", err)
1763 }
1764 return err
1765 }
1766
1767
1768
1769
1770 var errCallerOwnsConn = errors.New("read loop ending; caller owns writable underlying conn")
1771
1772
1773
1774
1775 const maxPostCloseReadBytes = 256 << 10
1776
1777
1778
1779
1780 const maxPostCloseReadTime = 50 * time.Millisecond
1781
1782 func maybeDrainBody(r io.Reader) bool {
1783 drainedCh := make(chan bool, 1)
1784 go func() {
1785
1786
1787
1788 if b, ok := r.(*body); ok {
1789 b.discardTrailer()
1790 }
1791 if _, err := io.CopyN(io.Discard, r, maxPostCloseReadBytes+1); err == io.EOF {
1792 drainedCh <- true
1793 } else {
1794 drainedCh <- false
1795 }
1796 }()
1797 select {
1798 case drained := <-drainedCh:
1799 return drained
1800 case <-time.After(maxPostCloseReadTime):
1801 return false
1802 }
1803 }
1804
1805 type bodyReadStatus uint8
1806
1807 const (
1808 bodyReadEOF bodyReadStatus = iota
1809 bodyReadClosedEarly
1810 bodyReadError
1811 )
1812
1813 func (pc *persistConn) readLoop() {
1814 closeErr := errReadLoopExiting
1815 defer func() {
1816 pc.CloseWithError(closeErr)
1817 if pc.internalStateHook != nil {
1818 pc.internalStateHook()
1819 }
1820 }()
1821
1822 tryPutIdleConn := func(trace *httptrace.ClientTrace) bool {
1823 if err := pc.roundTripDone(trace); err != nil {
1824 closeErr = err
1825 return false
1826 }
1827 return true
1828 }
1829
1830
1831
1832
1833
1834
1835
1836 eofc := make(chan struct{})
1837 defer close(eofc)
1838
1839
1840 testHookMu.Lock()
1841 testHookReadLoopBeforeNextRead := testHookReadLoopBeforeNextRead
1842 testHookMu.Unlock()
1843
1844 alive := true
1845 for alive {
1846 pc.readLimit = pc.maxHeaderResponseSize()
1847 _, err := pc.br.Peek(1)
1848
1849 pc.mu.Lock()
1850 if pc.numExpectedResponses == 0 {
1851 pc.readLoopPeekFailLocked(err)
1852 pc.mu.Unlock()
1853 return
1854 }
1855 pc.mu.Unlock()
1856
1857 rc := <-pc.reqch
1858 trace := rc.treq.trace
1859
1860 var resp *Response
1861 if err == nil {
1862 resp, err = pc.readResponse(rc, trace)
1863 } else {
1864 err = transportReadFromServerError{err}
1865 closeErr = err
1866 }
1867
1868 if err != nil {
1869 if pc.readLimit <= 0 {
1870 err = fmt.Errorf("net/http: server response headers exceeded %d bytes; aborted", pc.maxHeaderResponseSize())
1871 }
1872
1873 select {
1874 case rc.ch <- responseAndError{err: err}:
1875 case <-rc.callerGone:
1876 return
1877 }
1878 return
1879 }
1880 pc.readLimit = maxInt64
1881
1882 pc.mu.Lock()
1883 pc.numExpectedResponses--
1884 pc.mu.Unlock()
1885
1886 bodyWritable := resp.bodyIsWritable()
1887 isConnect := rc.treq.Request.Method == "CONNECT"
1888 hasBody := rc.treq.Request.Method != "HEAD" && resp.ContentLength != 0
1889
1890 if resp.Close || rc.treq.Request.wantsClose() || resp.StatusCode <= 199 || bodyWritable || isConnect {
1891
1892
1893
1894
1895
1896
1897
1898 alive = false
1899 }
1900
1901 if !hasBody || bodyWritable {
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915 waitc := eofc
1916 select {
1917 case rc.ch <- responseAndError{res: resp, waitc: waitc}:
1918 case <-rc.callerGone:
1919 return
1920 }
1921
1922
1923
1924 alive = alive &&
1925 !pc.sawEOF &&
1926 pc.wroteRequest() &&
1927 tryPutIdleConn(trace)
1928 if bodyWritable {
1929 closeErr = errCallerOwnsConn
1930 }
1931 rc.treq.cancel(errRequestDone)
1932
1933
1934 waitc <- struct{}{}
1935
1936
1937
1938
1939 testHookReadLoopBeforeNextRead()
1940 continue
1941 }
1942
1943 waitForBodyRead := make(chan bodyReadStatus, 1)
1944 body := &bodyEOFSignal{
1945 body: resp.Body,
1946 earlyCloseFn: func() error {
1947 waitForBodyRead <- bodyReadClosedEarly
1948 <-eofc
1949 return nil
1950 },
1951 fn: func(err error) error {
1952 if err == io.EOF {
1953 waitForBodyRead <- bodyReadEOF
1954 <-eofc
1955 } else {
1956 waitForBodyRead <- bodyReadError
1957 if err != nil {
1958 if cerr := pc.canceled(); cerr != nil {
1959 return cerr
1960 }
1961 }
1962 }
1963 return err
1964 },
1965 }
1966
1967 resp.Body = body
1968 if rc.addedGzip && ascii.EqualFold(resp.Header.Get("Content-Encoding"), "gzip") {
1969 resp.Body = &httpcommon.GzipReader{Body: body}
1970 resp.Header.Del("Content-Encoding")
1971 resp.Header.Del("Content-Length")
1972 resp.ContentLength = -1
1973 resp.Uncompressed = true
1974 }
1975
1976 select {
1977 case rc.ch <- responseAndError{res: resp}:
1978 case <-rc.callerGone:
1979 return
1980 }
1981
1982
1983
1984
1985 select {
1986 case status := <-waitForBodyRead:
1987 tryPutIdle := func() {
1988 alive = alive &&
1989 !pc.sawEOF &&
1990 pc.wroteRequest() &&
1991 tryPutIdleConn(trace)
1992 }
1993 switch status {
1994 case bodyReadEOF:
1995 tryPutIdle()
1996 eofc <- struct{}{}
1997 case bodyReadClosedEarly:
1998
1999
2000 tryDrain := alive && (pc.isClientConn || !pc.t.closeConnsOnIdle()) && resp.ContentLength <= maxPostCloseReadBytes
2001 eofc <- struct{}{}
2002 if tryDrain && maybeDrainBody(body.body) {
2003 tryPutIdle()
2004 } else {
2005 alive = false
2006 }
2007 case bodyReadError:
2008 alive = false
2009 }
2010 case <-rc.treq.ctx.Done():
2011 alive = false
2012 pc.cancelRequest(context.Cause(rc.treq.ctx))
2013 case <-pc.closech:
2014 alive = false
2015 }
2016
2017 rc.treq.cancel(errRequestDone)
2018 testHookReadLoopBeforeNextRead()
2019 }
2020 }
2021
2022 func (pc *persistConn) readLoopPeekFailLocked(peekErr error) {
2023 if pc.closed != nil {
2024 return
2025 }
2026 if n := pc.br.Buffered(); n > 0 {
2027 buf, _ := pc.br.Peek(n)
2028 if is408Message(buf) {
2029 pc.closeLocked(errServerClosedIdle)
2030 return
2031 } else {
2032 log.Printf("Unsolicited response received on idle HTTP channel starting with %q; err=%v", buf, peekErr)
2033 }
2034 }
2035 if peekErr == io.EOF {
2036
2037 pc.closeLocked(errServerClosedIdle)
2038 } else {
2039 pc.closeLocked(fmt.Errorf("readLoopPeekFailLocked: %w", peekErr))
2040 }
2041 }
2042
2043
2044
2045
2046 func is408Message(buf []byte) bool {
2047 if len(buf) < len("HTTP/1.x 408") {
2048 return false
2049 }
2050 if string(buf[:7]) != "HTTP/1." {
2051 return false
2052 }
2053 return string(buf[8:12]) == " 408"
2054 }
2055
2056
2057
2058
2059 func (pc *persistConn) readResponse(rc requestAndChan, trace *httptrace.ClientTrace) (resp *Response, err error) {
2060 if trace != nil && trace.GotFirstResponseByte != nil {
2061 if peek, err := pc.br.Peek(1); err == nil && len(peek) == 1 {
2062 trace.GotFirstResponseByte()
2063 }
2064 }
2065
2066 continueCh := rc.continueCh
2067 for {
2068 resp, err = ReadResponse(pc.br, rc.treq.Request)
2069 if err != nil {
2070 return
2071 }
2072 resCode := resp.StatusCode
2073 if continueCh != nil && resCode == StatusContinue {
2074 if trace != nil && trace.Got100Continue != nil {
2075 trace.Got100Continue()
2076 }
2077 continueCh <- struct{}{}
2078 continueCh = nil
2079 }
2080 is1xx := 100 <= resCode && resCode <= 199
2081
2082 is1xxNonTerminal := is1xx && resCode != StatusSwitchingProtocols
2083 if is1xxNonTerminal {
2084 if trace != nil && trace.Got1xxResponse != nil {
2085 if err := trace.Got1xxResponse(resCode, textproto.MIMEHeader(resp.Header)); err != nil {
2086 return nil, err
2087 }
2088
2089
2090
2091
2092
2093
2094
2095 pc.readLimit = pc.maxHeaderResponseSize()
2096 }
2097 continue
2098 }
2099 break
2100 }
2101 if resp.isProtocolSwitch() && isProtocolSwitchHeader(rc.treq.Request.Header) {
2102 resp.Body = newReadWriteCloserBody(pc.br, pc.conn)
2103 }
2104 if continueCh != nil {
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117 if resp.Close || rc.treq.Request.Close {
2118 close(continueCh)
2119 } else {
2120 continueCh <- struct{}{}
2121 }
2122 }
2123
2124 resp.TLS = pc.tlsState
2125 return
2126 }
2127
2128
2129
2130
2131 func (pc *persistConn) waitForContinue(continueCh <-chan struct{}) func() bool {
2132 if continueCh == nil {
2133 return nil
2134 }
2135 return func() bool {
2136 timer := time.NewTimer(pc.t.ExpectContinueTimeout)
2137 defer timer.Stop()
2138
2139 select {
2140 case _, ok := <-continueCh:
2141 return ok
2142 case <-timer.C:
2143 return true
2144 case <-pc.closech:
2145 return false
2146 }
2147 }
2148 }
2149
2150 func newReadWriteCloserBody(br *bufio.Reader, rwc io.ReadWriteCloser) io.ReadWriteCloser {
2151 body := &readWriteCloserBody{ReadWriteCloser: rwc}
2152 if br.Buffered() != 0 {
2153 body.br = br
2154 }
2155 return body
2156 }
2157
2158
2159
2160
2161
2162
2163 type readWriteCloserBody struct {
2164 _ incomparable
2165 br *bufio.Reader
2166 io.ReadWriteCloser
2167 }
2168
2169 func (b *readWriteCloserBody) Read(p []byte) (n int, err error) {
2170 if b.br != nil {
2171 if n := b.br.Buffered(); len(p) > n {
2172 p = p[:n]
2173 }
2174 n, err = b.br.Read(p)
2175 if b.br.Buffered() == 0 {
2176 b.br = nil
2177 }
2178 return n, err
2179 }
2180 return b.ReadWriteCloser.Read(p)
2181 }
2182
2183 func (b *readWriteCloserBody) CloseWrite() error {
2184 if cw, ok := b.ReadWriteCloser.(interface{ CloseWrite() error }); ok {
2185 return cw.CloseWrite()
2186 }
2187 return fmt.Errorf("CloseWrite: %w", ErrNotSupported)
2188 }
2189
2190
2191 type nothingWrittenError struct {
2192 error
2193 }
2194
2195 func (nwe nothingWrittenError) Unwrap() error {
2196 return nwe.error
2197 }
2198
2199 func (pc *persistConn) writeLoop() {
2200 defer close(pc.writeLoopDone)
2201 for {
2202 select {
2203 case wr := <-pc.writech:
2204 startBytesWritten := pc.nwrite
2205 err := wr.req.Request.write(pc.bw, pc.isProxy, wr.req.extra, pc.waitForContinue(wr.continueCh))
2206 if bre, ok := err.(requestBodyReadError); ok {
2207 err = bre.error
2208
2209
2210
2211
2212
2213
2214
2215 wr.req.setError(err)
2216 }
2217 if err == nil {
2218 err = pc.bw.Flush()
2219 }
2220 if err != nil {
2221 if pc.nwrite == startBytesWritten {
2222 err = nothingWrittenError{err}
2223 }
2224 }
2225 pc.writeErrCh <- err
2226 wr.ch <- err
2227 if err != nil {
2228
2229 return
2230 }
2231 case <-pc.closech:
2232 return
2233 }
2234 }
2235 }
2236
2237
2238
2239
2240
2241
2242
2243 var maxWriteWaitBeforeConnReuse = 50 * time.Millisecond
2244
2245
2246
2247 func (pc *persistConn) wroteRequest() bool {
2248 select {
2249 case err := <-pc.writeErrCh:
2250
2251
2252 return err == nil
2253 default:
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264 t := time.NewTimer(maxWriteWaitBeforeConnReuse)
2265 defer t.Stop()
2266 select {
2267 case err := <-pc.writeErrCh:
2268 return err == nil
2269 case <-t.C:
2270 return false
2271 }
2272 }
2273 }
2274
2275
2276
2277 type responseAndError struct {
2278 _ incomparable
2279 res *Response
2280 waitc <-chan struct{}
2281 err error
2282 }
2283
2284 type requestAndChan struct {
2285 _ incomparable
2286 treq *transportRequest
2287 ch chan responseAndError
2288
2289
2290
2291
2292 addedGzip bool
2293
2294
2295
2296
2297
2298 continueCh chan<- struct{}
2299
2300 callerGone <-chan struct{}
2301 }
2302
2303
2304
2305
2306
2307 type writeRequest struct {
2308 req *transportRequest
2309 ch chan<- error
2310
2311
2312
2313
2314 continueCh <-chan struct{}
2315 }
2316
2317
2318
2319 type timeoutError struct {
2320 err string
2321 }
2322
2323 func (e *timeoutError) Error() string { return e.err }
2324 func (e *timeoutError) Timeout() bool { return true }
2325 func (e *timeoutError) Temporary() bool { return true }
2326 func (e *timeoutError) Is(err error) bool { return err == context.DeadlineExceeded }
2327
2328 var errTimeout error = &timeoutError{"net/http: timeout awaiting response headers"}
2329
2330
2331
2332 var errRequestCanceled = internal.ErrRequestCanceled
2333 var errRequestCanceledConn = errors.New("net/http: request canceled while waiting for connection")
2334
2335
2336
2337 var errRequestDone = errors.New("net/http: request completed")
2338
2339 func nop() {}
2340
2341
2342 var (
2343 testHookEnterRoundTrip = nop
2344 testHookWaitResLoop = nop
2345 testHookRoundTripRetried = nop
2346
2347 testHookMu sync.Locker = fakeLocker{}
2348 testHookReadLoopBeforeNextRead = nop
2349 )
2350
2351 func (pc *persistConn) waitForAvailability(ctx context.Context) error {
2352 select {
2353 case <-pc.availch:
2354 return nil
2355 case <-pc.closech:
2356 return pc.closed
2357 case <-ctx.Done():
2358 return ctx.Err()
2359 }
2360 }
2361
2362 const postRequestWriteErrorWaitTime = 50 * time.Millisecond
2363
2364 func (pc *persistConn) roundTrip(req *transportRequest) (resp *Response, err error) {
2365 testHookEnterRoundTrip()
2366
2367 pc.mu.Lock()
2368 if !pc.reserved {
2369 select {
2370 case <-pc.availch:
2371 default:
2372 pc.mu.Unlock()
2373 if err := pc.waitForAvailability(req.ctx); err != nil {
2374 return nil, err
2375 }
2376 pc.mu.Lock()
2377 }
2378 }
2379 pc.reserved = false
2380 pc.inFlight = true
2381 pc.numExpectedResponses++
2382 headerFn := pc.mutateHeaderFunc
2383 pc.mu.Unlock()
2384
2385 if headerFn != nil {
2386 headerFn(req.extraHeaders())
2387 }
2388
2389
2390
2391
2392
2393 requestedGzip := false
2394 if !pc.t.DisableCompression &&
2395 req.Header.Get("Accept-Encoding") == "" &&
2396 req.Header.Get("Range") == "" &&
2397 req.Method != "HEAD" {
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410 requestedGzip = true
2411 req.extraHeaders().Set("Accept-Encoding", "gzip")
2412 }
2413
2414 var continueCh chan struct{}
2415 if req.ProtoAtLeast(1, 1) && req.Body != nil && req.expectsContinue() {
2416 continueCh = make(chan struct{}, 1)
2417 }
2418
2419 if pc.t.DisableKeepAlives &&
2420 !req.wantsClose() &&
2421 !isProtocolSwitchHeader(req.Header) &&
2422 !pc.isClientConn {
2423 req.extraHeaders().Set("Connection", "close")
2424 }
2425
2426 gone := make(chan struct{})
2427 defer close(gone)
2428
2429 const debugRoundTrip = false
2430
2431
2432
2433
2434 startBytesWritten := pc.nwrite
2435 writeErrCh := make(chan error, 1)
2436 pc.writech <- writeRequest{req, writeErrCh, continueCh}
2437
2438 resc := make(chan responseAndError)
2439 pc.reqch <- requestAndChan{
2440 treq: req,
2441 ch: resc,
2442 addedGzip: requestedGzip,
2443 continueCh: continueCh,
2444 callerGone: gone,
2445 }
2446
2447 handleResponse := func(re responseAndError) (*Response, error) {
2448 if (re.res == nil) == (re.err == nil) {
2449 panic(fmt.Sprintf("internal error: exactly one of res or err should be set; nil=%v", re.res == nil))
2450 }
2451 if debugRoundTrip {
2452 req.logf("resc recv: %p, %T/%#v", re.res, re.err, re.err)
2453 }
2454 if re.waitc != nil {
2455 <-re.waitc
2456 }
2457 if re.err != nil {
2458 return nil, pc.mapRoundTripError(req, startBytesWritten, re.err)
2459 }
2460 return re.res, nil
2461 }
2462
2463 var writeErr error
2464 var respHeaderTimer <-chan time.Time
2465 ctxDoneChan := req.ctx.Done()
2466 pcClosed := pc.closech
2467 for {
2468 testHookWaitResLoop()
2469 select {
2470 case err := <-writeErrCh:
2471 if debugRoundTrip {
2472 req.logf("writeErrCh recv: %T/%#v", err, err)
2473 }
2474 timeout := pc.t.ResponseHeaderTimeout
2475 if err != nil {
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485 if _, ok := errors.AsType[*net.OpError](err); !ok {
2486 pc.CloseWithError(fmt.Errorf("write error: %w", err))
2487 return nil, pc.mapRoundTripError(req, startBytesWritten, err)
2488 }
2489 writeErr = err
2490 if timeout == 0 {
2491 timeout = postRequestWriteErrorWaitTime
2492 } else {
2493 timeout = min(timeout, postRequestWriteErrorWaitTime)
2494 }
2495 }
2496 if timeout > 0 {
2497 if debugRoundTrip {
2498 req.logf("starting timer for %v", timeout)
2499 }
2500 timer := time.NewTimer(timeout)
2501 respHeaderTimer = timer.C
2502 }
2503 case <-pcClosed:
2504 select {
2505 case re := <-resc:
2506
2507
2508
2509 return handleResponse(re)
2510 default:
2511 }
2512 if debugRoundTrip {
2513 req.logf("closech recv: %T %#v", pc.closed, pc.closed)
2514 }
2515 return nil, pc.mapRoundTripError(req, startBytesWritten, pc.closed)
2516 case <-respHeaderTimer:
2517 if debugRoundTrip {
2518 req.logf("timeout waiting for response headers.")
2519 }
2520 if writeErr != nil {
2521
2522
2523 pc.CloseWithError(fmt.Errorf("write error: %w", writeErr))
2524 return nil, pc.mapRoundTripError(req, startBytesWritten, writeErr)
2525 }
2526 pc.CloseWithError(errTimeout)
2527 return nil, errTimeout
2528 case re := <-resc:
2529 return handleResponse(re)
2530 case <-ctxDoneChan:
2531 select {
2532 case re := <-resc:
2533
2534
2535
2536 return handleResponse(re)
2537 default:
2538 }
2539 pc.cancelRequest(context.Cause(req.ctx))
2540 }
2541 }
2542 }
2543
2544
2545
2546 type tLogKey struct{}
2547
2548 func (tr *transportRequest) logf(format string, args ...any) {
2549 if logf, ok := tr.Request.Context().Value(tLogKey{}).(func(string, ...any)); ok {
2550 logf(time.Now().Format(time.RFC3339Nano)+": "+format, args...)
2551 }
2552 }
2553
2554
2555
2556
2557
2558
2559 func (pc *persistConn) CloseWithError(err error) {
2560 pc.mu.Lock()
2561 defer pc.mu.Unlock()
2562 pc.closeLocked(err)
2563 }
2564
2565 func (pc *persistConn) closeLocked(err error) {
2566 if err == nil {
2567 panic("nil error")
2568 }
2569 if pc.closed == nil {
2570 pc.closed = err
2571 if err != errCallerOwnsConn {
2572 pc.conn.Close()
2573 }
2574 close(pc.closech)
2575 }
2576 pc.mutateHeaderFunc = nil
2577 }
2578
2579 func schemePort(scheme string) string {
2580 switch scheme {
2581 case "http":
2582 return "80"
2583 case "https":
2584 return "443"
2585 case "socks5", "socks5h":
2586 return "1080"
2587 default:
2588 return ""
2589 }
2590 }
2591
2592 func idnaASCIIFromURL(url *url.URL) string {
2593 addr := url.Hostname()
2594 if v, err := idnaASCII(addr); err == nil && v != "" {
2595 addr = v
2596 }
2597 return addr
2598 }
2599
2600
2601 func canonicalAddr(url *url.URL) string {
2602 port := url.Port()
2603 if port == "" {
2604 port = schemePort(url.Scheme)
2605 }
2606 return net.JoinHostPort(idnaASCIIFromURL(url), port)
2607 }
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620 type bodyEOFSignal struct {
2621 body io.ReadCloser
2622 mu sync.Mutex
2623 closed bool
2624 rerr error
2625 fn func(error) error
2626 earlyCloseFn func() error
2627 }
2628
2629 var errReadOnClosedResBody = errors.New("http: read on closed response body")
2630
2631 func (es *bodyEOFSignal) Read(p []byte) (n int, err error) {
2632 es.mu.Lock()
2633 closed, rerr := es.closed, es.rerr
2634 es.mu.Unlock()
2635 if closed {
2636 return 0, errReadOnClosedResBody
2637 }
2638 if rerr != nil {
2639 return 0, rerr
2640 }
2641
2642 n, err = es.body.Read(p)
2643 if err != nil {
2644 es.mu.Lock()
2645 defer es.mu.Unlock()
2646 if es.rerr == nil {
2647 es.rerr = err
2648 }
2649 err = es.condfn(err)
2650 }
2651 return
2652 }
2653
2654 func (es *bodyEOFSignal) Close() error {
2655 es.mu.Lock()
2656 defer es.mu.Unlock()
2657 if es.closed {
2658 return nil
2659 }
2660 es.closed = true
2661 if es.earlyCloseFn != nil && es.rerr == nil {
2662 earlyCloseFn := es.earlyCloseFn
2663 es.earlyCloseFn = nil
2664 es.fn = nil
2665 return earlyCloseFn()
2666 }
2667 if es.rerr != nil && es.rerr != io.EOF {
2668
2669
2670 return nil
2671 }
2672 err := es.body.Close()
2673 return es.condfn(err)
2674 }
2675
2676
2677 func (es *bodyEOFSignal) condfn(err error) error {
2678 if es.fn == nil {
2679 return err
2680 }
2681 fn := es.fn
2682 es.fn = nil
2683 es.earlyCloseFn = nil
2684 return fn(err)
2685 }
2686
2687 type tlsHandshakeTimeoutError struct{}
2688
2689 func (tlsHandshakeTimeoutError) Timeout() bool { return true }
2690 func (tlsHandshakeTimeoutError) Temporary() bool { return true }
2691 func (tlsHandshakeTimeoutError) Error() string { return "net/http: TLS handshake timeout" }
2692
2693
2694
2695
2696 type fakeLocker struct{}
2697
2698 func (fakeLocker) Lock() {}
2699 func (fakeLocker) Unlock() {}
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714 func cloneTLSConfig(cfg *tls.Config) *tls.Config {
2715 if cfg == nil {
2716 return &tls.Config{}
2717 }
2718 return cfg.Clone()
2719 }
2720
View as plain text