dialer.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. src := internet.DialerSourceFromContext(ctx)
  26. wsSettings := internet.StreamSettingsFromContext(ctx).ProtocolSettings.(*Config)
  27. dialer := &websocket.Dialer{
  28. NetDial: func(network, addr string) (net.Conn, error) {
  29. return internet.DialSystem(ctx, src, dest)
  30. },
  31. ReadBufferSize: 4 * 1024,
  32. WriteBufferSize: 4 * 1024,
  33. HandshakeTimeout: time.Second * 8,
  34. }
  35. protocol := "ws"
  36. if config := tls.ConfigFromContext(ctx); config != nil {
  37. protocol = "wss"
  38. dialer.TLSClientConfig = config.GetTLSConfig(tls.WithDestination(dest))
  39. }
  40. host := dest.NetAddr()
  41. if (protocol == "ws" && dest.Port == 80) || (protocol == "wss" && dest.Port == 443) {
  42. host = dest.Address.String()
  43. }
  44. uri := protocol + "://" + host + wsSettings.GetNormalizedPath()
  45. conn, resp, err := dialer.Dial(uri, wsSettings.GetRequestHeader())
  46. if err != nil {
  47. var reason string
  48. if resp != nil {
  49. reason = resp.Status
  50. }
  51. return nil, newError("failed to dial to (", uri, "): ", reason).Base(err)
  52. }
  53. return newConnection(conn, conn.RemoteAddr()), nil
  54. }