forked from v2ray/v2ray-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcp_hub.go
75 lines (67 loc) · 1.93 KB
/
tcp_hub.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
package internet
import (
"context"
"net"
"time"
v2net "v2ray.com/core/common/net"
)
var (
transportListenerCache = make(map[TransportProtocol]ListenFunc)
)
func RegisterTransportListener(protocol TransportProtocol, listener ListenFunc) error {
if _, found := transportListenerCache[protocol]; found {
return newError(protocol, " listener already registered.").AtError()
}
transportListenerCache[protocol] = listener
return nil
}
type AddConnection func(context.Context, Connection) bool
type ListenFunc func(ctx context.Context, address v2net.Address, port v2net.Port, addConn AddConnection) (Listener, error)
type Listener interface {
Close() error
Addr() net.Addr
}
func ListenTCP(ctx context.Context, address v2net.Address, port v2net.Port, conns chan<- Connection) (Listener, error) {
settings := StreamSettingsFromContext(ctx)
protocol := settings.GetEffectiveProtocol()
transportSettings, err := settings.GetEffectiveTransportSettings()
if err != nil {
return nil, err
}
ctx = ContextWithTransportSettings(ctx, transportSettings)
if settings != nil && settings.HasSecuritySettings() {
securitySettings, err := settings.GetEffectiveSecuritySettings()
if err != nil {
return nil, err
}
ctx = ContextWithSecuritySettings(ctx, securitySettings)
}
listenFunc := transportListenerCache[protocol]
if listenFunc == nil {
return nil, newError(protocol, " listener not registered.").AtError()
}
listener, err := listenFunc(ctx, address, port, func(ctx context.Context, conn Connection) bool {
select {
case <-ctx.Done():
conn.Close()
return false
case conns <- conn:
return true
default:
select {
case <-ctx.Done():
conn.Close()
return false
case conns <- conn:
return true
case <-time.After(time.Second * 5):
conn.Close()
return false
}
}
})
if err != nil {
return nil, newError("failed to listen on address: ", address, ":", port).Base(err)
}
return listener, nil
}