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