dialer.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package ws
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "net"
  6. "github.com/gorilla/websocket"
  7. "v2ray.com/core/common/log"
  8. v2net "v2ray.com/core/common/net"
  9. "v2ray.com/core/transport/internet"
  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("WebSocket|Dailer: Creating connection to ", dest)
  16. if src == nil {
  17. src = v2net.AnyIP
  18. }
  19. id := src.String() + "-" + dest.NetAddr()
  20. var conn *wsconn
  21. if dest.Network == v2net.Network_TCP && effectiveConfig.ConnectionReuse {
  22. connt := globalCache.Get(id)
  23. if connt != nil {
  24. conn = connt.(*wsconn)
  25. }
  26. }
  27. if conn == nil {
  28. var err error
  29. conn, err = wsDial(src, dest, options)
  30. if err != nil {
  31. log.Warning("WebSocket|Dialer: Dial failed: ", err)
  32. return nil, err
  33. }
  34. }
  35. return NewConnection(id, conn, globalCache), nil
  36. }
  37. func init() {
  38. internet.WSDialer = Dial
  39. }
  40. func wsDial(src v2net.Address, dest v2net.Destination, options internet.DialerOptions) (*wsconn, error) {
  41. commonDial := func(network, addr string) (net.Conn, error) {
  42. return internet.DialToDest(src, dest)
  43. }
  44. dialer := websocket.Dialer{
  45. NetDial: commonDial,
  46. ReadBufferSize: 65536,
  47. WriteBufferSize: 65536,
  48. }
  49. protocol := "ws"
  50. if options.Stream != nil && options.Stream.Security == internet.StreamSecurityTypeTLS {
  51. protocol = "wss"
  52. dialer.TLSClientConfig = options.Stream.TLSSettings.GetTLSConfig()
  53. if dest.Address.Family().IsDomain() {
  54. dialer.TLSClientConfig.ServerName = dest.Address.Domain()
  55. }
  56. }
  57. uri := func(dst v2net.Destination, pto string, path string) string {
  58. return fmt.Sprintf("%v://%v/%v", pto, dst.NetAddr(), path)
  59. }(dest, protocol, effectiveConfig.Path)
  60. conn, resp, err := dialer.Dial(uri, nil)
  61. if err != nil {
  62. if resp != nil {
  63. reason, reasonerr := ioutil.ReadAll(resp.Body)
  64. log.Info(string(reason), reasonerr)
  65. }
  66. return nil, err
  67. }
  68. return func() internet.Connection {
  69. connv2ray := &wsconn{wsc: conn, connClosing: false}
  70. connv2ray.setup()
  71. return connv2ray
  72. }().(*wsconn), nil
  73. }