dialer.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package hub
  2. import (
  3. "errors"
  4. "net"
  5. "time"
  6. "github.com/v2ray/v2ray-core/common/log"
  7. v2net "github.com/v2ray/v2ray-core/common/net"
  8. "github.com/v2ray/v2ray-core/transport"
  9. )
  10. var (
  11. ErrorInvalidHost = errors.New("Invalid Host.")
  12. globalCache = NewConnectionCache()
  13. )
  14. func Dial(dest v2net.Destination) (*Connection, error) {
  15. destStr := dest.String()
  16. var conn net.Conn
  17. if transport.TCPStreamConfig.ConnectionReuse {
  18. conn = globalCache.Get(destStr)
  19. }
  20. if conn == nil {
  21. var err error
  22. log.Debug("Hub: Dialling new connection to ", dest)
  23. conn, err = DialWithoutCache(dest)
  24. if err != nil {
  25. return nil, err
  26. }
  27. } else {
  28. log.Debug("Hub: Reusing connection to ", dest)
  29. }
  30. return &Connection{
  31. dest: destStr,
  32. conn: conn,
  33. listener: globalCache,
  34. }, nil
  35. }
  36. func DialWithoutCache(dest v2net.Destination) (net.Conn, error) {
  37. if dest.Address().IsDomain() {
  38. dialer := &net.Dialer{
  39. Timeout: time.Second * 60,
  40. DualStack: true,
  41. }
  42. network := "tcp"
  43. if dest.IsUDP() {
  44. network = "udp"
  45. }
  46. return dialer.Dial(network, dest.NetAddr())
  47. }
  48. ip := dest.Address().IP()
  49. if dest.IsTCP() {
  50. return net.DialTCP("tcp", nil, &net.TCPAddr{
  51. IP: ip,
  52. Port: int(dest.Port()),
  53. })
  54. }
  55. return net.DialUDP("udp", nil, &net.UDPAddr{
  56. IP: ip,
  57. Port: int(dest.Port()),
  58. })
  59. }