dialer.go 1.7 KB

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