dialer.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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/common/session"
  9. "v2ray.com/core/transport/internet"
  10. "v2ray.com/core/transport/internet/tls"
  11. )
  12. // Dial dials a WebSocket connection to the given destination.
  13. func Dial(ctx context.Context, dest net.Destination) (internet.Connection, error) {
  14. newError("creating connection to ", dest).WriteToLog(session.ExportIDToError(ctx))
  15. conn, err := dialWebsocket(ctx, dest)
  16. if err != nil {
  17. return nil, newError("failed to dial WebSocket").Base(err)
  18. }
  19. return internet.Connection(conn), nil
  20. }
  21. func init() {
  22. common.Must(internet.RegisterTransportDialer(protocolName, Dial))
  23. }
  24. func dialWebsocket(ctx context.Context, dest net.Destination) (net.Conn, error) {
  25. wsSettings := internet.StreamSettingsFromContext(ctx).ProtocolSettings.(*Config)
  26. dialer := &websocket.Dialer{
  27. NetDial: func(network, addr string) (net.Conn, error) {
  28. return internet.DialSystem(ctx, 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.GetNormalizedPath()
  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. }