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. var protocol string
  22. if streamSettings != nil {
  23. protocol = streamSettings.ProtocolName
  24. } else {
  25. protocol = "tcp"
  26. pSettings, err := CreateTransportConfigByName(protocol)
  27. if err != nil {
  28. return nil, newError("failed to create default config for protocol: ", protocol).Base(err)
  29. }
  30. ctx = ContextWithStreamSettings(ctx, &MemoryStreamConfig{
  31. ProtocolName: protocol,
  32. ProtocolSettings: pSettings,
  33. })
  34. }
  35. dialer := transportDialerCache[protocol]
  36. if dialer == nil {
  37. return nil, newError(protocol, " dialer not registered").AtError()
  38. }
  39. return dialer(ctx, dest)
  40. }
  41. udpDialer := transportDialerCache["udp"]
  42. if udpDialer == nil {
  43. return nil, newError("UDP dialer not registered").AtError()
  44. }
  45. return udpDialer(ctx, dest)
  46. }
  47. // DialSystem calls system dialer to create a network connection.
  48. func DialSystem(ctx context.Context, src net.Address, dest net.Destination) (net.Conn, error) {
  49. return effectiveSystemDialer.Dial(ctx, src, dest)
  50. }