tcp_hub.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package internet
  2. import (
  3. "context"
  4. "net"
  5. v2net "v2ray.com/core/common/net"
  6. )
  7. var (
  8. transportListenerCache = make(map[TransportProtocol]ListenFunc)
  9. )
  10. func RegisterTransportListener(protocol TransportProtocol, listener ListenFunc) error {
  11. if _, found := transportListenerCache[protocol]; found {
  12. return newError(protocol, " listener already registered.").AtError()
  13. }
  14. transportListenerCache[protocol] = listener
  15. return nil
  16. }
  17. type ListenFunc func(ctx context.Context, address v2net.Address, port v2net.Port, conns chan<- Connection) (Listener, error)
  18. type Listener interface {
  19. Close() error
  20. Addr() net.Addr
  21. }
  22. func ListenTCP(ctx context.Context, address v2net.Address, port v2net.Port, conns chan<- Connection) (Listener, error) {
  23. settings := StreamSettingsFromContext(ctx)
  24. protocol := settings.GetEffectiveProtocol()
  25. transportSettings, err := settings.GetEffectiveTransportSettings()
  26. if err != nil {
  27. return nil, err
  28. }
  29. ctx = ContextWithTransportSettings(ctx, transportSettings)
  30. if settings != nil && settings.HasSecuritySettings() {
  31. securitySettings, err := settings.GetEffectiveSecuritySettings()
  32. if err != nil {
  33. return nil, err
  34. }
  35. ctx = ContextWithSecuritySettings(ctx, securitySettings)
  36. }
  37. listenFunc := transportListenerCache[protocol]
  38. if listenFunc == nil {
  39. return nil, newError(protocol, " listener not registered.").AtError()
  40. }
  41. listener, err := listenFunc(ctx, address, port, conns)
  42. if err != nil {
  43. return nil, newError("failed to listen on address: ", address, ":", port).Base(err)
  44. }
  45. return listener, nil
  46. }