forked from v2fly/v2ray-core
/
dialer.go
216 lines (185 loc) · 6.83 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
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
package websocket
import (
"bytes"
"context"
"encoding/base64"
"io"
gonet "net"
"net/http"
"time"
"github.com/gorilla/websocket"
core "github.com/anchel/v2ray-core"
"github.com/anchel/v2ray-core/common"
"github.com/anchel/v2ray-core/common/net"
"github.com/anchel/v2ray-core/common/session"
"github.com/anchel/v2ray-core/features/extension"
"github.com/anchel/v2ray-core/transport/internet"
"github.com/anchel/v2ray-core/transport/internet/security"
)
// Dial dials a WebSocket connection to the given destination.
func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.MemoryStreamConfig) (internet.Connection, error) {
newError("creating connection to ", dest).WriteToLog(session.ExportIDToError(ctx))
conn, err := dialWebsocket(ctx, dest, streamSettings)
if err != nil {
return nil, newError("failed to dial WebSocket").Base(err)
}
return internet.Connection(conn), nil
}
func init() {
common.Must(internet.RegisterTransportDialer(protocolName, Dial))
}
func dialWebsocket(ctx context.Context, dest net.Destination, streamSettings *internet.MemoryStreamConfig) (net.Conn, error) {
wsSettings := streamSettings.ProtocolSettings.(*Config)
dialer := &websocket.Dialer{
NetDial: func(network, addr string) (net.Conn, error) {
return internet.DialSystem(ctx, dest, streamSettings.SocketSettings)
},
ReadBufferSize: 4 * 1024,
WriteBufferSize: 4 * 1024,
HandshakeTimeout: time.Second * 8,
}
protocol := "ws"
securityEngine, err := security.CreateSecurityEngineFromSettings(ctx, streamSettings)
if err != nil {
return nil, newError("unable to create security engine").Base(err)
}
if securityEngine != nil {
protocol = "wss"
dialer.NetDialTLSContext = func(ctx context.Context, network, addr string) (gonet.Conn, error) {
conn, err := dialer.NetDial(network, addr)
if err != nil {
return nil, newError("dial TLS connection failed").Base(err)
}
conn, err = securityEngine.Client(conn,
security.OptionWithDestination{Dest: dest},
security.OptionWithALPN{ALPNs: []string{"http/1.1"}})
if err != nil {
return nil, newError("unable to create security protocol client from security engine").Base(err)
}
return conn, nil
}
}
host := dest.NetAddr()
if (protocol == "ws" && dest.Port == 80) || (protocol == "wss" && dest.Port == 443) {
host = dest.Address.String()
}
uri := protocol + "://" + host + wsSettings.GetNormalizedPath()
if wsSettings.UseBrowserForwarding {
var forwarder extension.BrowserForwarder
err := core.RequireFeatures(ctx, func(Forwarder extension.BrowserForwarder) {
forwarder = Forwarder
})
if err != nil {
return nil, newError("cannot find browser forwarder service").Base(err)
}
if wsSettings.MaxEarlyData != 0 {
return newRelayedConnectionWithDelayedDial(&dialerWithEarlyDataRelayed{
forwarder: forwarder,
uriBase: uri,
config: wsSettings,
}), nil
}
conn, err := forwarder.DialWebsocket(uri, nil)
if err != nil {
return nil, newError("cannot dial with browser forwarder service").Base(err)
}
return newRelayedConnection(conn), nil
}
if wsSettings.MaxEarlyData != 0 {
return newConnectionWithDelayedDial(&dialerWithEarlyData{
dialer: dialer,
uriBase: uri,
config: wsSettings,
}), nil
}
conn, resp, err := dialer.Dial(uri, wsSettings.GetRequestHeader()) // nolint: bodyclose
if err != nil {
var reason string
if resp != nil {
reason = resp.Status
}
return nil, newError("failed to dial to (", uri, "): ", reason).Base(err)
}
return newConnection(conn, conn.RemoteAddr()), nil
}
type dialerWithEarlyData struct {
dialer *websocket.Dialer
uriBase string
config *Config
}
func (d dialerWithEarlyData) Dial(earlyData []byte) (*websocket.Conn, error) {
earlyDataBuf := bytes.NewBuffer(nil)
base64EarlyDataEncoder := base64.NewEncoder(base64.RawURLEncoding, earlyDataBuf)
earlydata := bytes.NewReader(earlyData)
limitedEarlyDatareader := io.LimitReader(earlydata, int64(d.config.MaxEarlyData))
n, encerr := io.Copy(base64EarlyDataEncoder, limitedEarlyDatareader)
if encerr != nil {
return nil, newError("websocket delayed dialer cannot encode early data").Base(encerr)
}
if errc := base64EarlyDataEncoder.Close(); errc != nil {
return nil, newError("websocket delayed dialer cannot encode early data tail").Base(errc)
}
dialFunction := func() (*websocket.Conn, *http.Response, error) {
return d.dialer.Dial(d.uriBase+earlyDataBuf.String(), d.config.GetRequestHeader())
}
if d.config.EarlyDataHeaderName != "" {
dialFunction = func() (*websocket.Conn, *http.Response, error) {
earlyDataStr := earlyDataBuf.String()
currentHeader := d.config.GetRequestHeader()
currentHeader.Set(d.config.EarlyDataHeaderName, earlyDataStr)
return d.dialer.Dial(d.uriBase, currentHeader)
}
}
conn, resp, err := dialFunction() // nolint: bodyclose
if err != nil {
var reason string
if resp != nil {
reason = resp.Status
}
return nil, newError("failed to dial to (", d.uriBase, ") with early data: ", reason).Base(err)
}
if n != int64(len(earlyData)) {
if errWrite := conn.WriteMessage(websocket.BinaryMessage, earlyData[n:]); errWrite != nil {
return nil, newError("failed to dial to (", d.uriBase, ") with early data as write of remainder early data failed: ").Base(err)
}
}
return conn, nil
}
type dialerWithEarlyDataRelayed struct {
forwarder extension.BrowserForwarder
uriBase string
config *Config
}
func (d dialerWithEarlyDataRelayed) Dial(earlyData []byte) (io.ReadWriteCloser, error) {
earlyDataBuf := bytes.NewBuffer(nil)
base64EarlyDataEncoder := base64.NewEncoder(base64.RawURLEncoding, earlyDataBuf)
earlydata := bytes.NewReader(earlyData)
limitedEarlyDatareader := io.LimitReader(earlydata, int64(d.config.MaxEarlyData))
n, encerr := io.Copy(base64EarlyDataEncoder, limitedEarlyDatareader)
if encerr != nil {
return nil, newError("websocket delayed dialer cannot encode early data").Base(encerr)
}
if errc := base64EarlyDataEncoder.Close(); errc != nil {
return nil, newError("websocket delayed dialer cannot encode early data tail").Base(errc)
}
dialFunction := func() (io.ReadWriteCloser, error) {
return d.forwarder.DialWebsocket(d.uriBase+earlyDataBuf.String(), d.config.GetRequestHeader())
}
if d.config.EarlyDataHeaderName != "" {
earlyDataStr := earlyDataBuf.String()
currentHeader := d.config.GetRequestHeader()
currentHeader.Set(d.config.EarlyDataHeaderName, earlyDataStr)
return d.forwarder.DialWebsocket(d.uriBase, currentHeader)
}
conn, err := dialFunction()
if err != nil {
var reason string
return nil, newError("failed to dial to (", d.uriBase, ") with early data: ", reason).Base(err)
}
if n != int64(len(earlyData)) {
if _, errWrite := conn.Write(earlyData[n:]); errWrite != nil {
return nil, newError("failed to dial to (", d.uriBase, ") with early data as write of remainder early data failed: ").Base(err)
}
}
return conn, nil
}