forked from teddysun/xray-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
459 lines (416 loc) · 12 KB
/
main.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
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
package main
//go:generate errorgen
import (
"flag"
"fmt"
"os"
"os/signal"
"os/user"
"runtime"
"strconv"
"strings"
"syscall"
"net/url"
"google.golang.org/protobuf/proto"
"github.com/xtls/xray-core/core"
"github.com/xtls/xray-core/app/dispatcher"
"github.com/xtls/xray-core/app/proxyman"
_ "github.com/xtls/xray-core/app/proxyman/inbound"
_ "github.com/xtls/xray-core/app/proxyman/outbound"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/proxy/dokodemo"
"github.com/xtls/xray-core/proxy/freedom"
"github.com/xtls/xray-core/transport/internet"
"github.com/xtls/xray-core/transport/internet/grpc"
"github.com/xtls/xray-core/transport/internet/quic"
"github.com/xtls/xray-core/transport/internet/tls"
"github.com/xtls/xray-core/transport/internet/websocket"
vlog "github.com/xtls/xray-core/app/log"
clog "github.com/xtls/xray-core/common/log"
"github.com/xtls/xray-core/common/platform/filesystem"
"github.com/teddysun/xray-plugin/cmd/build"
)
var (
VERSION = "custom"
)
var (
vpn = flag.Bool("V", false, "Run in VPN mode.")
fastOpen = flag.Bool("fast-open", false, "Enable TCP fast open.")
localAddr = flag.String("localAddr", "127.0.0.1", "local address to listen on.")
localPort = flag.String("localPort", "1984", "local port to listen on.")
remoteAddr = flag.String("remoteAddr", "127.0.0.1", "remote address to forward.")
remotePort = flag.String("remotePort", "1080", "remote port to forward.")
path = flag.String("path", "/", "URL path for websocket.")
serviceName = flag.String("serviceName", "GunService", "Service name for grpc.")
host = flag.String("host", "cloudfront.com", "Hostname for server.")
tlsEnabled = flag.Bool("tls", false, "Enable TLS.")
cert = flag.String("cert", "", "Path to TLS certificate file. Overrides certRaw. Default: ~/.acme.sh/{host}/fullchain.cer")
certRaw = flag.String("certRaw", "", "Raw TLS certificate content. Intended only for Android.")
key = flag.String("key", "", "(server) Path to TLS key file. Default: ~/.acme.sh/{host}/{host}.key")
mode = flag.String("mode", "websocket", "Transport mode: websocket, quic (enforced tls), grpc.")
mux = flag.Int("mux", 1, "Concurrent multiplexed connections (websocket client mode only).")
server = flag.Bool("server", false, "Run in server mode")
logLevel = flag.String("loglevel", "", "loglevel for xray: debug, info, warning (default), error, none.")
version = flag.Bool("version", false, "Show current version of xray-plugin")
fwmark = flag.Int("fwmark", 0, "Set SO_MARK option for outbound sockets.")
)
func homeDir() string {
usr, err := user.Current()
if err != nil {
logFatal(err)
os.Exit(1)
}
return usr.HomeDir
}
func readCertificate() ([]byte, error) {
if *cert != "" {
return filesystem.ReadFile(*cert)
}
if *certRaw != "" {
certHead := "-----BEGIN CERTIFICATE-----"
certTail := "-----END CERTIFICATE-----"
fixedCert := certHead + "\n" + *certRaw + "\n" + certTail
return []byte(fixedCert), nil
}
panic("thou shalt not reach hear")
}
func logConfig(logLevel string) *vlog.Config {
config := &vlog.Config{
ErrorLogLevel: clog.Severity_Warning,
ErrorLogType: vlog.LogType_Console,
AccessLogType: vlog.LogType_Console,
}
level := strings.ToLower(logLevel)
switch level {
case "debug":
config.ErrorLogLevel = clog.Severity_Debug
case "info":
config.ErrorLogLevel = clog.Severity_Info
case "error":
config.ErrorLogLevel = clog.Severity_Error
case "none":
config.ErrorLogType = vlog.LogType_None
config.AccessLogType = vlog.LogType_None
}
return config
}
func parseLocalAddr(localAddr string) []string {
return strings.Split(localAddr, "|")
}
func generateConfig() (*core.Config, error) {
lport, err := net.PortFromString(*localPort)
if err != nil {
return nil, errors.New("invalid localPort:", *localPort).Base(err)
}
rport, err := strconv.ParseUint(*remotePort, 10, 32)
if err != nil {
return nil, errors.New("invalid remotePort:", *remotePort).Base(err)
}
outboundProxy := serial.ToTypedMessage(&freedom.Config{
DestinationOverride: &freedom.DestinationOverride{
Server: &protocol.ServerEndpoint{
Address: net.NewIPOrDomain(net.ParseAddress(*remoteAddr)),
Port: uint32(rport),
},
},
})
var transportSettings proto.Message
var connectionReuse bool
switch *mode {
case "websocket":
var ed uint32
if u, err := url.Parse(*path); err == nil {
if q := u.Query(); q.Get("ed") != "" {
Ed, _ := strconv.Atoi(q.Get("ed"))
ed = uint32(Ed)
q.Del("ed")
u.RawQuery = q.Encode()
*path = u.String()
}
}
transportSettings = &websocket.Config{
Path: *path,
Host: *host,
Header: map[string]string{
"host": *host,
},
Ed: ed,
}
if *mux != 0 {
connectionReuse = true
}
case "quic":
transportSettings = &quic.Config{
Security: &protocol.SecurityConfig{Type: protocol.SecurityType_NONE},
}
*tlsEnabled = true
case "grpc":
transportSettings = &grpc.Config{
ServiceName: *serviceName,
}
default:
return nil, errors.New("unsupported mode:", *mode)
}
streamConfig := internet.StreamConfig{
ProtocolName: *mode,
TransportSettings: []*internet.TransportConfig{{
ProtocolName: *mode,
Settings: serial.ToTypedMessage(transportSettings),
}},
}
if *fastOpen || *fwmark != 0 {
socketConfig := &internet.SocketConfig{}
if *fastOpen {
socketConfig.Tfo = 256
}
if *fwmark != 0 {
socketConfig.Mark = int32(*fwmark)
}
streamConfig.SocketSettings = socketConfig
}
if *tlsEnabled {
tlsConfig := tls.Config{ServerName: *host}
if *server {
certificate := tls.Certificate{}
if *cert == "" && *certRaw == "" {
*cert = fmt.Sprintf("%s/.acme.sh/%s/fullchain.cer", homeDir(), *host)
logWarn("No TLS cert specified, trying", *cert)
}
certificate.Certificate, err = readCertificate()
if err != nil {
return nil, errors.New("failed to read cert").Base(err)
}
if *key == "" {
*key = fmt.Sprintf("%[1]s/.acme.sh/%[2]s/%[2]s.key", homeDir(), *host)
logWarn("No TLS key specified, trying", *key)
}
certificate.Key, err = filesystem.ReadFile(*key)
if err != nil {
return nil, errors.New("failed to read key file").Base(err)
}
tlsConfig.Certificate = []*tls.Certificate{&certificate}
} else if *cert != "" || *certRaw != "" {
certificate := tls.Certificate{Usage: tls.Certificate_AUTHORITY_VERIFY}
certificate.Certificate, err = readCertificate()
if err != nil {
return nil, errors.New("failed to read cert").Base(err)
}
tlsConfig.Certificate = []*tls.Certificate{&certificate}
}
streamConfig.SecurityType = serial.GetMessageType(&tlsConfig)
streamConfig.SecuritySettings = []*serial.TypedMessage{serial.ToTypedMessage(&tlsConfig)}
}
apps := []*serial.TypedMessage{
serial.ToTypedMessage(&dispatcher.Config{}),
serial.ToTypedMessage(&proxyman.InboundConfig{}),
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
serial.ToTypedMessage(logConfig(*logLevel)),
}
if *server {
proxyAddress := net.LocalHostIP
if connectionReuse {
// This address is required when mux is used on client.
// dokodemo is not aware of mux connections by itself.
proxyAddress = net.ParseAddress("v1.mux.cool")
}
localAddrs := parseLocalAddr(*localAddr)
inbounds := make([]*core.InboundHandlerConfig, len(localAddrs))
for i := 0; i < len(localAddrs); i++ {
inbounds[i] = &core.InboundHandlerConfig{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortList: &net.PortList{
Range: []*net.PortRange{net.SinglePortRange(lport)},
},
Listen: net.NewIPOrDomain(net.ParseAddress(localAddrs[i])),
StreamSettings: &streamConfig,
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(proxyAddress),
Networks: []net.Network{net.Network_TCP},
}),
}
}
return &core.Config{
Inbound: inbounds,
Outbound: []*core.OutboundHandlerConfig{{
ProxySettings: outboundProxy,
}},
App: apps,
}, nil
} else {
senderConfig := proxyman.SenderConfig{StreamSettings: &streamConfig}
if connectionReuse {
senderConfig.MultiplexSettings = &proxyman.MultiplexingConfig{Enabled: true, Concurrency: int32(*mux)}
}
return &core.Config{
Inbound: []*core.InboundHandlerConfig{{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortList: &net.PortList{
Range: []*net.PortRange{net.SinglePortRange(lport)},
},
Listen: net.NewIPOrDomain(net.ParseAddress(*localAddr)),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(net.LocalHostIP),
Networks: []net.Network{net.Network_TCP},
}),
}},
Outbound: []*core.OutboundHandlerConfig{{
SenderSettings: serial.ToTypedMessage(&senderConfig),
ProxySettings: outboundProxy,
}},
App: apps,
}, nil
}
}
func startXRay() (core.Server, error) {
opts, err := parseEnv()
if err == nil {
if c, b := opts.Get("mode"); b {
*mode = c
}
if c, b := opts.Get("mux"); b {
if i, err := strconv.Atoi(c); err == nil {
*mux = i
} else {
logWarn("failed to parse mux, use default value")
}
}
if _, b := opts.Get("tls"); b {
*tlsEnabled = true
}
if c, b := opts.Get("host"); b {
*host = c
}
if c, b := opts.Get("path"); b {
*path = c
}
if c, b := opts.Get("serviceName"); b {
*serviceName = c
}
if c, b := opts.Get("cert"); b {
*cert = c
}
if c, b := opts.Get("certRaw"); b {
*certRaw = c
}
if c, b := opts.Get("key"); b {
*key = c
}
if c, b := opts.Get("loglevel"); b {
*logLevel = c
}
if _, b := opts.Get("server"); b {
*server = true
}
if c, b := opts.Get("localAddr"); b {
if *server {
*remoteAddr = c
} else {
*localAddr = c
}
}
if c, b := opts.Get("localPort"); b {
if *server {
*remotePort = c
} else {
*localPort = c
}
}
if c, b := opts.Get("remoteAddr"); b {
if *server {
*localAddr = c
} else {
*remoteAddr = c
}
}
if c, b := opts.Get("remotePort"); b {
if *server {
*localPort = c
} else {
*remotePort = c
}
}
if _, b := opts.Get("fastOpen"); b {
*fastOpen = true
}
if _, b := opts.Get("__android_vpn"); b {
*vpn = true
}
if c, b := opts.Get("fwmark"); b {
if i, err := strconv.Atoi(c); err == nil {
*fwmark = i
} else {
logWarn("failed to parse fwmark, use default value")
}
}
if *vpn {
registerControlFunc()
}
}
config, err := generateConfig()
if err != nil {
return nil, errors.New("failed to parse config").Base(err)
}
instance, err := core.New(config)
if err != nil {
return nil, errors.New("failed to create xray instance").Base(err)
}
return instance, nil
}
func printCoreVersion() {
version := core.VersionStatement()
for _, s := range version {
logInfo(s)
}
}
func printVersion() {
osVersion, osKernel := build.GetOSVersion()
if osVersion == "" {
osVersion = "unknown"
}
if osKernel == "" {
osKernel = "unknown"
}
arch := build.GetArch()
fmt.Println("xray-plugin", VERSION)
fmt.Println("Yet another SIP003 plugin for shadowsocks")
fmt.Printf("- os/version: %s\n", osVersion)
fmt.Printf("- os/kernel: %s\n", osKernel)
fmt.Printf("- os/type: %s\n", runtime.GOOS)
fmt.Printf("- os/arch: %s\n", arch)
fmt.Printf("- go/version: %s\n", runtime.Version())
}
func main() {
flag.Parse()
if *version {
printVersion()
return
}
logInit()
printCoreVersion()
server, err := startXRay()
if err != nil {
logFatal(err.Error())
// Configuration error. Exit with a special value to prevent systemd from restarting.
os.Exit(23)
}
if err := server.Start(); err != nil {
logFatal("failed to start server:", err.Error())
os.Exit(1)
}
defer func() {
err := server.Close()
if err != nil {
logWarn(err.Error())
}
}()
{
osSignals := make(chan os.Signal, 1)
signal.Notify(osSignals, os.Interrupt, os.Kill, syscall.SIGTERM)
<-osSignals
}
}