1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-09-29 15:26:29 -04:00
v2fly/transport/internet/tcp_hub.go

55 lines
1.6 KiB
Go
Raw Normal View History

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