dialer.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package tcp
  2. import (
  3. "net"
  4. "crypto/tls"
  5. "v2ray.com/core/common/log"
  6. v2net "v2ray.com/core/common/net"
  7. "v2ray.com/core/transport/internet"
  8. )
  9. var (
  10. globalCache = NewConnectionCache()
  11. )
  12. func Dial(src v2net.Address, dest v2net.Destination, options internet.DialerOptions) (internet.Connection, error) {
  13. log.Info("Dailing TCP to ", dest)
  14. if src == nil {
  15. src = v2net.AnyIP
  16. }
  17. id := src.String() + "-" + dest.NetAddr()
  18. var conn net.Conn
  19. if dest.Network == v2net.Network_TCP && effectiveConfig.ConnectionReuse {
  20. conn = globalCache.Get(id)
  21. }
  22. if conn == nil {
  23. var err error
  24. conn, err = internet.DialToDest(src, dest)
  25. if err != nil {
  26. return nil, err
  27. }
  28. }
  29. if options.Stream != nil && options.Stream.Security == internet.StreamSecurityTypeTLS {
  30. config := options.Stream.TLSSettings.GetTLSConfig()
  31. if dest.Address.Family().IsDomain() {
  32. config.ServerName = dest.Address.Domain()
  33. }
  34. conn = tls.Client(conn, config)
  35. }
  36. return NewConnection(id, conn, globalCache), nil
  37. }
  38. func DialRaw(src v2net.Address, dest v2net.Destination, options internet.DialerOptions) (internet.Connection, error) {
  39. log.Info("Dailing Raw TCP to ", dest)
  40. conn, err := internet.DialToDest(src, dest)
  41. if err != nil {
  42. return nil, err
  43. }
  44. // TODO: handle dialer options
  45. return &RawConnection{
  46. TCPConn: *conn.(*net.TCPConn),
  47. }, nil
  48. }
  49. func init() {
  50. internet.TCPDialer = Dial
  51. internet.RawTCPDialer = DialRaw
  52. }