dialer.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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, streamSettings *MemoryStreamConfig) (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, streamSettings *MemoryStreamConfig) (Connection, error) {
  29. if dest.Network == net.Network_TCP {
  30. if streamSettings == nil {
  31. s, err := ToMemoryStreamConfig(nil)
  32. if err != nil {
  33. return nil, newError("failed to create default stream settings").Base(err)
  34. }
  35. streamSettings = s
  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, streamSettings)
  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, streamSettings)
  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, sockopt *SocketConfig) (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, sockopt)
  60. }