tcp_hub.go 1.6 KB

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