forked from v2fly/v2ray-core
-
Notifications
You must be signed in to change notification settings - Fork 29
/
inbound_detour_always.go
74 lines (67 loc) · 1.99 KB
/
inbound_detour_always.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
package point
import (
"github.com/v2ray/v2ray-core/app"
"github.com/v2ray/v2ray-core/common/dice"
"github.com/v2ray/v2ray-core/common/log"
v2net "github.com/v2ray/v2ray-core/common/net"
"github.com/v2ray/v2ray-core/common/retry"
"github.com/v2ray/v2ray-core/proxy"
proxyrepo "github.com/v2ray/v2ray-core/proxy/repo"
)
type InboundConnectionHandlerWithPort struct {
port v2net.Port
handler proxy.InboundHandler
}
// Handler for inbound detour connections.
type InboundDetourHandlerAlways struct {
space app.Space
config *InboundDetourConfig
ich []*InboundConnectionHandlerWithPort
}
func NewInboundDetourHandlerAlways(space app.Space, config *InboundDetourConfig) (*InboundDetourHandlerAlways, error) {
handler := &InboundDetourHandlerAlways{
space: space,
config: config,
}
ports := config.PortRange
handler.ich = make([]*InboundConnectionHandlerWithPort, 0, ports.To-ports.From+1)
for i := ports.From; i <= ports.To; i++ {
ichConfig := config.Settings
ich, err := proxyrepo.CreateInboundHandler(config.Protocol, space, ichConfig)
if err != nil {
log.Error("Failed to create inbound connection handler: ", err)
return nil, err
}
handler.ich = append(handler.ich, &InboundConnectionHandlerWithPort{
port: i,
handler: ich,
})
}
return handler, nil
}
func (this *InboundDetourHandlerAlways) GetConnectionHandler() (proxy.InboundHandler, int) {
ich := this.ich[dice.Roll(len(this.ich))]
return ich.handler, this.config.Allocation.Refresh
}
func (this *InboundDetourHandlerAlways) Close() {
for _, ich := range this.ich {
ich.handler.Close()
}
}
// Starts the inbound connection handler.
func (this *InboundDetourHandlerAlways) Start() error {
for _, ich := range this.ich {
err := retry.Timed(100 /* times */, 100 /* ms */).On(func() error {
err := ich.handler.Listen(ich.port)
if err != nil {
log.Error("Failed to start inbound detour on port ", ich.port, ": ", err)
return err
}
return nil
})
if err != nil {
return err
}
}
return nil
}