tcp_hub.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package internet
  2. import (
  3. "context"
  4. "v2ray.com/core/common/net"
  5. )
  6. var (
  7. transportListenerCache = make(map[string]ListenFunc)
  8. )
  9. func RegisterTransportListener(protocol string, 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. if settings == nil {
  25. s, err := ToMemoryStreamConfig(nil)
  26. if err != nil {
  27. return nil, newError("failed to create default stream settings").Base(err)
  28. }
  29. settings = s
  30. ctx = ContextWithStreamSettings(ctx, settings)
  31. }
  32. if address.Family().IsDomain() && address.Domain() == "localhost" {
  33. address = net.LocalHostIP
  34. }
  35. protocol := settings.ProtocolName
  36. listenFunc := transportListenerCache[protocol]
  37. if listenFunc == nil {
  38. return nil, newError(protocol, " listener not registered.").AtError()
  39. }
  40. listener, err := listenFunc(ctx, address, port, handler)
  41. if err != nil {
  42. return nil, newError("failed to listen on address: ", address, ":", port).Base(err)
  43. }
  44. return listener, nil
  45. }
  46. func ListenSystem(ctx context.Context, addr net.Addr) (net.Listener, error) {
  47. return effectiveListener.Listen(ctx, addr)
  48. }
  49. func ListenSystemPacket(ctx context.Context, addr net.Addr) (net.PacketConn, error) {
  50. return effectiveListener.ListenPacket(ctx, addr)
  51. }