dialer.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package websocket
  2. import (
  3. "context"
  4. "time"
  5. "github.com/gorilla/websocket"
  6. "v2ray.com/core/common"
  7. "v2ray.com/core/common/net"
  8. "v2ray.com/core/transport/internet"
  9. "v2ray.com/core/transport/internet/tls"
  10. )
  11. // Dial dials a WebSocket connection to the given destination.
  12. func Dial(ctx context.Context, dest net.Destination) (internet.Connection, error) {
  13. newError("creating connection to ", dest).WithContext(ctx).WriteToLog()
  14. conn, err := dialWebsocket(ctx, dest)
  15. if err != nil {
  16. return nil, newError("failed to dial WebSocket").Base(err)
  17. }
  18. return internet.Connection(conn), nil
  19. }
  20. func init() {
  21. common.Must(internet.RegisterTransportDialer(internet.TransportProtocol_WebSocket, Dial))
  22. }
  23. func dialWebsocket(ctx context.Context, dest net.Destination) (net.Conn, error) {
  24. src := internet.DialerSourceFromContext(ctx)
  25. wsSettings := internet.TransportSettingsFromContext(ctx).(*Config)
  26. dialer := &websocket.Dialer{
  27. NetDial: func(network, addr string) (net.Conn, error) {
  28. return internet.DialSystem(ctx, src, dest)
  29. },
  30. ReadBufferSize: 4 * 1024,
  31. WriteBufferSize: 4 * 1024,
  32. HandshakeTimeout: time.Second * 8,
  33. }
  34. protocol := "ws"
  35. if config := tls.ConfigFromContext(ctx); config != nil {
  36. protocol = "wss"
  37. dialer.TLSClientConfig = config.GetTLSConfig(tls.WithDestination(dest))
  38. }
  39. host := dest.NetAddr()
  40. if (protocol == "ws" && dest.Port == 80) || (protocol == "wss" && dest.Port == 443) {
  41. host = dest.Address.String()
  42. }
  43. uri := protocol + "://" + host + wsSettings.GetNormailzedPath()
  44. conn, resp, err := dialer.Dial(uri, wsSettings.GetRequestHeader())
  45. if err != nil {
  46. var reason string
  47. if resp != nil {
  48. reason = resp.Status
  49. }
  50. return nil, newError("failed to dial to (", uri, "): ", reason).Base(err)
  51. }
  52. return newConnection(conn, conn.RemoteAddr()), nil
  53. }