dialer.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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[TransportProtocol]Dialer)
  9. )
  10. func RegisterTransportDialer(protocol TransportProtocol, 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. func Dial(ctx context.Context, dest net.Destination) (Connection, error) {
  18. if dest.Network == net.Network_TCP {
  19. streamSettings := StreamSettingsFromContext(ctx)
  20. protocol := streamSettings.GetEffectiveProtocol()
  21. transportSettings, err := streamSettings.GetEffectiveTransportSettings()
  22. if err != nil {
  23. return nil, err
  24. }
  25. ctx = ContextWithTransportSettings(ctx, transportSettings)
  26. if streamSettings != nil && streamSettings.HasSecuritySettings() {
  27. securitySettings, err := streamSettings.GetEffectiveSecuritySettings()
  28. if err != nil {
  29. return nil, err
  30. }
  31. ctx = ContextWithSecuritySettings(ctx, securitySettings)
  32. }
  33. dialer := transportDialerCache[protocol]
  34. if dialer == nil {
  35. return nil, newError(protocol, " dialer not registered").AtError()
  36. }
  37. return dialer(ctx, dest)
  38. }
  39. udpDialer := transportDialerCache[TransportProtocol_UDP]
  40. if udpDialer == nil {
  41. return nil, newError("UDP dialer not registered").AtError()
  42. }
  43. return udpDialer(ctx, dest)
  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. }