dialer.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package tcp
  2. import (
  3. "errors"
  4. "net"
  5. "crypto/tls"
  6. "v2ray.com/core/common/log"
  7. v2net "v2ray.com/core/common/net"
  8. "v2ray.com/core/transport/internet"
  9. v2tls "v2ray.com/core/transport/internet/tls"
  10. )
  11. var (
  12. globalCache = NewConnectionCache()
  13. )
  14. func Dial(src v2net.Address, dest v2net.Destination, options internet.DialerOptions) (internet.Connection, error) {
  15. log.Info("Dailing TCP to ", dest)
  16. if src == nil {
  17. src = v2net.AnyIP
  18. }
  19. networkSettings, err := options.Stream.GetEffectiveNetworkSettings()
  20. if err != nil {
  21. return nil, err
  22. }
  23. tcpSettings := networkSettings.(*Config)
  24. id := src.String() + "-" + dest.NetAddr()
  25. var conn net.Conn
  26. if dest.Network == v2net.Network_TCP && tcpSettings.ConnectionReuse.IsEnabled() {
  27. conn = globalCache.Get(id)
  28. }
  29. if conn == nil {
  30. var err error
  31. conn, err = internet.DialToDest(src, dest)
  32. if err != nil {
  33. return nil, err
  34. }
  35. if options.Stream != nil && options.Stream.HasSecuritySettings() {
  36. securitySettings, err := options.Stream.GetEffectiveSecuritySettings()
  37. if err != nil {
  38. log.Error("TCP: Failed to get security settings: ", err)
  39. return nil, err
  40. }
  41. tlsConfig, ok := securitySettings.(*v2tls.Config)
  42. if ok {
  43. config := tlsConfig.GetTLSConfig()
  44. if dest.Address.Family().IsDomain() {
  45. config.ServerName = dest.Address.Domain()
  46. }
  47. conn = tls.Client(conn, config)
  48. }
  49. }
  50. if tcpSettings.HeaderSettings != nil {
  51. headerConfig, err := tcpSettings.HeaderSettings.GetInstance()
  52. if err != nil {
  53. return nil, errors.New("TCP: Failed to get header settings: " + err.Error())
  54. }
  55. auth, err := internet.CreateConnectionAuthenticator(tcpSettings.HeaderSettings.Type, headerConfig)
  56. if err != nil {
  57. return nil, errors.New("TCP: Failed to create header authenticator: " + err.Error())
  58. }
  59. conn = auth.Client(conn)
  60. }
  61. }
  62. return NewConnection(id, conn, globalCache, tcpSettings), nil
  63. }
  64. func DialRaw(src v2net.Address, dest v2net.Destination, options internet.DialerOptions) (internet.Connection, error) {
  65. log.Info("Dailing Raw TCP to ", dest)
  66. conn, err := internet.DialToDest(src, dest)
  67. if err != nil {
  68. return nil, err
  69. }
  70. // TODO: handle dialer options
  71. return &RawConnection{
  72. TCPConn: *conn.(*net.TCPConn),
  73. }, nil
  74. }
  75. func init() {
  76. internet.TCPDialer = Dial
  77. internet.RawTCPDialer = DialRaw
  78. }