dialer.go 2.1 KB

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