dialer.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package internet
  2. import (
  3. "context"
  4. "v2ray.com/core/common/net"
  5. "v2ray.com/core/common/session"
  6. )
  7. // Dialer is an interface to dial network connection to a specific destination.
  8. type Dialer func(ctx context.Context, dest net.Destination) (Connection, error)
  9. var (
  10. transportDialerCache = make(map[string]Dialer)
  11. )
  12. // RegisterTransportDialer registers a Dialer with given name.
  13. func RegisterTransportDialer(protocol string, dialer Dialer) error {
  14. if _, found := transportDialerCache[protocol]; found {
  15. return newError(protocol, " dialer already registered").AtError()
  16. }
  17. transportDialerCache[protocol] = dialer
  18. return nil
  19. }
  20. // Dial dials a internet connection towards the given destination.
  21. func Dial(ctx context.Context, dest net.Destination) (Connection, error) {
  22. if dest.Network == net.Network_TCP {
  23. streamSettings := StreamSettingsFromContext(ctx)
  24. if streamSettings == nil {
  25. s, err := ToMemoryStreamConfig(nil)
  26. if err != nil {
  27. return nil, newError("failed to create default stream settings").Base(err)
  28. }
  29. streamSettings = s
  30. ctx = ContextWithStreamSettings(ctx, streamSettings)
  31. }
  32. protocol := streamSettings.ProtocolName
  33. dialer := transportDialerCache[protocol]
  34. if dialer == nil {
  35. return nil, newError(protocol, " dialer not registered").AtError()
  36. }
  37. return dialer(ctx, dest)
  38. }
  39. if dest.Network == net.Network_UDP {
  40. udpDialer := transportDialerCache["udp"]
  41. if udpDialer == nil {
  42. return nil, newError("UDP dialer not registered").AtError()
  43. }
  44. return udpDialer(ctx, dest)
  45. }
  46. return nil, newError("unknown network ", dest.Network)
  47. }
  48. // DialSystem calls system dialer to create a network connection.
  49. func DialSystem(ctx context.Context, dest net.Destination) (net.Conn, error) {
  50. var src net.Address
  51. if outbound := session.OutboundFromContext(ctx); outbound != nil {
  52. src = outbound.Gateway
  53. }
  54. return effectiveSystemDialer.Dial(ctx, src, dest)
  55. }