tcp_hub.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package internet
  2. import (
  3. "context"
  4. "v2ray.com/core/common/net"
  5. )
  6. var (
  7. transportListenerCache = make(map[TransportProtocol]ListenFunc)
  8. )
  9. func RegisterTransportListener(protocol TransportProtocol, listener ListenFunc) error {
  10. if _, found := transportListenerCache[protocol]; found {
  11. return newError(protocol, " listener already registered.").AtError()
  12. }
  13. transportListenerCache[protocol] = listener
  14. return nil
  15. }
  16. type ConnHandler func(Connection)
  17. type ListenFunc func(ctx context.Context, address net.Address, port net.Port, handler ConnHandler) (Listener, error)
  18. type Listener interface {
  19. Close() error
  20. Addr() net.Addr
  21. }
  22. func ListenTCP(ctx context.Context, address net.Address, port net.Port, handler ConnHandler) (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, handler)
  42. if err != nil {
  43. return nil, newError("failed to listen on address: ", address, ":", port).Base(err)
  44. }
  45. return listener, nil
  46. }