1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-06-10 09:50:43 +00:00
v2fly/transport/internet/tcp_hub.go

54 lines
1.5 KiB
Go
Raw Normal View History

2016-06-14 20:54:08 +00:00
package internet
import (
2017-02-24 00:05:16 +00:00
"context"
2017-02-26 13:38:41 +00:00
"net"
2017-02-24 00:05:16 +00:00
2016-08-20 18:55:45 +00:00
v2net "v2ray.com/core/common/net"
2016-06-14 20:54:08 +00:00
)
var (
transportListenerCache = make(map[TransportProtocol]ListenFunc)
2016-06-14 20:54:08 +00:00
)
func RegisterTransportListener(protocol TransportProtocol, listener ListenFunc) error {
if _, found := transportListenerCache[protocol]; found {
2017-04-08 23:43:25 +00:00
return newError(protocol, " listener already registered.").AtError()
2017-01-03 14:16:48 +00:00
}
transportListenerCache[protocol] = listener
2017-01-03 14:16:48 +00:00
return nil
}
2017-02-26 13:38:41 +00:00
type ListenFunc func(ctx context.Context, address v2net.Address, port v2net.Port, conns chan<- Connection) (Listener, error)
2016-09-30 14:53:40 +00:00
2016-06-14 20:54:08 +00:00
type Listener interface {
Close() error
Addr() net.Addr
}
2017-02-26 13:38:41 +00:00
func ListenTCP(ctx context.Context, address v2net.Address, port v2net.Port, conns chan<- Connection) (Listener, error) {
settings := StreamSettingsFromContext(ctx)
protocol := settings.GetEffectiveProtocol()
2017-02-24 00:05:16 +00:00
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]
2017-01-03 14:16:48 +00:00
if listenFunc == nil {
2017-04-08 23:43:25 +00:00
return nil, newError(protocol, " listener not registered.").AtError()
2016-06-14 20:54:08 +00:00
}
2017-02-26 13:38:41 +00:00
listener, err := listenFunc(ctx, address, port, conns)
2016-06-14 20:54:08 +00:00
if err != nil {
2017-04-08 23:43:25 +00:00
return nil, newError("failed to listen on address: ", address, ":", port).Base(err)
2016-06-14 20:54:08 +00:00
}
2017-02-26 13:38:41 +00:00
return listener, nil
2016-06-14 20:54:08 +00:00
}