dialer.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. protocol := streamSettings.GetEffectiveProtocol()
  22. transportSettings, err := streamSettings.GetEffectiveTransportSettings()
  23. if err != nil {
  24. return nil, err
  25. }
  26. ctx = ContextWithTransportSettings(ctx, transportSettings)
  27. if streamSettings != nil && streamSettings.HasSecuritySettings() {
  28. securitySettings, err := streamSettings.GetEffectiveSecuritySettings()
  29. if err != nil {
  30. return nil, err
  31. }
  32. ctx = ContextWithSecuritySettings(ctx, securitySettings)
  33. }
  34. dialer := transportDialerCache[protocol]
  35. if dialer == nil {
  36. return nil, newError(protocol, " dialer not registered").AtError()
  37. }
  38. return dialer(ctx, dest)
  39. }
  40. udpDialer := transportDialerCache["udp"]
  41. if udpDialer == nil {
  42. return nil, newError("UDP dialer not registered").AtError()
  43. }
  44. return udpDialer(ctx, dest)
  45. }
  46. // DialSystem calls system dialer to create a network connection.
  47. func DialSystem(ctx context.Context, src net.Address, dest net.Destination) (net.Conn, error) {
  48. return effectiveSystemDialer.Dial(ctx, src, dest)
  49. }