dialer.go 1.6 KB

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