dialer.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. )
  9. var (
  10. ErrorInvalidHost = errors.New("Invalid Host.")
  11. globalCache = NewConnectionCache()
  12. )
  13. func Dial(dest v2net.Destination) (*Connection, error) {
  14. destStr := dest.String()
  15. conn := globalCache.Get(destStr)
  16. if conn == nil {
  17. var err error
  18. log.Debug("Hub: Dialling new connection to ", dest)
  19. conn, err = DialWithoutCache(dest)
  20. if err != nil {
  21. return nil, err
  22. }
  23. } else {
  24. log.Debug("Hub: Reusing connection to ", dest)
  25. }
  26. return &Connection{
  27. dest: destStr,
  28. conn: conn,
  29. listener: globalCache,
  30. }, nil
  31. }
  32. func DialWithoutCache(dest v2net.Destination) (net.Conn, error) {
  33. if dest.Address().IsDomain() {
  34. dialer := &net.Dialer{
  35. Timeout: time.Second * 60,
  36. DualStack: true,
  37. }
  38. network := "tcp"
  39. if dest.IsUDP() {
  40. network = "udp"
  41. }
  42. return dialer.Dial(network, dest.NetAddr())
  43. }
  44. ip := dest.Address().IP()
  45. if dest.IsTCP() {
  46. return net.DialTCP("tcp", nil, &net.TCPAddr{
  47. IP: ip,
  48. Port: int(dest.Port()),
  49. })
  50. }
  51. return net.DialUDP("udp", nil, &net.UDPAddr{
  52. IP: ip,
  53. Port: int(dest.Port()),
  54. })
  55. }