forked from v2fly/v2ray-core
/
dialer.go
156 lines (133 loc) · 4.22 KB
/
dialer.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
package http
import (
"context"
gotls "crypto/tls"
"net/http"
"net/url"
"sync"
"golang.org/x/net/http2"
core "github.com/anchel/v2ray-core"
"github.com/anchel/v2ray-core/common"
"github.com/anchel/v2ray-core/common/buf"
"github.com/anchel/v2ray-core/common/net"
"github.com/anchel/v2ray-core/transport/internet"
"github.com/anchel/v2ray-core/transport/internet/tls"
"github.com/anchel/v2ray-core/transport/pipe"
)
var (
globalDialerMap map[net.Destination]*http.Client
globalDialerAccess sync.Mutex
)
type dialerCanceller func()
func getHTTPClient(ctx context.Context, dest net.Destination, tlsSettings *tls.Config, streamSettings *internet.MemoryStreamConfig) (*http.Client, dialerCanceller) {
globalDialerAccess.Lock()
defer globalDialerAccess.Unlock()
canceller := func() {
globalDialerAccess.Lock()
defer globalDialerAccess.Unlock()
delete(globalDialerMap, dest)
}
if globalDialerMap == nil {
globalDialerMap = make(map[net.Destination]*http.Client)
}
if client, found := globalDialerMap[dest]; found {
return client, canceller
}
transport := &http2.Transport{
DialTLS: func(network string, addr string, tlsConfig *gotls.Config) (net.Conn, error) {
rawHost, rawPort, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
if len(rawPort) == 0 {
rawPort = "443"
}
port, err := net.PortFromString(rawPort)
if err != nil {
return nil, err
}
address := net.ParseAddress(rawHost)
detachedContext := core.ToBackgroundDetachedContext(ctx)
pconn, err := internet.DialSystem(detachedContext, net.TCPDestination(address, port), streamSettings.SocketSettings)
if err != nil {
return nil, err
}
cn := gotls.Client(pconn, tlsConfig)
if err := cn.Handshake(); err != nil {
return nil, err
}
if !tlsConfig.InsecureSkipVerify {
if err := cn.VerifyHostname(tlsConfig.ServerName); err != nil {
return nil, err
}
}
state := cn.ConnectionState()
if p := state.NegotiatedProtocol; p != http2.NextProtoTLS {
return nil, newError("http2: unexpected ALPN protocol " + p + "; want q" + http2.NextProtoTLS).AtError()
}
return cn, nil
},
TLSClientConfig: tlsSettings.GetTLSConfig(tls.WithDestination(dest)),
}
client := &http.Client{
Transport: transport,
}
globalDialerMap[dest] = client
return client, canceller
}
// Dial dials a new TCP connection to the given destination.
func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.MemoryStreamConfig) (internet.Connection, error) {
httpSettings := streamSettings.ProtocolSettings.(*Config)
tlsConfig := tls.ConfigFromStreamSettings(streamSettings)
if tlsConfig == nil {
return nil, newError("TLS must be enabled for http transport.").AtWarning()
}
client, canceller := getHTTPClient(ctx, dest, tlsConfig, streamSettings)
opts := pipe.OptionsFromContext(ctx)
preader, pwriter := pipe.New(opts...)
breader := &buf.BufferedReader{Reader: preader}
httpMethod := "PUT"
if httpSettings.Method != "" {
httpMethod = httpSettings.Method
}
httpHeaders := make(http.Header)
for _, httpHeader := range httpSettings.Header {
for _, httpHeaderValue := range httpHeader.Value {
httpHeaders.Set(httpHeader.Name, httpHeaderValue)
}
}
request := &http.Request{
Method: httpMethod,
Host: httpSettings.getRandomHost(),
Body: breader,
URL: &url.URL{
Scheme: "https",
Host: dest.NetAddr(),
Path: httpSettings.getNormalizedPath(),
},
Proto: "HTTP/2",
ProtoMajor: 2,
ProtoMinor: 0,
Header: httpHeaders,
}
// Disable any compression method from server.
request.Header.Set("Accept-Encoding", "identity")
response, err := client.Do(request) // nolint: bodyclose
if err != nil {
canceller()
return nil, newError("failed to dial to ", dest).Base(err).AtWarning()
}
if response.StatusCode != 200 {
return nil, newError("unexpected status", response.StatusCode).AtWarning()
}
bwriter := buf.NewBufferedWriter(pwriter)
common.Must(bwriter.SetBuffered(false))
return net.NewConnection(
net.ConnectionOutput(response.Body),
net.ConnectionInput(bwriter),
net.ConnectionOnClose(common.ChainedClosable{breader, bwriter, response.Body}),
), nil
}
func init() {
common.Must(internet.RegisterTransportDialer(protocolName, Dial))
}