forked from wangluozhe/requests
/
roundtripper.go
208 lines (176 loc) · 5.34 KB
/
roundtripper.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
package transport
import (
"context"
"errors"
"fmt"
"net"
"strings"
"sync"
utls "github.com/refraction-networking/utls"
http "github.com/wangluozhe/chttp"
http2 "github.com/wangluozhe/chttp/http2"
"golang.org/x/net/proxy"
)
var errProtocolNegotiated = errors.New("protocol negotiated")
type roundTripper struct {
sync.RWMutex
// fix typing
JA3 string
UserAgent string
cachedConnections sync.Map
cachedTransports sync.Map
dialer proxy.ContextDialer
config *utls.Config
tlsExtensions *TLSExtensions
http2Settings *http2.HTTP2Settings
forceHTTP1 bool
}
func (rt *roundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
if req.Header.Get("user-agent") == "" {
req.Header.Set("user-agent", rt.UserAgent)
}
addr := rt.getDialTLSAddr(req)
transport, err := rt.getTransport(req, addr)
if err != nil {
return nil, err
}
return transport.RoundTrip(req)
}
func (rt *roundTripper) getTransport(req *http.Request, addr string) (http.RoundTripper, error) {
transport, ok := rt.cachedTransports.Load(addr)
if ok {
return transport.(http.RoundTripper), nil
}
switch strings.ToLower(req.URL.Scheme) {
case "http":
ts := &http.Transport{DialContext: rt.dialer.DialContext, DisableKeepAlives: true}
rt.cachedTransports.Store(addr, ts)
return ts, nil
case "https":
default:
return nil, fmt.Errorf("invalid URL scheme: [%v]", req.URL.Scheme)
}
_, err := rt.dialTLS(context.Background(), "tcp", addr)
switch err {
case errProtocolNegotiated:
case nil:
// Should never happen.
//panic("dialTLS returned no error when determining cachedTransports")
return nil, fmt.Errorf("dialTLS returned no error when determining cachedTransports")
default:
return nil, err
}
transport, _ = rt.cachedTransports.Load(addr)
return transport.(http.RoundTripper), nil
}
func (rt *roundTripper) dialTLS(ctx context.Context, network, addr string) (net.Conn, error) {
rt.Lock()
defer rt.Unlock()
// If we have the connection from when we determined the HTTPS
// cachedTransports to use, return that.
conn, ok := rt.cachedConnections.Load(addr)
if ok {
return conn.(net.Conn), nil
}
rawConn, err := rt.dialer.DialContext(ctx, network, addr)
if err != nil {
return nil, err
}
var host string
if host, _, err = net.SplitHostPort(addr); err != nil {
host = addr
}
//////////////////
spec, err := StringToSpec(rt.JA3, rt.UserAgent, rt.tlsExtensions, rt.forceHTTP1)
if err != nil {
return nil, err
}
rt.config.ServerName = host
tlsConn := utls.UClient(rawConn, rt.config.Clone(), utls.HelloCustom)
if err := tlsConn.ApplyPreset(spec); err != nil {
return nil, err
}
if err = tlsConn.HandshakeContext(ctx); err != nil {
_ = tlsConn.Close()
if err.Error() == "tls: CurvePreferences includes unsupported curve" {
//fix this
return nil, fmt.Errorf("conn.Handshake() error for tls 1.3 (please retry request): %+v", err)
}
return nil, fmt.Errorf("uTlsConn.Handshake() error: %+v", err)
}
//////////
_, ok = rt.cachedTransports.Load(addr)
if ok {
return tlsConn, nil
}
// No http.Transport constructed yet, create one based on the results
// of ALPN.
switch tlsConn.ConnectionState().NegotiatedProtocol {
case http2.NextProtoTLS:
t2 := http2.Transport{
DialTLS: rt.dialTLSHTTP2,
TLSClientConfig: rt.config,
}
if rt.http2Settings != nil {
t2.HTTP2Settings = rt.http2Settings
}
rt.cachedTransports.Store(addr, &t2)
default:
// Assume the remote peer is speaking HTTP 1.x + TLS.
rt.cachedTransports.Store(addr, &http.Transport{DialTLSContext: rt.dialTLS})
}
// Stash the connection just established for use servicing the
// actual request (should be near-immediate).
rt.cachedConnections.Store(addr, tlsConn)
return nil, errProtocolNegotiated
}
func (rt *roundTripper) dialTLSHTTP2(network, addr string, _ *utls.Config) (net.Conn, error) {
return rt.dialTLS(context.Background(), network, addr)
}
func (rt *roundTripper) getDialTLSAddr(req *http.Request) string {
host, port, err := net.SplitHostPort(req.URL.Host)
if err == nil {
return net.JoinHostPort(host, port)
}
return net.JoinHostPort(req.URL.Host, "443") // we can assume port is 443 at this point
}
func newRoundTripper(browser Browser, config *utls.Config, tlsExtensions *TLSExtensions, http2Settings *http2.HTTP2Settings, forceHTTP1 bool, dialer ...proxy.ContextDialer) http.RoundTripper {
if config == nil {
if strings.Index(strings.Split(browser.JA3, ",")[2], "-41") == -1 {
config = &utls.Config{
InsecureSkipVerify: true,
}
} else {
config = &utls.Config{
InsecureSkipVerify: true,
SessionTicketKey: [32]byte{},
ClientSessionCache: utls.NewLRUClientSessionCache(0),
OmitEmptyPsk: true,
}
}
}
if len(dialer) > 0 {
return &roundTripper{
dialer: dialer[0],
JA3: browser.JA3,
UserAgent: browser.UserAgent,
cachedTransports: sync.Map{},
cachedConnections: sync.Map{},
config: config,
tlsExtensions: tlsExtensions,
http2Settings: http2Settings,
forceHTTP1: forceHTTP1,
}
}
return &roundTripper{
dialer: proxy.Direct,
JA3: browser.JA3,
UserAgent: browser.UserAgent,
cachedTransports: sync.Map{},
cachedConnections: sync.Map{},
config: config,
tlsExtensions: tlsExtensions,
http2Settings: http2Settings,
forceHTTP1: forceHTTP1,
}
}