-
Notifications
You must be signed in to change notification settings - Fork 0
/
hub.go
97 lines (83 loc) · 2.41 KB
/
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// +build !confonly
package tcp
import (
"context"
gotls "crypto/tls"
"strings"
"v2ray.com/core/common"
"v2ray.com/core/common/net"
"v2ray.com/core/common/session"
"v2ray.com/core/transport/internet"
"v2ray.com/core/transport/internet/tls"
)
// Listener is an internet.Listener that listens for TCP connections.
type Listener struct {
listener net.Listener
tlsConfig *gotls.Config
authConfig internet.ConnectionAuthenticator
config *Config
addConn internet.ConnHandler
}
// ListenTCP creates a new Listener based on configurations.
func ListenTCP(ctx context.Context, address net.Address, port net.Port, streamSettings *internet.MemoryStreamConfig, handler internet.ConnHandler) (internet.Listener, error) {
listener, err := internet.ListenSystem(ctx, &net.TCPAddr{
IP: address.IP(),
Port: int(port),
}, streamSettings.SocketSettings)
if err != nil {
return nil, err
}
newError("listening TCP on ", address, ":", port).WriteToLog(session.ExportIDToError(ctx))
tcpSettings := streamSettings.ProtocolSettings.(*Config)
l := &Listener{
listener: listener,
config: tcpSettings,
addConn: handler,
}
if config := tls.ConfigFromStreamSettings(streamSettings); config != nil {
l.tlsConfig = config.GetTLSConfig(tls.WithNextProto("h2"))
}
if tcpSettings.HeaderSettings != nil {
headerConfig, err := tcpSettings.HeaderSettings.GetInstance()
if err != nil {
return nil, newError("invalid header settings").Base(err).AtError()
}
auth, err := internet.CreateConnectionAuthenticator(headerConfig)
if err != nil {
return nil, newError("invalid header settings.").Base(err).AtError()
}
l.authConfig = auth
}
go l.keepAccepting()
return l, nil
}
func (v *Listener) keepAccepting() {
for {
conn, err := v.listener.Accept()
if err != nil {
if strings.Contains(err.Error(), "closed") {
break
}
newError("failed to accepted raw connections").Base(err).AtWarning().WriteToLog()
continue
}
if v.tlsConfig != nil {
conn = tls.Server(conn, v.tlsConfig)
}
if v.authConfig != nil {
conn = v.authConfig.Server(conn)
}
v.addConn(internet.Connection(conn))
}
}
// Addr implements internet.Listener.Addr.
func (v *Listener) Addr() net.Addr {
return v.listener.Addr()
}
// Close implements internet.Listener.Close.
func (v *Listener) Close() error {
return v.listener.Close()
}
func init() {
common.Must(internet.RegisterTransportListener(protocolName, ListenTCP))
}