forked from imroc/req
-
Notifications
You must be signed in to change notification settings - Fork 0
/
transport.go
3656 lines (3304 loc) · 104 KB
/
transport.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// HTTP client implementation. See RFC 7230 through 7235.
//
// This is the low-level Transport implementation of http.RoundTripper.
// The high-level interface is in client.go.
package req
import (
"bufio"
"compress/gzip"
"container/list"
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"log"
"mime"
"net"
"net/http"
"net/http/httptrace"
"net/textproto"
"net/url"
"runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/imroc/req/v3/http2"
"github.com/imroc/req/v3/internal/altsvcutil"
"github.com/imroc/req/v3/internal/ascii"
"github.com/imroc/req/v3/internal/common"
"github.com/imroc/req/v3/internal/dump"
"github.com/imroc/req/v3/internal/header"
h2internal "github.com/imroc/req/v3/internal/http2"
"github.com/imroc/req/v3/internal/http3"
"github.com/imroc/req/v3/internal/netutil"
"github.com/imroc/req/v3/internal/socks"
"github.com/imroc/req/v3/internal/transport"
"github.com/imroc/req/v3/internal/util"
"github.com/imroc/req/v3/pkg/altsvc"
reqtls "github.com/imroc/req/v3/pkg/tls"
htmlcharset "golang.org/x/net/html/charset"
"golang.org/x/text/encoding/ianaindex"
"golang.org/x/net/http/httpguts"
)
// httpVersion represents http version.
type httpVersion string
const (
// h1 represents "HTTP/1.1"
h1 httpVersion = "1.1"
// h2 represents "HTTP/2.0"
h2 httpVersion = "2"
// h3 represents "HTTP/3.0"
h3 httpVersion = "3"
)
// defaultMaxIdleConnsPerHost is the default value of Transport's
// MaxIdleConnsPerHost.
const defaultMaxIdleConnsPerHost = 2
// Transport is an implementation of http.RoundTripper that supports HTTP,
// HTTPS, and HTTP proxies (for either HTTP or HTTPS with CONNECT).
//
// By default, Transport caches connections for future re-use.
// This may leave many open connections when accessing many hosts.
// This behavior can be managed using Transport's CloseIdleConnections method
// and the MaxIdleConnsPerHost and DisableKeepAlives fields.
//
// Transports should be reused instead of created as needed.
// Transports are safe for concurrent use by multiple goroutines.
//
// A Transport is a low-level primitive for making HTTP and HTTPS requests.
// For high-level functionality, such as cookies and redirects, see Client.
//
// Transport uses HTTP/1.1 for HTTP URLs and either HTTP/1.1 or HTTP/2
// for HTTPS URLs, depending on whether the server supports HTTP/2,
// and how the Transport is configured. The DefaultTransport supports HTTP/2.
// To explicitly enable HTTP/2 on a transport, use golang.org/x/net/http2
// and call ConfigureTransport. See the package docs for more about HTTP/2.
//
// Responses with status codes in the 1xx range are either handled
// automatically (100 expect-continue) or ignored. The one
// exception is HTTP status code 101 (Switching Protocols), which is
// considered a terminal status and returned by RoundTrip. To see the
// ignored 1xx responses, use the httptrace trace package's
// ClientTrace.Got1xxResponse.
//
// Transport only retries a request upon encountering a network error
// if the request is idempotent and either has no body or has its
// Request.GetBody defined. HTTP requests are considered idempotent if
// they have HTTP methods GET, HEAD, OPTIONS, or TRACE; or if their
// Header map contains an "Idempotency-Key" or "X-Idempotency-Key"
// entry. If the idempotency key value is a zero-length slice, the
// request is treated as idempotent but the header is not sent on the
// wire.
type Transport struct {
Headers http.Header
Cookies []*http.Cookie
idleMu sync.Mutex
closeIdle bool // user has requested to close all idle conns
idleConn map[connectMethodKey][]*persistConn // most recently used at end
idleConnWait map[connectMethodKey]wantConnQueue // waiting getConns
idleLRU connLRU
reqMu sync.Mutex
reqCanceler map[cancelKey]func(error)
connsPerHostMu sync.Mutex
connsPerHost map[connectMethodKey]int
connsPerHostWait map[connectMethodKey]wantConnQueue // waiting getConns
altSvcJar altsvc.Jar
pendingAltSvcs map[string]*pendingAltSvc
pendingAltSvcsMu sync.Mutex
// Force using specific http version
forceHttpVersion httpVersion
transport.Options
t2 *h2internal.Transport // non-nil if http2 wired up
t3 *http3.RoundTripper
// disableAutoDecode, if true, prevents auto detect response
// body's charset and decode it to utf-8
disableAutoDecode bool
// autoDecodeContentType specifies an optional function for determine
// whether the response body should been auto decode to utf-8.
// Only valid when DisableAutoDecode is true.
autoDecodeContentType func(contentType string) bool
wrappedRoundTrip http.RoundTripper
httpRoundTripWrappers []HttpRoundTripWrapper
}
// NewTransport is an alias of T
func NewTransport() *Transport {
return T()
}
// T create a Transport.
func T() *Transport {
t := &Transport{
Options: transport.Options{
Proxy: http.ProxyFromEnvironment,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
TLSClientConfig: &tls.Config{NextProtos: []string{"http/1.1", "h2"}},
},
}
t.t2 = &h2internal.Transport{Options: &t.Options}
return t
}
// HttpRoundTripFunc is a http.RoundTripper implementation, which is a simple function.
type HttpRoundTripFunc func(req *http.Request) (resp *http.Response, err error)
// RoundTrip implements http.RoundTripper.
func (fn HttpRoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return fn(req)
}
// HttpRoundTripWrapper is transport middleware function.
type HttpRoundTripWrapper func(rt http.RoundTripper) http.RoundTripper
// HttpRoundTripWrapperFunc is transport middleware function, more convenient than HttpRoundTripWrapper.
type HttpRoundTripWrapperFunc func(rt http.RoundTripper) HttpRoundTripFunc
func (f HttpRoundTripWrapperFunc) wrapper() HttpRoundTripWrapper {
return func(rt http.RoundTripper) http.RoundTripper {
return f(rt)
}
}
// WrapRoundTripFunc adds a transport middleware function that will give the caller
// an opportunity to wrap the underlying http.RoundTripper.
func (t *Transport) WrapRoundTripFunc(funcs ...HttpRoundTripWrapperFunc) *Transport {
var wrappers []HttpRoundTripWrapper
for _, fn := range funcs {
wrappers = append(wrappers, fn.wrapper())
}
return t.WrapRoundTrip(wrappers...)
}
// WrapRoundTrip adds a transport middleware function that will give the caller
// an opportunity to wrap the underlying http.RoundTripper.
func (t *Transport) WrapRoundTrip(wrappers ...HttpRoundTripWrapper) *Transport {
if len(wrappers) == 0 {
return t
}
if t.wrappedRoundTrip == nil {
t.httpRoundTripWrappers = wrappers
fn := func(req *http.Request) (*http.Response, error) {
return t.roundTrip(req)
}
t.wrappedRoundTrip = HttpRoundTripFunc(fn)
} else {
t.httpRoundTripWrappers = append(t.httpRoundTripWrappers, wrappers...)
}
for _, w := range wrappers {
t.wrappedRoundTrip = w(t.wrappedRoundTrip)
}
return t
}
// DisableAutoDecode disable auto-detect charset and decode to utf-8
// (enabled by default).
func (t *Transport) DisableAutoDecode() *Transport {
t.disableAutoDecode = true
return t
}
// EnableAutoDecode enable auto-detect charset and decode to utf-8
// (enabled by default).
func (t *Transport) EnableAutoDecode() *Transport {
t.disableAutoDecode = false
return t
}
// SetAutoDecodeContentTypeFunc set the function that determines whether the
// specified `Content-Type` should be auto-detected and decode to utf-8.
func (t *Transport) SetAutoDecodeContentTypeFunc(fn func(contentType string) bool) *Transport {
t.autoDecodeContentType = fn
return t
}
// SetAutoDecodeAllContentType enable try auto-detect charset and decode all
// content type to utf-8.
func (t *Transport) SetAutoDecodeAllContentType() *Transport {
t.autoDecodeContentType = func(contentType string) bool {
return true
}
return t
}
// SetAutoDecodeContentType set the content types that will be auto-detected and decode
// to utf-8 (e.g. "json", "xml", "html", "text").
func (t *Transport) SetAutoDecodeContentType(contentTypes ...string) {
t.autoDecodeContentType = autoDecodeContentTypeFunc(contentTypes...)
}
// GetMaxIdleConns returns MaxIdleConns.
func (t *Transport) GetMaxIdleConns() int {
return t.MaxIdleConns
}
// SetMaxIdleConns set the MaxIdleConns, which controls the maximum number of idle (keep-alive)
// connections across all hosts. Zero means no limit.
func (t *Transport) SetMaxIdleConns(max int) *Transport {
t.MaxIdleConns = max
return t
}
// SetMaxConnsPerHost set the MaxConnsPerHost, optionally limits the
// total number of connections per host, including connections in the
// dialing, active, and idle states. On limit violation, dials will block.
//
// Zero means no limit.
func (t *Transport) SetMaxConnsPerHost(max int) *Transport {
t.MaxConnsPerHost = max
return t
}
// SetIdleConnTimeout set the IdleConnTimeout, which is the maximum
// amount of time an idle (keep-alive) connection will remain idle before
// closing itself.
//
// Zero means no limit.
func (t *Transport) SetIdleConnTimeout(timeout time.Duration) *Transport {
t.IdleConnTimeout = timeout
return t
}
// SetTLSHandshakeTimeout set the TLSHandshakeTimeout, which specifies the
// maximum amount of time waiting to wait for a TLS handshake.
//
// Zero means no timeout.
func (t *Transport) SetTLSHandshakeTimeout(timeout time.Duration) *Transport {
t.TLSHandshakeTimeout = timeout
return t
}
// SetResponseHeaderTimeout set the ResponseHeaderTimeout, if non-zero, specifies
// the amount of time to wait for a server's response headers after fully writing
// the request (including its body, if any). This time does not include the time
// to read the response body.
func (t *Transport) SetResponseHeaderTimeout(timeout time.Duration) *Transport {
t.ResponseHeaderTimeout = timeout
return t
}
// SetExpectContinueTimeout set the ExpectContinueTimeout, if non-zero, specifies
// the amount of time to wait for a server's first response headers after fully
// writing the request headers if the request has an "Expect: 100-continue" header.
// Zero means no timeout and causes the body to be sent immediately, without waiting
// for the server to approve.
// This time does not include the time to send the request header.
func (t *Transport) SetExpectContinueTimeout(timeout time.Duration) *Transport {
t.ExpectContinueTimeout = timeout
return t
}
// SetGetProxyConnectHeader set the GetProxyConnectHeader, which optionally specifies a func
// to return headers to send to proxyURL during a CONNECT request to the ip:port target.
// If it returns an error, the Transport's RoundTrip fails with that error. It can
// return (nil, nil) to not add headers.
// If GetProxyConnectHeader is non-nil, ProxyConnectHeader is ignored.
func (t *Transport) SetGetProxyConnectHeader(fn func(ctx context.Context, proxyURL *url.URL, target string) (http.Header, error)) *Transport {
t.GetProxyConnectHeader = fn
return t
}
// SetProxyConnectHeader set the ProxyConnectHeader, which optionally specifies headers to
// send to proxies during CONNECT requests.
// To set the header dynamically, see SetGetProxyConnectHeader.
func (t *Transport) SetProxyConnectHeader(header http.Header) *Transport {
t.ProxyConnectHeader = header
return t
}
// SetReadBufferSize set the ReadBufferSize, which specifies the size of the read buffer used
// when reading from the transport.
// If zero, a default (currently 4KB) is used.
func (t *Transport) SetReadBufferSize(size int) *Transport {
t.ReadBufferSize = size
return t
}
// SetWriteBufferSize set the WriteBufferSize, which specifies the size of the write buffer used
// when writing to the transport.
// If zero, a default (currently 4KB) is used.
func (t *Transport) SetWriteBufferSize(size int) *Transport {
t.WriteBufferSize = size
return t
}
// SetMaxResponseHeaderBytes set the MaxResponseHeaderBytes, which specifies a limit on how many
// response bytes are allowed in the server's response header.
//
// Zero means to use a default limit.
func (t *Transport) SetMaxResponseHeaderBytes(max int64) *Transport {
t.MaxResponseHeaderBytes = max
return t
}
// SetHTTP2MaxHeaderListSize set the http2 MaxHeaderListSize,
// which is the http2 SETTINGS_MAX_HEADER_LIST_SIZE to
// send in the initial settings frame. It is how many bytes
// of response headers are allowed. Unlike the http2 spec, zero here
// means to use a default limit (currently 10MB). If you actually
// want to advertise an unlimited value to the peer, Transport
// interprets the highest possible value here (0xffffffff or 1<<32-1)
// to mean no limit.
func (t *Transport) SetHTTP2MaxHeaderListSize(max uint32) *Transport {
t.t2.MaxHeaderListSize = max
return t
}
// SetHTTP2StrictMaxConcurrentStreams set the http2
// StrictMaxConcurrentStreams, which controls whether the
// server's SETTINGS_MAX_CONCURRENT_STREAMS should be respected
// globally. If false, new TCP connections are created to the
// server as needed to keep each under the per-connection
// SETTINGS_MAX_CONCURRENT_STREAMS limit. If true, the
// server's SETTINGS_MAX_CONCURRENT_STREAMS is interpreted as
// a global limit and callers of RoundTrip block when needed,
// waiting for their turn.
func (t *Transport) SetHTTP2StrictMaxConcurrentStreams(strict bool) *Transport {
t.t2.StrictMaxConcurrentStreams = strict
return t
}
// SetHTTP2ReadIdleTimeout set the http2 ReadIdleTimeout,
// which is the timeout after which a health check using ping
// frame will be carried out if no frame is received on the connection.
// Note that a ping response will is considered a received frame, so if
// there is no other traffic on the connection, the health check will
// be performed every ReadIdleTimeout interval.
// If zero, no health check is performed.
func (t *Transport) SetHTTP2ReadIdleTimeout(timeout time.Duration) *Transport {
t.t2.ReadIdleTimeout = timeout
return t
}
// SetHTTP2PingTimeout set the http2 PingTimeout, which is the timeout
// after which the connection will be closed if a response to Ping is
// not received.
// Defaults to 15s
func (t *Transport) SetHTTP2PingTimeout(timeout time.Duration) *Transport {
t.t2.PingTimeout = timeout
return t
}
// SetHTTP2WriteByteTimeout set the http2 WriteByteTimeout, which is the
// timeout after which the connection will be closed no data can be written
// to it. The timeout begins when data is available to write, and is
// extended whenever any bytes are written.
func (t *Transport) SetHTTP2WriteByteTimeout(timeout time.Duration) *Transport {
t.t2.WriteByteTimeout = timeout
return t
}
// SetHTTP2SettingsFrame set the ordered http2 settings frame.
func (t *Transport) SetHTTP2SettingsFrame(settings ...http2.Setting) *Transport {
t.t2.Settings = settings
return t
}
// SetHTTP2ConnectionFlow set the default http2 connection flow, which is the increment
// value of initial WINDOW_UPDATE frame.
func (t *Transport) SetHTTP2ConnectionFlow(flow uint32) *Transport {
t.t2.ConnectionFlow = flow
return t
}
// SetHTTP2HeaderPriority set the header priority param.
func (t *Transport) SetHTTP2HeaderPriority(priority http2.PriorityParam) *Transport {
t.t2.HeaderPriority = priority
return t
}
// SetHTTP2PriorityFrames set the ordered http2 priority frames.
func (t *Transport) SetHTTP2PriorityFrames(frames ...http2.PriorityFrame) *Transport {
t.t2.PriorityFrames = frames
return t
}
// SetTLSClientConfig set the custom TLSClientConfig, which specifies the TLS configuration to
// use with tls.Client.
// If nil, the default configuration is used.
// If non-nil, HTTP/2 support may not be enabled by default.
func (t *Transport) SetTLSClientConfig(cfg *tls.Config) *Transport {
t.TLSClientConfig = cfg
return t
}
// SetDebug set the optional debug function.
func (t *Transport) SetDebug(debugf func(format string, v ...interface{})) *Transport {
t.Debugf = debugf
return t
}
// SetProxy set the http proxy, only valid for HTTP1 and HTTP2, which specifies a function
// to return a proxy for a given Request. If the function returns a non-nil error, the request
// is aborted with the provided error.
//
// The proxy type is determined by the URL scheme. "http",
// "https", and "socks5" are supported. If the scheme is empty,
// "http" is assumed.
//
// If Proxy is nil or returns a nil *URL, no proxy is used.
func (t *Transport) SetProxy(proxy func(*http.Request) (*url.URL, error)) *Transport {
t.Proxy = proxy
return t
}
// SetDial set the custom DialContext function, only valid for HTTP1 and HTTP2, which specifies the
// dial function for creating unencrypted TCP connections.
// If it is nil, then the transport dials using package net.
//
// The dial function runs concurrently with calls to RoundTrip.
// A RoundTrip call that initiates a dial may end up using a connection dialed previously when the
// earlier connection becomes idle before the later dial function completes.
func (t *Transport) SetDial(fn func(ctx context.Context, network, addr string) (net.Conn, error)) *Transport {
t.DialContext = fn
return t
}
// SetDialTLS set the custom DialTLSContext function, only valid for HTTP1 and HTTP2, which specifies
// an optional dial function for creating TLS connections for non-proxied HTTPS requests (proxy will
// not work if set).
//
// If it is nil, DialContext and TLSClientConfig are used.
//
// If it is set, the function that set in SetDial is not used for HTTPS requests and the TLSClientConfig
// and TLSHandshakeTimeout are ignored. The returned net.Conn is assumed to already be past the TLS handshake.
func (t *Transport) SetDialTLS(fn func(ctx context.Context, network, addr string) (net.Conn, error)) *Transport {
t.DialTLSContext = fn
return t
}
// SetTLSHandshake set the custom tls handshake function, only valid for HTTP1 and HTTP2, not HTTP3,
// it specifies an optional dial function for tls handshake, it works even if a proxy is set, can be
// used to customize the tls fingerprint.
func (t *Transport) SetTLSHandshake(fn func(ctx context.Context, addr string, plainConn net.Conn) (conn net.Conn, tlsState *tls.ConnectionState, err error)) *Transport {
t.TLSHandshakeContext = fn
return t
}
type pendingAltSvc struct {
CurrentIndex int
Entries []*altsvc.AltSvc
Mu sync.Mutex
LastTime time.Time
Transport http.RoundTripper
}
// EnableForceHTTP1 enable force using HTTP1 (disabled by default).
func (t *Transport) EnableForceHTTP1() *Transport {
t.forceHttpVersion = h1
return t
}
// EnableForceHTTP2 enable force using HTTP2 for https requests
// (disabled by default).
func (t *Transport) EnableForceHTTP2() *Transport {
t.forceHttpVersion = h2
return t
}
// EnableH2C enables HTTP2 over TCP without TLS.
func (t *Transport) EnableH2C() *Transport {
t.Options.EnableH2C = true
t.t2.AllowHTTP = true
t.DialTLSContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
return net.Dial(network, addr)
}
return t
}
// DisableH2C disables HTTP2 over TCP without TLS.
func (t *Transport) DisableH2C() *Transport {
t.Options.EnableH2C = false
t.t2.AllowHTTP = false
t.t2.DialTLSContext = nil
return t
}
// EnableForceHTTP3 enable force using HTTP3 for https requests
// (disabled by default).
func (t *Transport) EnableForceHTTP3() *Transport {
t.EnableHTTP3()
if t.t3 != nil {
t.forceHttpVersion = h3
}
return t
}
// DisableForceHttpVersion disable force using specified http
// version (disabled by default).
func (t *Transport) DisableForceHttpVersion() *Transport {
t.forceHttpVersion = ""
return t
}
func (t *Transport) DisableHTTP3() {
t.altSvcJar = nil
t.pendingAltSvcs = nil
t.t3 = nil
}
func (t *Transport) EnableHTTP3() {
if t.t3 != nil {
return
}
v := runtime.Version()
ss := strings.Split(v, ".")
if len(ss) < 2 || ss[0] != "go1" {
if t.Debugf != nil {
t.Debugf("bad go version format: %s", v)
}
return
}
minorVersion, err := strconv.Atoi(ss[1])
if err != nil {
if t.Debugf != nil {
t.Debugf("bad go minor version: %s", v)
}
return
}
if !(minorVersion >= 20 && minorVersion <= 21) {
if t.Debugf != nil {
t.Debugf("%s is not support http3", v)
}
return
}
if t.altSvcJar == nil {
t.altSvcJar = altsvc.NewAltSvcJar()
}
if t.pendingAltSvcs == nil {
t.pendingAltSvcs = make(map[string]*pendingAltSvc)
}
t3 := &http3.RoundTripper{
Options: &t.Options,
}
t.t3 = t3
}
type wrapResponseBodyKeyType int
const wrapResponseBodyKey wrapResponseBodyKeyType = iota
type wrapResponseBodyFunc func(rc io.ReadCloser) io.ReadCloser
func (t *Transport) handleResponseBody(res *http.Response, req *http.Request) {
if wrap, ok := req.Context().Value(wrapResponseBodyKey).(wrapResponseBodyFunc); ok {
t.wrapResponseBody(res, wrap)
}
t.autoDecodeResponseBody(res)
dump.WrapResponseBodyIfNeeded(res, req, t.Dump)
}
var allowedProtocols = map[string]bool{
"h3": true,
}
func (t *Transport) handleAltSvc(req *http.Request, value string) {
addr := netutil.AuthorityKey(req.URL)
as := t.altSvcJar.GetAltSvc(addr)
if as != nil {
return
}
t.pendingAltSvcsMu.Lock()
defer t.pendingAltSvcsMu.Unlock()
_, ok := t.pendingAltSvcs[addr]
if ok {
return
}
ass, err := altsvcutil.ParseHeader(value)
if err != nil {
if t.Debugf != nil {
t.Debugf("failed to parse alt-svc header: %s", err.Error())
}
return
}
var entries []*altsvc.AltSvc
for _, a := range ass {
if allowedProtocols[a.Protocol] {
entries = append(entries, a)
}
}
if len(entries) > 0 {
pas := &pendingAltSvc{
Entries: entries,
}
t.pendingAltSvcs[addr] = pas
go t.handlePendingAltSvc(req.URL, pas)
}
}
func (t *Transport) handlePendingAltSvc(u *url.URL, pas *pendingAltSvc) {
for i := pas.CurrentIndex; i < len(pas.Entries); i++ {
switch pas.Entries[i].Protocol {
case "h3": // only support h3 in alt-svc for now
u2 := altsvcutil.ConvertURL(pas.Entries[i], u)
hostname := u2.Host
err := t.t3.AddConn(hostname)
if err != nil {
if t.Debugf != nil {
t.Debugf("failed to get http3 connection: %s", err.Error())
}
} else {
pas.CurrentIndex = i
pas.Transport = t.t3
if t.Debugf != nil {
t.Debugf("detected that the server %s supports http3, will try to use http3 protocol in subsequent requests", hostname)
}
return
}
}
}
}
func (t *Transport) wrapResponseBody(res *http.Response, wrap wrapResponseBodyFunc) {
switch b := res.Body.(type) {
case *gzipReader:
b.body.body = wrap(b.body.body)
case *h2internal.GzipReader:
b.Body = wrap(b.Body)
case *http3.GzipReader:
b.Body = wrap(b.Body)
default:
res.Body = wrap(res.Body)
}
}
func (t *Transport) autoDecodeResponseBody(res *http.Response) {
if t.disableAutoDecode || res.Header.Get("Accept-Encoding") != "" {
return
}
contentType := res.Header.Get("Content-Type")
var shouldDecode func(contentType string) bool
if t.autoDecodeContentType != nil {
shouldDecode = t.autoDecodeContentType
} else {
shouldDecode = autoDecodeText
}
if !shouldDecode(contentType) {
return
}
_, params, err := mime.ParseMediaType(contentType)
if err != nil {
if t.Debugf != nil {
t.Debugf("failed to parse content type %q: %v", contentType, err)
}
} else if charset, ok := params["charset"]; ok {
charset = strings.ToLower(charset)
if strings.Contains(charset, "utf-8") || strings.Contains(charset, "utf8") { // do not decode utf-8
return
}
enc, _ := htmlcharset.Lookup(charset)
if enc == nil {
enc, err = ianaindex.MIME.Encoding(charset)
if err != nil || enc == nil {
if t.Debugf != nil {
t.Debugf("ignore charset %s which is detected in Content-Type but not supported", charset)
}
return
}
}
if t.Debugf != nil {
t.Debugf("charset %s detected in Content-Type, auto-decode to utf-8", charset)
}
decodeReader := enc.NewDecoder().Reader(res.Body)
res.Body = &decodeReaderCloser{res.Body, decodeReader}
return
}
res.Body = newAutoDecodeReadCloser(res.Body, t)
}
// A cancelKey is the key of the reqCanceler map.
// We wrap the *http.Request in this type since we want to use the original request,
// not any transient one created by roundTrip.
type cancelKey struct {
req *http.Request
}
func (t *Transport) writeBufferSize() int {
if t.WriteBufferSize > 0 {
return t.WriteBufferSize
}
return 4 << 10
}
func (t *Transport) readBufferSize() int {
if t.ReadBufferSize > 0 {
return t.ReadBufferSize
}
return 4 << 10
}
// Clone returns a deep copy of t's exported fields.
func (t *Transport) Clone() *Transport {
tt := &Transport{
Headers: t.Headers.Clone(),
Cookies: cloneSlice(t.Cookies),
Options: t.Options.Clone(),
disableAutoDecode: t.disableAutoDecode,
autoDecodeContentType: t.autoDecodeContentType,
forceHttpVersion: t.forceHttpVersion,
httpRoundTripWrappers: t.httpRoundTripWrappers,
}
if len(tt.httpRoundTripWrappers) > 0 { // clone transport middleware
fn := func(req *http.Request) (*http.Response, error) {
return tt.roundTrip(req)
}
tt.wrappedRoundTrip = HttpRoundTripFunc(fn)
for _, w := range tt.httpRoundTripWrappers {
tt.wrappedRoundTrip = w(tt.wrappedRoundTrip)
}
}
if t.t2 != nil {
tt.t2 = &h2internal.Transport{
Options: &tt.Options,
MaxHeaderListSize: t.t2.MaxHeaderListSize,
StrictMaxConcurrentStreams: t.t2.StrictMaxConcurrentStreams,
ReadIdleTimeout: t.t2.ReadIdleTimeout,
PingTimeout: t.t2.PingTimeout,
WriteByteTimeout: t.t2.WriteByteTimeout,
ConnectionFlow: t.t2.ConnectionFlow,
Settings: cloneSlice(t.t2.Settings),
HeaderPriority: t.t2.HeaderPriority,
PriorityFrames: cloneSlice(t.t2.PriorityFrames),
}
}
if t.t3 != nil {
tt.EnableHTTP3()
}
return tt
}
// EnableDump enables the dump for all requests with specified dump options.
func (t *Transport) EnableDump(opt *DumpOptions) {
dump := newDumper(opt)
t.Dump = dump
go dump.Start()
}
// DisableDump disables the dump.
func (t *Transport) DisableDump() {
if t.Dump != nil {
t.Dump.Stop()
t.Dump = nil
}
}
func (t *Transport) hasCustomTLSDialer() bool {
return t.DialTLSContext != nil
}
// transportRequest is a wrapper around a *http.Request that adds
// optional extra headers to write and stores any error to return
// from roundTrip.
type transportRequest struct {
*http.Request // original request, not to be mutated
extra http.Header // extra headers to write, or nil
trace *httptrace.ClientTrace // optional
cancelKey cancelKey
mu sync.Mutex // guards err
err error // first setError value for mapRoundTripError to consider
}
func (tr *transportRequest) extraHeaders() http.Header {
if tr.extra == nil {
tr.extra = make(http.Header)
}
return tr.extra
}
func (tr *transportRequest) setError(err error) {
tr.mu.Lock()
if tr.err == nil {
tr.err = err
}
tr.mu.Unlock()
}
func (t *Transport) roundTripAltSvc(req *http.Request, as *altsvc.AltSvc) (resp *http.Response, err error) {
r := req.Clone(req.Context())
r.URL = altsvcutil.ConvertURL(as, req.URL)
switch as.Protocol {
case "h3":
resp, err = t.t3.RoundTrip(r)
case "h2":
resp, err = t.t2.RoundTrip(r)
default:
// impossible!
panic(fmt.Sprintf("unknown protocol %q", as.Protocol))
}
return
}
func (t *Transport) checkAltSvc(req *http.Request) (resp *http.Response, err error) {
if t.altSvcJar == nil {
return
}
addr := netutil.AuthorityKey(req.URL)
pas, ok := t.pendingAltSvcs[addr]
if ok && pas.Transport != nil {
pas.Mu.Lock()
if pas.Transport != nil {
pas.LastTime = time.Now()
r := req.Clone(req.Context())
r.URL = altsvcutil.ConvertURL(pas.Entries[pas.CurrentIndex], req.URL)
resp, err = pas.Transport.RoundTrip(r)
if err != nil {
pas.Transport = nil
if pas.CurrentIndex+1 < len(pas.Entries) {
pas.CurrentIndex++
go t.handlePendingAltSvc(req.URL, pas)
}
} else {
t.altSvcJar.SetAltSvc(addr, pas.Entries[pas.CurrentIndex])
delete(t.pendingAltSvcs, addr)
}
}
pas.Mu.Unlock()
return
}
if as := t.altSvcJar.GetAltSvc(addr); as != nil {
return t.roundTripAltSvc(req, as)
}
return
}
// roundTrip implements a http.RoundTripper over HTTP.
func (t *Transport) roundTrip(req *http.Request) (resp *http.Response, err error) {
ctx := req.Context()
trace := httptrace.ContextClientTrace(ctx)
if req.URL == nil {
closeBody(req)
return nil, errors.New("http: nil Request.URL")
}
resp, err = t.checkAltSvc(req)
if err != nil || resp != nil {
return
}
scheme := req.URL.Scheme
isHTTP := scheme == "http" || scheme == "https"
if isHTTP {
// TODO: is h2c should also check this?
for k, vv := range req.Header {
if !httpguts.ValidHeaderFieldName(k) {
closeBody(req)
err = fmt.Errorf("net/http: invalid header field name %q", k)
return
}
for _, v := range vv {
if !httpguts.ValidHeaderFieldValue(v) {
closeBody(req)
// Don't include the value in the error, because it may be sensitive.
err = fmt.Errorf("net/http: invalid header field value for %q", k)
return
}
}
}
}
if req.Header == nil {
req.Header = make(http.Header)
}
if t.forceHttpVersion != "" {
switch t.forceHttpVersion {
case h3:
return t.t3.RoundTrip(req)
case h2:
return t.t2.RoundTrip(req)
}
}
origReq := req
cancelKey := cancelKey{origReq}
req = setupRewindBody(req)
if scheme == "https" && t.forceHttpVersion != h1 {
resp, err := t.t2.RoundTripOnlyCachedConn(req)
if err != h2internal.ErrNoCachedConn {
return resp, err
}
req, err = rewindBody(req)
if err != nil {
return nil, err
}
if t.t3 != nil {
resp, err = t.t3.RoundTripOnlyCachedConn(req)
if err != http3.ErrNoCachedConn {
return resp, err
}
req, err = rewindBody(req)
if err != nil {
return nil, err
}
}
}
if !isHTTP {
closeBody(req)
return nil, badStringError("unsupported protocol scheme", scheme)
}
if req.Method != "" && !validMethod(req.Method) {
closeBody(req)
return nil, fmt.Errorf("net/http: invalid method %q", req.Method)
}
if req.URL.Host == "" {
closeBody(req)
return nil, errors.New("http: no Host in request URL")
}
for {
select {
case <-ctx.Done():
closeBody(req)
return nil, ctx.Err()
default:
}
// treq gets modified by roundTrip, so we need to recreate for each retry.
treq := &transportRequest{Request: req, trace: trace, cancelKey: cancelKey}
cm, err := t.connectMethodForRequest(treq)
if err != nil {
closeBody(req)
return nil, err
}
// Get the cached or newly-created connection to either the
// host (for http or https), the http proxy, or the http proxy
// pre-CONNECTed to https server. In any case, we'll be ready
// to send it requests.