dialer.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package internet
  2. import (
  3. "crypto/tls"
  4. "errors"
  5. "net"
  6. v2net "github.com/v2ray/v2ray-core/common/net"
  7. v2tls "github.com/v2ray/v2ray-core/transport/internet/tls"
  8. )
  9. var (
  10. ErrUnsupportedStreamType = errors.New("Unsupported stream type.")
  11. )
  12. type Dialer func(src v2net.Address, dest v2net.Destination) (Connection, error)
  13. var (
  14. TCPDialer Dialer
  15. KCPDialer Dialer
  16. RawTCPDialer Dialer
  17. UDPDialer Dialer
  18. )
  19. func Dial(src v2net.Address, dest v2net.Destination, settings *StreamSettings) (Connection, error) {
  20. var connection Connection
  21. var err error
  22. if dest.IsTCP() {
  23. switch {
  24. case settings.IsCapableOf(StreamConnectionTypeTCP):
  25. connection, err = TCPDialer(src, dest)
  26. case settings.IsCapableOf(StreamConnectionTypeKCP):
  27. connection, err = KCPDialer(src, dest)
  28. case settings.IsCapableOf(StreamConnectionTypeRawTCP):
  29. connection, err = RawTCPDialer(src, dest)
  30. default:
  31. return nil, ErrUnsupportedStreamType
  32. }
  33. if err != nil {
  34. return nil, err
  35. }
  36. if settings.Security == StreamSecurityTypeNone {
  37. return connection, nil
  38. }
  39. config := settings.TLSSettings.GetTLSConfig()
  40. if dest.Address().Family().IsDomain() {
  41. config.ServerName = dest.Address().Domain()
  42. }
  43. tlsConn := tls.Client(connection, config)
  44. return v2tls.NewConnection(tlsConn), nil
  45. }
  46. return UDPDialer(src, dest)
  47. }
  48. func DialToDest(src v2net.Address, dest v2net.Destination) (net.Conn, error) {
  49. return effectiveSystemDialer.Dial(src, dest)
  50. }