This repository has been archived by the owner on Jul 13, 2022. It is now read-only.
/
v2ray.go
798 lines (707 loc) · 24.2 KB
/
v2ray.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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
package conf
import (
"encoding/json"
"log"
gonet "net"
"os"
"runtime"
"strings"
core "github.com/Shadowsocks-NET/v2ray-go/v4"
"github.com/Shadowsocks-NET/v2ray-go/v4/app/dispatcher"
"github.com/Shadowsocks-NET/v2ray-go/v4/app/proxyman"
"github.com/Shadowsocks-NET/v2ray-go/v4/app/stats"
"github.com/Shadowsocks-NET/v2ray-go/v4/common/net"
"github.com/Shadowsocks-NET/v2ray-go/v4/common/serial"
"github.com/Shadowsocks-NET/v2ray-go/v4/infra/conf/cfgcommon"
"github.com/Shadowsocks-NET/v2ray-go/v4/transport/internet"
)
var (
inboundConfigLoader = NewJSONConfigLoader(ConfigCreatorCache{
"dokodemo-door": func() interface{} { return new(DokodemoConfig) },
"http": func() interface{} { return new(HTTPServerConfig) },
"shadowsocks": func() interface{} { return new(ShadowsocksServerConfig) },
"socks": func() interface{} { return new(SocksServerConfig) },
"vmess": func() interface{} { return new(VMessInboundConfig) },
"trojan": func() interface{} { return new(TrojanServerConfig) },
}, "protocol", "settings")
outboundConfigLoader = NewJSONConfigLoader(ConfigCreatorCache{
"blackhole": func() interface{} { return new(BlackholeConfig) },
"freedom": func() interface{} { return new(FreedomConfig) },
"http": func() interface{} { return new(HTTPClientConfig) },
"shadowsocks": func() interface{} { return new(ShadowsocksClientConfig) },
"socks": func() interface{} { return new(SocksClientConfig) },
"vmess": func() interface{} { return new(VMessOutboundConfig) },
"trojan": func() interface{} { return new(TrojanClientConfig) },
"dns": func() interface{} { return new(DNSOutboundConfig) },
"loopback": func() interface{} { return new(LoopbackConfig) },
}, "protocol", "settings")
ctllog = log.New(os.Stderr, "v2ctl> ", 0)
)
func toProtocolList(s []string) ([]proxyman.KnownProtocols, error) {
kp := make([]proxyman.KnownProtocols, 0, 8)
for _, p := range s {
switch strings.ToLower(p) {
case "http":
kp = append(kp, proxyman.KnownProtocols_HTTP)
case "https", "tls", "ssl":
kp = append(kp, proxyman.KnownProtocols_TLS)
default:
return nil, newError("Unknown protocol: ", p)
}
}
return kp, nil
}
type SniffingConfig struct {
Enabled bool `json:"enabled"`
DestOverride *cfgcommon.StringList `json:"destOverride"`
MetadataOnly bool `json:"metadataOnly"`
RouteOnly bool `json:"routeOnly"`
SkipDomainDestinations bool `json:"skipDomainDestinations"`
SkippedDomains []string `json:"skippedDomains"`
}
// Build implements Buildable.
func (c *SniffingConfig) Build() (*proxyman.SniffingConfig, error) {
var p []string
if c.DestOverride != nil {
for _, domainOverride := range *c.DestOverride {
switch strings.ToLower(domainOverride) {
case "http":
p = append(p, "http")
case "tls", "https", "ssl":
p = append(p, "tls")
case "fakedns":
p = append(p, "fakedns")
case "fakedns+others":
p = append(p, "fakedns+others")
default:
return nil, newError("unknown protocol: ", domainOverride)
}
}
}
return &proxyman.SniffingConfig{
Enabled: c.Enabled,
DestinationOverride: p,
MetadataOnly: c.MetadataOnly,
RouteOnly: c.RouteOnly,
SkipDomainDestinations: c.SkipDomainDestinations,
SkippedDomains: c.SkippedDomains,
}, nil
}
type MuxConfig struct {
Enabled bool `json:"enabled"`
Concurrency int16 `json:"concurrency"`
}
// Build creates MultiplexingConfig, Concurrency < 0 completely disables mux.
func (m *MuxConfig) Build() *proxyman.MultiplexingConfig {
if m.Concurrency < 0 {
return nil
}
var con uint32 = 8
if m.Concurrency > 0 {
con = uint32(m.Concurrency)
}
return &proxyman.MultiplexingConfig{
Enabled: m.Enabled,
Concurrency: con,
}
}
type InboundDetourAllocationConfig struct {
Strategy string `json:"strategy"`
Concurrency *uint32 `json:"concurrency"`
RefreshMin *uint32 `json:"refresh"`
}
// Build implements Buildable.
func (c *InboundDetourAllocationConfig) Build() (*proxyman.AllocationStrategy, error) {
config := new(proxyman.AllocationStrategy)
switch strings.ToLower(c.Strategy) {
case "always":
config.Type = proxyman.AllocationStrategy_Always
case "random":
config.Type = proxyman.AllocationStrategy_Random
case "external":
config.Type = proxyman.AllocationStrategy_External
default:
return nil, newError("unknown allocation strategy: ", c.Strategy)
}
if c.Concurrency != nil {
config.Concurrency = &proxyman.AllocationStrategy_AllocationStrategyConcurrency{
Value: *c.Concurrency,
}
}
if c.RefreshMin != nil {
config.Refresh = &proxyman.AllocationStrategy_AllocationStrategyRefresh{
Value: *c.RefreshMin,
}
}
return config, nil
}
type InboundDetourConfig struct {
Protocol string `json:"protocol"`
PortRange *cfgcommon.PortRange `json:"port"`
ListenOn *cfgcommon.Address `json:"listen"`
Settings *json.RawMessage `json:"settings"`
Tag string `json:"tag"`
Allocation *InboundDetourAllocationConfig `json:"allocate"`
StreamSetting *StreamConfig `json:"streamSettings"`
DomainOverride *cfgcommon.StringList `json:"domainOverride"`
SniffingConfig *SniffingConfig `json:"sniffing"`
}
// Build implements Buildable.
func (c *InboundDetourConfig) Build() (*core.InboundHandlerConfig, error) {
receiverSettings := &proxyman.ReceiverConfig{}
if c.ListenOn == nil {
// Listen on anyip, must set PortRange
if c.PortRange == nil {
return nil, newError("Listen on AnyIP but no Port(s) set in InboundDetour.")
}
receiverSettings.PortRange = c.PortRange.Build()
} else {
// Listen on specific IP or Unix Domain Socket
receiverSettings.Listen = c.ListenOn.Build()
listenDS := c.ListenOn.Family().IsDomain() && (c.ListenOn.Domain()[0] == '/' || c.ListenOn.Domain()[0] == '@')
listenIP := c.ListenOn.Family().IsIP() || (c.ListenOn.Family().IsDomain() && c.ListenOn.Domain() == "localhost")
switch {
case listenIP:
// Listen on specific IP, must set PortRange
if c.PortRange == nil {
return nil, newError("Listen on specific ip without port in InboundDetour.")
}
// Listen on IP:Port
receiverSettings.PortRange = c.PortRange.Build()
case listenDS:
if c.PortRange != nil {
// Listen on Unix Domain Socket, PortRange should be nil
receiverSettings.PortRange = nil
}
default:
return nil, newError("unable to listen on domain address: ", c.ListenOn.Domain())
}
}
if c.Allocation != nil {
concurrency := -1
if c.Allocation.Concurrency != nil && c.Allocation.Strategy == "random" {
concurrency = int(*c.Allocation.Concurrency)
}
portRange := int(c.PortRange.To - c.PortRange.From + 1)
if concurrency >= 0 && concurrency >= portRange {
return nil, newError("not enough ports. concurrency = ", concurrency, " ports: ", c.PortRange.From, " - ", c.PortRange.To)
}
as, err := c.Allocation.Build()
if err != nil {
return nil, err
}
receiverSettings.AllocationStrategy = as
}
if c.StreamSetting != nil {
ss, err := c.StreamSetting.Build()
if err != nil {
return nil, err
}
receiverSettings.StreamSettings = ss
}
if c.SniffingConfig != nil {
s, err := c.SniffingConfig.Build()
if err != nil {
return nil, newError("failed to build sniffing config").Base(err)
}
receiverSettings.SniffingSettings = s
}
if c.DomainOverride != nil {
kp, err := toProtocolList(*c.DomainOverride)
if err != nil {
return nil, newError("failed to parse inbound detour config").Base(err)
}
receiverSettings.DomainOverride = kp
}
settings := []byte("{}")
if c.Settings != nil {
settings = ([]byte)(*c.Settings)
}
rawConfig, err := inboundConfigLoader.LoadWithID(settings, c.Protocol)
if err != nil {
return nil, newError("failed to load inbound detour config.").Base(err)
}
if dokodemoConfig, ok := rawConfig.(*DokodemoConfig); ok {
receiverSettings.ReceiveOriginalDestination = dokodemoConfig.Redirect
}
ts, err := rawConfig.(Buildable).Build()
if err != nil {
return nil, err
}
return &core.InboundHandlerConfig{
Tag: c.Tag,
ReceiverSettings: serial.ToTypedMessage(receiverSettings),
ProxySettings: serial.ToTypedMessage(ts),
}, nil
}
type OutboundDetourConfig struct {
Protocol string `json:"protocol"`
// Name of the network interface to bind.
BindInterface string `json:"bindInterface"`
// Bind to an IPv4 address or the IPv4 address of an interface.
// When an interface is specified, the address is a domain.
Bind4 *cfgcommon.Address `json:"bind4"`
// Bind to an IPv6 address or the IPv6 address of an interface.
// When an interface is specified, the address is a domain.
Bind6 *cfgcommon.Address `json:"bind6"`
// LinuxBindInterfaceUDPUsePktinfo controls when binding a UDP socket to an interface,
// whether the IP(V6)_PKTINFO socket control message should be used instead of
// the SO_BINDTODEVICE socket option.
LinuxBindInterfaceUDPUsePktinfo bool `json:"linuxBindInterfaceUDPUsePktinfo"`
// DomainStrategy controls how domain dial targets are processed.
DomainStrategy string `json:"domainStrategy"`
// FallbackDelayMs controls the RFC 6555 happy eyeballs fast fallback delay in milliseconds.
FallbackDelayMs int32 `json:"fallbackDelayMs"`
Tag string `json:"tag"`
Settings *json.RawMessage `json:"settings"`
StreamSetting *StreamConfig `json:"streamSettings"`
ProxySettings *ProxyConfig `json:"proxySettings"`
MuxSettings *MuxConfig `json:"mux"`
}
// Build implements Buildable.
//nolint: gocritic
func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
senderSettings := &proxyman.SenderConfig{}
var bindInterfaceIndex uint32
var bindInterfaceName string
var bindInterfaceIP4 []byte
var bindInterfaceIP6 []byte
if c.BindInterface != "" {
iface, err := gonet.InterfaceByName(c.BindInterface)
if err != nil {
return nil, err
}
// These platforms have syscalls that can bind to a specific interface.
if runtime.GOOS == "linux" || runtime.GOOS == "darwin" || runtime.GOOS == "windows" {
bindInterfaceIndex = uint32(iface.Index)
bindInterfaceName = iface.Name
newError("Outbound ", c.Tag, " bound to interface index ", bindInterfaceIndex, " name ", bindInterfaceName).AtInfo().WriteToLog()
}
// On other platforms, or Linux with PKTINFO, retrieve interface IP addresses.
if (c.LinuxBindInterfaceUDPUsePktinfo || runtime.GOOS != "linux") && runtime.GOOS != "darwin" && runtime.GOOS != "windows" {
addrs, err := iface.Addrs()
if err != nil {
return nil, err
}
newError(c.BindInterface, " has ", len(addrs), " IP address(es)").AtInfo().WriteToLog()
for _, addr := range addrs {
vaddr := net.ParseAddress(addr.String())
newError("Processing ", vaddr, " family ", vaddr.Family()).AtDebug().WriteToLog()
if c.Bind4 == nil && vaddr.Family().IsIPv4() {
c.Bind4 = &cfgcommon.Address{
Address: vaddr,
}
bindInterfaceIP4 = vaddr.IP()
newError("IPv4 local address set to ", vaddr, " from ", c.BindInterface).AtInfo().WriteToLog()
} else if c.Bind6 == nil && vaddr.Family().IsIPv6() {
c.Bind6 = &cfgcommon.Address{
Address: vaddr,
}
bindInterfaceIP6 = vaddr.IP()
newError("IPv6 local address set to ", vaddr, " from ", c.BindInterface).AtInfo().WriteToLog()
} else {
newError("Skipping IP ", vaddr, " from ", c.BindInterface).AtInfo().WriteToLog()
}
}
}
}
if c.Bind4 != nil {
if c.Bind4.Family().IsIPv4() {
senderSettings.Via4 = c.Bind4.Build()
} else if c.Bind4.Family().IsDomain() {
iface, err := gonet.InterfaceByName(c.Bind4.String())
if err != nil {
return nil, err
}
addrs, err := iface.Addrs()
if err != nil {
return nil, err
}
newError(c.Bind4, " has ", len(addrs), " IP address(es)").AtInfo().WriteToLog()
for _, addr := range addrs {
vaddr := net.ParseAddress(addr.String())
newError("Processing ", vaddr, " family ", vaddr.Family()).AtDebug().WriteToLog()
if vaddr.Family().IsIPv4() {
senderSettings.Via4 = net.NewIPOrDomain(vaddr)
newError("IPv4 local address set to ", vaddr).AtInfo().WriteToLog()
break
} else {
newError("Skipping IP ", vaddr, " from ", c.Bind4).AtInfo().WriteToLog()
}
}
} else {
return nil, newError("Invalid bind4: ", c.Bind4)
}
}
if c.Bind6 != nil {
if c.Bind6.Family().IsIPv6() {
senderSettings.Via6 = c.Bind6.Build()
} else if c.Bind6.Family().IsDomain() {
iface, err := gonet.InterfaceByName(c.Bind6.String())
if err != nil {
return nil, err
}
addrs, err := iface.Addrs()
if err != nil {
return nil, err
}
newError(c.Bind6, " has ", len(addrs), " IP address(es)").AtInfo().WriteToLog()
for _, addr := range addrs {
vaddr := net.ParseAddress(addr.String())
newError("Processing ", vaddr, " family ", vaddr.Family()).AtDebug().WriteToLog()
if vaddr.Family().IsIPv6() {
senderSettings.Via6 = net.NewIPOrDomain(vaddr)
newError("IPv6 local address set to ", vaddr).AtInfo().WriteToLog()
break
} else {
newError("Skipping IP ", vaddr, " from ", c.Bind6).AtInfo().WriteToLog()
}
}
} else {
return nil, newError("Invalid bind6: ", c.Bind6)
}
}
switch c.DomainStrategy {
case "":
senderSettings.DomainStrategy = proxyman.DomainStrategy_AS_IS
case "UseIP":
senderSettings.DomainStrategy = proxyman.DomainStrategy_USE_IP
case "UseIPv4":
senderSettings.DomainStrategy = proxyman.DomainStrategy_USE_IP4
case "UseIPv6":
senderSettings.DomainStrategy = proxyman.DomainStrategy_USE_IP6
}
senderSettings.FallbackDelayMs = c.FallbackDelayMs
if c.StreamSetting != nil {
ss, err := c.StreamSetting.Build()
if err != nil {
return nil, err
}
senderSettings.StreamSettings = ss
}
if bindInterfaceIndex != 0 {
if senderSettings.StreamSettings == nil {
senderSettings.StreamSettings = &internet.StreamConfig{
ProtocolName: "tcp",
SocketSettings: &internet.SocketConfig{
BindInterfaceIndex: bindInterfaceIndex,
BindInterfaceName: bindInterfaceName,
BindInterfaceIp4: bindInterfaceIP4,
BindInterfaceIp6: bindInterfaceIP6,
LinuxBindInterfaceUdpUsePktinfo: c.LinuxBindInterfaceUDPUsePktinfo,
},
}
} else if senderSettings.StreamSettings.SocketSettings == nil {
senderSettings.StreamSettings.SocketSettings = &internet.SocketConfig{
BindInterfaceIndex: bindInterfaceIndex,
BindInterfaceName: bindInterfaceName,
BindInterfaceIp4: bindInterfaceIP4,
BindInterfaceIp6: bindInterfaceIP6,
LinuxBindInterfaceUdpUsePktinfo: c.LinuxBindInterfaceUDPUsePktinfo,
}
} else {
senderSettings.StreamSettings.SocketSettings.BindInterfaceIndex = bindInterfaceIndex
senderSettings.StreamSettings.SocketSettings.BindInterfaceName = bindInterfaceName
senderSettings.StreamSettings.SocketSettings.BindInterfaceIp4 = bindInterfaceIP4
senderSettings.StreamSettings.SocketSettings.BindInterfaceIp6 = bindInterfaceIP6
senderSettings.StreamSettings.SocketSettings.LinuxBindInterfaceUdpUsePktinfo = c.LinuxBindInterfaceUDPUsePktinfo
}
}
if c.ProxySettings != nil {
ps, err := c.ProxySettings.Build()
if err != nil {
return nil, newError("invalid outbound detour proxy settings.").Base(err)
}
senderSettings.ProxySettings = ps
}
if c.MuxSettings != nil {
senderSettings.MultiplexSettings = c.MuxSettings.Build()
}
settings := []byte("{}")
if c.Settings != nil {
settings = ([]byte)(*c.Settings)
}
rawConfig, err := outboundConfigLoader.LoadWithID(settings, c.Protocol)
if err != nil {
return nil, newError("failed to parse to outbound detour config.").Base(err)
}
ts, err := rawConfig.(Buildable).Build()
if err != nil {
return nil, err
}
return &core.OutboundHandlerConfig{
SenderSettings: serial.ToTypedMessage(senderSettings),
Tag: c.Tag,
ProxySettings: serial.ToTypedMessage(ts),
}, nil
}
type StatsConfig struct{}
// Build implements Buildable.
func (c *StatsConfig) Build() (*stats.Config, error) {
return &stats.Config{}, nil
}
type Config struct {
// Port of this Point server.
// Deprecated: Port exists for historical compatibility
// and should not be used.
Port uint16 `json:"port"`
LogConfig *LogConfig `json:"log"`
RouterConfig *RouterConfig `json:"routing"`
DNSConfig *DNSConfig `json:"dns"`
InboundConfigs []InboundDetourConfig `json:"inbounds"`
OutboundConfigs []OutboundDetourConfig `json:"outbounds"`
Transport *TransportConfig `json:"transport"`
Policy *PolicyConfig `json:"policy"`
API *APIConfig `json:"api"`
Stats *StatsConfig `json:"stats"`
Reverse *ReverseConfig `json:"reverse"`
FakeDNS *FakeDNSConfig `json:"fakeDns"`
BrowserForwarder *BrowserForwarderConfig `json:"browserForwarder"`
Observatory *ObservatoryConfig `json:"observatory"`
Services map[string]*json.RawMessage `json:"services"`
}
func (c *Config) findInboundTag(tag string) int {
found := -1
for idx, ib := range c.InboundConfigs {
if ib.Tag == tag {
found = idx
break
}
}
return found
}
func (c *Config) findOutboundTag(tag string) int {
found := -1
for idx, ob := range c.OutboundConfigs {
if ob.Tag == tag {
found = idx
break
}
}
return found
}
// Override method accepts another Config overrides the current attribute
func (c *Config) Override(o *Config, fn string) {
// only process the non-deprecated members
if o.LogConfig != nil {
c.LogConfig = o.LogConfig
}
if o.RouterConfig != nil {
c.RouterConfig = o.RouterConfig
}
if o.DNSConfig != nil {
c.DNSConfig = o.DNSConfig
}
if o.Transport != nil {
c.Transport = o.Transport
}
if o.Policy != nil {
c.Policy = o.Policy
}
if o.API != nil {
c.API = o.API
}
if o.Stats != nil {
c.Stats = o.Stats
}
if o.Reverse != nil {
c.Reverse = o.Reverse
}
if o.FakeDNS != nil {
c.FakeDNS = o.FakeDNS
}
if o.BrowserForwarder != nil {
c.BrowserForwarder = o.BrowserForwarder
}
if o.Observatory != nil {
c.Observatory = o.Observatory
}
// update the Inbound in slice if the only one in overide config has same tag
if len(o.InboundConfigs) > 0 {
if len(c.InboundConfigs) > 0 && len(o.InboundConfigs) == 1 {
if idx := c.findInboundTag(o.InboundConfigs[0].Tag); idx > -1 {
c.InboundConfigs[idx] = o.InboundConfigs[0]
ctllog.Println("[", fn, "] updated inbound with tag: ", o.InboundConfigs[0].Tag)
} else {
c.InboundConfigs = append(c.InboundConfigs, o.InboundConfigs[0])
ctllog.Println("[", fn, "] appended inbound with tag: ", o.InboundConfigs[0].Tag)
}
} else {
c.InboundConfigs = o.InboundConfigs
}
}
// update the Outbound in slice if the only one in overide config has same tag
if len(o.OutboundConfigs) > 0 {
if len(c.OutboundConfigs) > 0 && len(o.OutboundConfigs) == 1 {
if idx := c.findOutboundTag(o.OutboundConfigs[0].Tag); idx > -1 {
c.OutboundConfigs[idx] = o.OutboundConfigs[0]
ctllog.Println("[", fn, "] updated outbound with tag: ", o.OutboundConfigs[0].Tag)
} else {
if strings.Contains(strings.ToLower(fn), "tail") {
c.OutboundConfigs = append(c.OutboundConfigs, o.OutboundConfigs[0])
ctllog.Println("[", fn, "] appended outbound with tag: ", o.OutboundConfigs[0].Tag)
} else {
c.OutboundConfigs = append(o.OutboundConfigs, c.OutboundConfigs...)
ctllog.Println("[", fn, "] prepended outbound with tag: ", o.OutboundConfigs[0].Tag)
}
}
} else {
c.OutboundConfigs = o.OutboundConfigs
}
}
}
func applyTransportConfig(s *StreamConfig, t *TransportConfig) {
if s.TCPSettings == nil {
s.TCPSettings = t.TCPConfig
}
if s.KCPSettings == nil {
s.KCPSettings = t.KCPConfig
}
if s.WSSettings == nil {
s.WSSettings = t.WSConfig
}
if s.HTTPSettings == nil {
s.HTTPSettings = t.HTTPConfig
}
if s.DSSettings == nil {
s.DSSettings = t.DSConfig
}
}
// Build implements Buildable.
func (c *Config) Build() (*core.Config, error) {
if err := PostProcessConfigureFile(c); err != nil {
return nil, err
}
config := &core.Config{
App: []*serial.TypedMessage{
serial.ToTypedMessage(&dispatcher.Config{}),
serial.ToTypedMessage(&proxyman.InboundConfig{}),
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
},
}
if c.API != nil {
apiConf, err := c.API.Build()
if err != nil {
return nil, err
}
config.App = append(config.App, serial.ToTypedMessage(apiConf))
}
if c.Stats != nil {
statsConf, err := c.Stats.Build()
if err != nil {
return nil, err
}
config.App = append(config.App, serial.ToTypedMessage(statsConf))
}
var logConfMsg *serial.TypedMessage
if c.LogConfig != nil {
logConfMsg = serial.ToTypedMessage(c.LogConfig.Build())
} else {
logConfMsg = serial.ToTypedMessage(DefaultLogConfig())
}
// let logger module be the first App to start,
// so that other modules could print log during initiating
config.App = append([]*serial.TypedMessage{logConfMsg}, config.App...)
if c.RouterConfig != nil {
routerConfig, err := c.RouterConfig.Build()
if err != nil {
return nil, err
}
config.App = append(config.App, serial.ToTypedMessage(routerConfig))
}
if c.DNSConfig != nil {
dnsApp, err := c.DNSConfig.Build()
if err != nil {
return nil, newError("failed to parse DNS config").Base(err)
}
config.App = append(config.App, serial.ToTypedMessage(dnsApp))
}
if c.Policy != nil {
pc, err := c.Policy.Build()
if err != nil {
return nil, err
}
config.App = append(config.App, serial.ToTypedMessage(pc))
}
if c.Reverse != nil {
r, err := c.Reverse.Build()
if err != nil {
return nil, err
}
config.App = append(config.App, serial.ToTypedMessage(r))
}
if c.FakeDNS != nil {
r, err := c.FakeDNS.Build()
if err != nil {
return nil, err
}
config.App = append(config.App, serial.ToTypedMessage(r))
}
if c.BrowserForwarder != nil {
r, err := c.BrowserForwarder.Build()
if err != nil {
return nil, err
}
config.App = append(config.App, serial.ToTypedMessage(r))
}
if c.Observatory != nil {
r, err := c.Observatory.Build()
if err != nil {
return nil, err
}
config.App = append(config.App, serial.ToTypedMessage(r))
}
// Load Additional Services that do not have a json translator
if msg, err := c.BuildServices(c.Services); err != nil {
developererr := newError("Loading a V2Ray Features as a service is intended for developers only. " +
"This is used for developers to prototype new features or for an advanced client to use special features in V2Ray," +
" instead of allowing end user to enable it without special tool and knowledge.")
sb := strings.Builder{}
return nil, newError("Cannot load service").Base(developererr).Base(err).Base(newError(sb.String()))
} else { // nolint: golint
// Using a else here is required to keep msg in scope
config.App = append(config.App, msg...)
}
var inbounds []InboundDetourConfig
if len(c.InboundConfigs) > 0 {
inbounds = append(inbounds, c.InboundConfigs...)
}
// Backward compatibility.
if len(inbounds) > 0 && inbounds[0].PortRange == nil && c.Port > 0 {
inbounds[0].PortRange = &cfgcommon.PortRange{
From: uint32(c.Port),
To: uint32(c.Port),
}
}
for _, rawInboundConfig := range inbounds {
if c.Transport != nil {
if rawInboundConfig.StreamSetting == nil {
rawInboundConfig.StreamSetting = &StreamConfig{}
}
applyTransportConfig(rawInboundConfig.StreamSetting, c.Transport)
}
ic, err := rawInboundConfig.Build()
if err != nil {
return nil, err
}
config.Inbound = append(config.Inbound, ic)
}
var outbounds []OutboundDetourConfig
if len(c.OutboundConfigs) > 0 {
outbounds = append(outbounds, c.OutboundConfigs...)
}
for _, rawOutboundConfig := range outbounds {
if c.Transport != nil {
if rawOutboundConfig.StreamSetting == nil {
rawOutboundConfig.StreamSetting = &StreamConfig{}
}
applyTransportConfig(rawOutboundConfig.StreamSetting, c.Transport)
}
oc, err := rawOutboundConfig.Build()
if err != nil {
return nil, err
}
config.Outbound = append(config.Outbound, oc)
}
return config, nil
}