dialer.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package websocket
  2. import (
  3. "context"
  4. "net"
  5. "github.com/gorilla/websocket"
  6. "v2ray.com/core/app/log"
  7. "v2ray.com/core/common"
  8. "v2ray.com/core/common/errors"
  9. v2net "v2ray.com/core/common/net"
  10. "v2ray.com/core/transport/internet"
  11. "v2ray.com/core/transport/internet/internal"
  12. v2tls "v2ray.com/core/transport/internet/tls"
  13. )
  14. var (
  15. globalCache = internal.NewConnectionPool()
  16. )
  17. func Dial(ctx context.Context, dest v2net.Destination) (internet.Connection, error) {
  18. log.Info("WebSocket|Dialer: Creating connection to ", dest)
  19. src := internet.DialerSourceFromContext(ctx)
  20. wsSettings := internet.TransportSettingsFromContext(ctx).(*Config)
  21. id := internal.NewConnectionID(src, dest)
  22. var conn net.Conn
  23. if dest.Network == v2net.Network_TCP && wsSettings.IsConnectionReuse() {
  24. conn = globalCache.Get(id)
  25. }
  26. if conn == nil {
  27. var err error
  28. conn, err = wsDial(ctx, dest)
  29. if err != nil {
  30. log.Warning("WebSocket|Dialer: Dial failed: ", err)
  31. return nil, err
  32. }
  33. }
  34. return internal.NewConnection(id, conn, globalCache, internal.ReuseConnection(wsSettings.IsConnectionReuse())), nil
  35. }
  36. func init() {
  37. common.Must(internet.RegisterTransportDialer(internet.TransportProtocol_WebSocket, Dial))
  38. }
  39. func wsDial(ctx context.Context, dest v2net.Destination) (net.Conn, error) {
  40. src := internet.DialerSourceFromContext(ctx)
  41. wsSettings := internet.TransportSettingsFromContext(ctx).(*Config)
  42. commonDial := func(network, addr string) (net.Conn, error) {
  43. return internet.DialSystem(src, dest)
  44. }
  45. dialer := websocket.Dialer{
  46. NetDial: commonDial,
  47. ReadBufferSize: 32 * 1024,
  48. WriteBufferSize: 32 * 1024,
  49. }
  50. protocol := "ws"
  51. if securitySettings := internet.SecuritySettingsFromContext(ctx); securitySettings != nil {
  52. tlsConfig, ok := securitySettings.(*v2tls.Config)
  53. if ok {
  54. protocol = "wss"
  55. dialer.TLSClientConfig = tlsConfig.GetTLSConfig()
  56. if dest.Address.Family().IsDomain() {
  57. dialer.TLSClientConfig.ServerName = dest.Address.Domain()
  58. }
  59. }
  60. }
  61. host := dest.NetAddr()
  62. if (protocol == "ws" && dest.Port == 80) || (protocol == "wss" && dest.Port == 443) {
  63. host = dest.Address.String()
  64. }
  65. uri := protocol + "://" + host + wsSettings.GetNormailzedPath()
  66. conn, resp, err := dialer.Dial(uri, nil)
  67. if err != nil {
  68. var reason string
  69. if resp != nil {
  70. reason = resp.Status
  71. }
  72. return nil, errors.Base(err).Message("WebSocket|Dialer: Failed to dial to (", uri, "): ", reason)
  73. }
  74. return &connection{
  75. wsc: conn,
  76. }, nil
  77. }