dialer.go 2.2 KB

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