-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxhttp_proxy.go
More file actions
305 lines (270 loc) · 7.73 KB
/
Copy pathxhttp_proxy.go
File metadata and controls
305 lines (270 loc) · 7.73 KB
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
package singproxy
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"net"
"net/url"
"strings"
"github.com/sagernet/sing-box/transport/trojan"
"github.com/sagernet/sing-vmess"
"github.com/sagernet/sing-vmess/vless"
"github.com/sagernet/sing/common/logger"
M "github.com/sagernet/sing/common/metadata"
)
var _ logger.Logger = nopLogger{}
type nopLogger struct{}
func (nopLogger) Trace(args ...any) {}
func (nopLogger) Debug(args ...any) {}
func (nopLogger) Info(args ...any) {}
func (nopLogger) Warn(args ...any) {}
func (nopLogger) Error(args ...any) {}
func (nopLogger) Fatal(args ...any) {}
func (nopLogger) Panic(args ...any) {}
func isXHTTPTransport(u *url.URL) bool {
t := strings.ToLower(u.Query().Get("type"))
return t == "xhttp" || t == "splithttp"
}
type xproxyProxy struct {
original string
proxyIP net.IP
typed string
cfg Config
xcfg *xhttpConfig
server string
port int
uuid string
password string
flow string
security string
alterID int
globalPad bool
authLength bool
}
func resolveProxyIP(host string) net.IP {
if ip := net.ParseIP(host); ip != nil {
return ip
}
ips, err := net.LookupIP(host)
if err == nil && len(ips) > 0 {
return ips[0]
}
return nil
}
func newXHTTPProxy(originalURL string, u *url.URL, typed string, cfg Config) (*xproxyProxy, error) {
if typed == "vmess" {
return newXHTTPProxyVMess(originalURL, u, cfg)
}
params := u.Query()
host := u.Hostname()
if host == "" {
return nil, fmt.Errorf("%w: xhttp: missing host", ErrInvalidProxyFormat)
}
port, err := parsePort(u.Port())
if err != nil || port == 0 {
return nil, fmt.Errorf("%w: xhttp: invalid or missing port", ErrInvalidProxyFormat)
}
xcfg, err := parseXHTTPTransportParams(params, host, int(port))
if err != nil {
return nil, fmt.Errorf("xhttp config: %w", err)
}
p := &xproxyProxy{
original: originalURL,
typed: typed,
cfg: cfg,
xcfg: xcfg,
server: host,
port: int(port),
}
switch typed {
case "vless":
p.uuid = u.User.Username()
p.flow = params.Get("flow")
case "trojan":
p.password = u.User.Username()
case "shadowsocks":
return nil, fmt.Errorf("xhttp: shadowsocks not supported with xhttp transport")
default:
return nil, fmt.Errorf("xhttp: protocol %s not supported with xhttp transport", typed)
}
p.proxyIP = resolveProxyIP(host)
return p, nil
}
type vmessXHTTPConfig struct {
uuid string
security string
alterID int
globalPadding bool
authLength bool
}
func extractVMessPayload(u *url.URL) (string, error) {
if u.Opaque != "" {
return u.Opaque, nil
}
if u.Host != "" {
payload := u.Host
if u.Path != "" {
payload += u.Path
}
if u.ForceQuery || u.RawQuery != "" {
payload += "?" + u.RawQuery
}
return payload, nil
}
return "", fmt.Errorf("unrecognized vmess URL format")
}
func decodeVMessJSON(payload string) (*vmessLinkData, error) {
jsonBytes, err := base64.RawStdEncoding.DecodeString(payload)
if err != nil {
jsonBytes, err = base64.StdEncoding.DecodeString(payload)
if err != nil {
jsonBytes, err = base64.RawURLEncoding.DecodeString(payload)
if err != nil {
return nil, fmt.Errorf("failed to decode vmess data: %w", err)
}
}
}
var data vmessLinkData
if err := json.Unmarshal(jsonBytes, &data); err != nil {
return nil, fmt.Errorf("failed to unmarshal vmess JSON: %w", err)
}
return &data, nil
}
func parseVMessForXHTTP(u *url.URL) (*vmessXHTTPConfig, error) {
payload, err := extractVMessPayload(u)
if err != nil {
return nil, err
}
data, err := decodeVMessJSON(payload)
if err != nil {
return nil, err
}
alterID, _ := parseAlterID(data.Aid)
security := data.Security
if security == "" {
security = "auto"
}
return &vmessXHTTPConfig{
uuid: data.ID,
security: security,
alterID: alterID,
globalPadding: data.GlobalPadding,
authLength: data.AuthLength,
}, nil
}
func newXHTTPProxyVMess(originalURL string, u *url.URL, cfg Config) (*xproxyProxy, error) {
vmCfg, err := parseVMessForXHTTP(u)
if err != nil {
return nil, fmt.Errorf("xhttp vmess: %w", err)
}
payload, err := extractVMessPayload(u)
if err != nil {
return nil, fmt.Errorf("xhttp vmess: %w", err)
}
data, err := decodeVMessJSON(payload)
if err != nil {
return nil, fmt.Errorf("xhttp vmess: %w", err)
}
host := data.Add
if host == "" {
return nil, fmt.Errorf("%w: xhttp vmess: missing host in JSON", ErrInvalidProxyFormat)
}
port, err := parsePort(data.Port)
if err != nil || port == 0 {
return nil, fmt.Errorf("%w: xhttp vmess: invalid or missing port in JSON", ErrInvalidProxyFormat)
}
params := url.Values{}
params.Set("host", anyToString(data.Host))
params.Set("path", anyToString(data.Path))
params.Set("mode", "")
if tlsStr := strings.ToLower(anyToString(data.TLS)); tlsStr == "tls" || strings.ToLower(data.Security) == "tls" {
params.Set("security", "tls")
params.Set("sni", anyToString(data.SNI))
params.Set("alpn", anyToString(data.ALPN))
params.Set("fp", anyToString(data.FP))
params.Set("allowInsecure", anyToString(data.AllowInsecure))
}
xcfg, err := parseXHTTPTransportParams(params, host, int(port))
if err != nil {
return nil, fmt.Errorf("xhttp config: %w", err)
}
p := &xproxyProxy{
original: originalURL,
typed: "vmess",
cfg: cfg,
xcfg: xcfg,
server: host,
port: int(port),
uuid: vmCfg.uuid,
security: vmCfg.security,
alterID: vmCfg.alterID,
globalPad: vmCfg.globalPadding,
authLength: vmCfg.authLength,
}
p.proxyIP = resolveProxyIP(host)
return p, nil
}
func (p *xproxyProxy) String() string { return p.original }
func (p *xproxyProxy) Addr() net.IP { return p.proxyIP }
func (p *xproxyProxy) DialContext(ctx context.Context, network string, addr string) (net.Conn, error) {
if addr == "" {
return nil, ErrMissingTarget
}
return p.dialSocksaddr(ctx, network, M.ParseSocksaddr(addr))
}
func (p *xproxyProxy) DialContextAddr(ctx context.Context, network string, addr *net.TCPAddr) (net.Conn, error) {
if addr == nil {
return nil, ErrMissingTarget
}
return p.dialSocksaddr(ctx, network, M.SocksaddrFromNet(addr))
}
func (p *xproxyProxy) dialSocksaddr(ctx context.Context, network string, targetAddr M.Socksaddr) (net.Conn, error) {
if network != "tcp" {
return nil, &net.OpError{Op: "dial", Net: network, Err: net.UnknownNetworkError(network)}
}
dialCtx, cancel := context.WithTimeout(ctx, p.cfg.DialTimeout)
defer cancel()
transportConn, err := dialXHTTP(dialCtx, p.xcfg, p.server, p.port, p.cfg)
if err != nil {
return nil, fmt.Errorf("xhttp transport: %w", err)
}
conn, err := p.wrapProtocolConn(transportConn, targetAddr)
if err != nil {
_ = transportConn.Close()
return nil, err
}
return conn, nil
}
func (p *xproxyProxy) wrapProtocolConn(transportConn net.Conn, targetAddr M.Socksaddr) (net.Conn, error) {
switch p.typed {
case "vless":
client, err := vless.NewClient(p.uuid, p.flow, nopLogger{})
if err != nil {
return nil, fmt.Errorf("xhttp vless client: %w", err)
}
conn, err := client.DialEarlyConn(transportConn, targetAddr)
if err != nil {
return nil, fmt.Errorf("xhttp vless dial: %w", err)
}
return conn, nil
case "vmess":
var opts []vmess.ClientOption
if p.globalPad {
opts = append(opts, vmess.ClientWithGlobalPadding())
}
if p.authLength {
opts = append(opts, vmess.ClientWithAuthenticatedLength())
}
client, err := vmess.NewClient(p.uuid, p.security, p.alterID, opts...)
if err != nil {
return nil, fmt.Errorf("xhttp vmess client: %w", err)
}
return client.DialEarlyConn(transportConn, targetAddr), nil
case "trojan":
key := trojan.Key(p.password)
return trojan.NewClientConn(transportConn, key, targetAddr), nil
default:
return nil, fmt.Errorf("xhttp: protocol %s not implemented", p.typed)
}
}