forked from XTLS/Xray-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dialer.go
179 lines (155 loc) · 5.3 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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
package http
import (
"context"
gotls "crypto/tls"
"net/http"
"net/url"
"sync"
"time"
"github.com/gurmeherchawla/xray-core/common"
"github.com/gurmeherchawla/xray-core/common/buf"
"github.com/gurmeherchawla/xray-core/common/net"
"github.com/gurmeherchawla/xray-core/common/net/cnc"
"github.com/gurmeherchawla/xray-core/common/session"
"github.com/gurmeherchawla/xray-core/transport/internet"
"github.com/gurmeherchawla/xray-core/transport/internet/stat"
"github.com/gurmeherchawla/xray-core/transport/internet/tls"
"github.com/gurmeherchawla/xray-core/transport/pipe"
"golang.org/x/net/http2"
)
type dialerConf struct {
net.Destination
*internet.MemoryStreamConfig
}
var (
globalDialerMap map[dialerConf]*http.Client
globalDialerAccess sync.Mutex
)
func getHTTPClient(ctx context.Context, dest net.Destination, streamSettings *internet.MemoryStreamConfig) (*http.Client, error) {
globalDialerAccess.Lock()
defer globalDialerAccess.Unlock()
if globalDialerMap == nil {
globalDialerMap = make(map[dialerConf]*http.Client)
}
httpSettings := streamSettings.ProtocolSettings.(*Config)
tlsConfigs := tls.ConfigFromStreamSettings(streamSettings)
if tlsConfigs == nil {
return nil, newError("TLS must be enabled for http transport.").AtWarning()
}
sockopt := streamSettings.SocketSettings
if client, found := globalDialerMap[dialerConf{dest, streamSettings}]; found {
return client, nil
}
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)
dctx := context.Background()
dctx = session.ContextWithID(dctx, session.IDFromContext(ctx))
dctx = session.ContextWithOutbound(dctx, session.OutboundFromContext(ctx))
pconn, err := internet.DialSystem(dctx, net.TCPDestination(address, port), sockopt)
if err != nil {
newError("failed to dial to " + addr).Base(err).AtError().WriteToLog()
return nil, err
}
var cn tls.Interface
if fingerprint, ok := tls.Fingerprints[tlsConfigs.Fingerprint]; ok {
cn = tls.UClient(pconn, tlsConfig, fingerprint).(*tls.UConn)
} else {
cn = tls.Client(pconn, tlsConfig).(*tls.Conn)
}
if err := cn.Handshake(); err != nil {
newError("failed to dial to " + addr).Base(err).AtError().WriteToLog()
return nil, err
}
if !tlsConfig.InsecureSkipVerify {
if err := cn.VerifyHostname(tlsConfig.ServerName); err != nil {
newError("failed to dial to " + addr).Base(err).AtError().WriteToLog()
return nil, err
}
}
negotiatedProtocol, negotiatedProtocolIsMutual := cn.NegotiatedProtocol()
if negotiatedProtocol != http2.NextProtoTLS {
return nil, newError("http2: unexpected ALPN protocol " + negotiatedProtocol + "; want q" + http2.NextProtoTLS).AtError()
}
if !negotiatedProtocolIsMutual {
return nil, newError("http2: could not negotiate protocol mutually").AtError()
}
return cn, nil
},
TLSClientConfig: tlsConfigs.GetTLSConfig(tls.WithDestination(dest)),
}
if httpSettings.IdleTimeout > 0 || httpSettings.HealthCheckTimeout > 0 {
transport.ReadIdleTimeout = time.Second * time.Duration(httpSettings.IdleTimeout)
transport.PingTimeout = time.Second * time.Duration(httpSettings.HealthCheckTimeout)
}
client := &http.Client{
Transport: transport,
}
globalDialerMap[dialerConf{dest, streamSettings}] = client
return client, nil
}
// Dial dials a new TCP connection to the given destination.
func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.MemoryStreamConfig) (stat.Connection, error) {
httpSettings := streamSettings.ProtocolSettings.(*Config)
client, err := getHTTPClient(ctx, dest, streamSettings)
if err != nil {
return nil, err
}
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)
if err != nil {
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 cnc.NewConnection(
cnc.ConnectionOutput(response.Body),
cnc.ConnectionInput(bwriter),
cnc.ConnectionOnClose(common.ChainedClosable{breader, bwriter, response.Body}),
), nil
}
func init() {
common.Must(internet.RegisterTransportDialer(protocolName, Dial))
}