forked from shadowsocks/v2ray-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
400 lines (361 loc) · 10.3 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
package main
//go:generate errorgen
import (
"flag"
"fmt"
"os"
"os/signal"
"os/user"
"runtime"
"strconv"
"strings"
"syscall"
"github.com/golang/protobuf/proto"
"v2ray.com/core"
"v2ray.com/core/app/dispatcher"
"v2ray.com/core/app/proxyman"
_ "v2ray.com/core/app/proxyman/inbound"
_ "v2ray.com/core/app/proxyman/outbound"
"v2ray.com/core/common/net"
"v2ray.com/core/common/protocol"
"v2ray.com/core/common/serial"
"v2ray.com/core/proxy/dokodemo"
"v2ray.com/core/proxy/freedom"
"v2ray.com/core/transport/internet"
"v2ray.com/core/transport/internet/quic"
"v2ray.com/core/transport/internet/tls"
"v2ray.com/core/transport/internet/websocket"
vlog "v2ray.com/core/app/log"
clog "v2ray.com/core/common/log"
"v2ray.com/core/common/platform/filesystem"
)
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.")
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).")
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 v2ray: debug, info, warning (default), error, none.")
version = flag.Bool("version", false, "Show current version of v2ray-plugin")
)
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, newError("invalid localPort:", *localPort).Base(err)
}
rport, err := strconv.ParseUint(*remotePort, 10, 32)
if err != nil {
return nil, newError("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":
transportSettings = &websocket.Config{
Path: *path,
Header: []*websocket.Header{
{Key: "Host", Value: *host},
},
}
if *mux != 0 {
connectionReuse = true
}
case "quic":
transportSettings = &quic.Config{
Security: &protocol.SecurityConfig{Type: protocol.SecurityType_NONE},
}
*tlsEnabled = true
default:
return nil, newError("unsupported mode:", *mode)
}
streamConfig := internet.StreamConfig{
ProtocolName: *mode,
TransportSettings: []*internet.TransportConfig{{
ProtocolName: *mode,
Settings: serial.ToTypedMessage(transportSettings),
}},
}
if *fastOpen {
streamConfig.SocketSettings = &internet.SocketConfig{Tfo: internet.SocketConfig_Enable}
}
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, newError("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, newError("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, newError("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{
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: uint32(*mux)}
}
return &core.Config{
Inbound: []*core.InboundHandlerConfig{{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
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 startV2Ray() (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("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 *vpn {
registerControlFunc()
}
}
config, err := generateConfig()
if err != nil {
return nil, newError("failed to parse config").Base(err)
}
instance, err := core.New(config)
if err != nil {
return nil, newError("failed to create v2ray instance").Base(err)
}
return instance, nil
}
func printCoreVersion() {
version := core.VersionStatement()
for _, s := range version {
logInfo(s)
}
}
func printVersion() {
fmt.Println("v2ray-plugin", VERSION)
fmt.Println("Go version", runtime.Version())
fmt.Println("Yet another SIP003 plugin for shadowsocks")
}
func main() {
flag.Parse()
if *version {
printVersion()
return
}
logInit()
printCoreVersion()
server, err := startV2Ray()
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
}
}