dialer.go 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. package websocket
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "io"
  6. "time"
  7. "github.com/gorilla/websocket"
  8. "github.com/xtls/xray-core/common"
  9. "github.com/xtls/xray-core/common/net"
  10. "github.com/xtls/xray-core/common/session"
  11. "github.com/xtls/xray-core/transport/internet"
  12. "github.com/xtls/xray-core/transport/internet/tls"
  13. )
  14. // Dial dials a WebSocket connection to the given destination.
  15. func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.MemoryStreamConfig) (internet.Connection, error) {
  16. newError("creating connection to ", dest).WriteToLog(session.ExportIDToError(ctx))
  17. var conn net.Conn
  18. if streamSettings.ProtocolSettings.(*Config).Ed > 0 {
  19. ctx, cancel := context.WithCancel(ctx)
  20. conn = &delayDialConn{
  21. dialed: make(chan bool, 1),
  22. cancel: cancel,
  23. ctx: ctx,
  24. dest: dest,
  25. streamSettings: streamSettings,
  26. }
  27. } else {
  28. var err error
  29. if conn, err = dialWebSocket(ctx, dest, streamSettings, nil); err != nil {
  30. return nil, newError("failed to dial WebSocket").Base(err)
  31. }
  32. }
  33. return internet.Connection(conn), nil
  34. }
  35. func init() {
  36. common.Must(internet.RegisterTransportDialer(protocolName, Dial))
  37. }
  38. func dialWebSocket(ctx context.Context, dest net.Destination, streamSettings *internet.MemoryStreamConfig, ed []byte) (net.Conn, error) {
  39. wsSettings := streamSettings.ProtocolSettings.(*Config)
  40. dialer := &websocket.Dialer{
  41. NetDial: func(network, addr string) (net.Conn, error) {
  42. return internet.DialSystem(ctx, dest, streamSettings.SocketSettings)
  43. },
  44. ReadBufferSize: 4 * 1024,
  45. WriteBufferSize: 4 * 1024,
  46. HandshakeTimeout: time.Second * 8,
  47. }
  48. protocol := "ws"
  49. if config := tls.ConfigFromStreamSettings(streamSettings); config != nil {
  50. protocol = "wss"
  51. dialer.TLSClientConfig = config.GetTLSConfig(tls.WithDestination(dest), tls.WithNextProto("http/1.1"))
  52. }
  53. host := dest.NetAddr()
  54. if (protocol == "ws" && dest.Port == 80) || (protocol == "wss" && dest.Port == 443) {
  55. host = dest.Address.String()
  56. }
  57. uri := protocol + "://" + host + wsSettings.GetNormalizedPath()
  58. header := wsSettings.GetRequestHeader()
  59. if ed != nil {
  60. header.Set("Sec-WebSocket-Protocol", base64.StdEncoding.EncodeToString(ed))
  61. }
  62. conn, resp, err := dialer.Dial(uri, header)
  63. if err != nil {
  64. var reason string
  65. if resp != nil {
  66. reason = resp.Status
  67. }
  68. return nil, newError("failed to dial to (", uri, "): ", reason).Base(err)
  69. }
  70. return newConnection(conn, conn.RemoteAddr(), nil), nil
  71. }
  72. type delayDialConn struct {
  73. net.Conn
  74. closed bool
  75. dialed chan bool
  76. cancel context.CancelFunc
  77. ctx context.Context
  78. dest net.Destination
  79. streamSettings *internet.MemoryStreamConfig
  80. }
  81. func (d *delayDialConn) Write(b []byte) (int, error) {
  82. if d.closed {
  83. return 0, io.ErrClosedPipe
  84. }
  85. if d.Conn == nil {
  86. ed := b
  87. if len(ed) > int(d.streamSettings.ProtocolSettings.(*Config).Ed) {
  88. ed = nil
  89. }
  90. var err error
  91. if d.Conn, err = dialWebSocket(d.ctx, d.dest, d.streamSettings, ed); err != nil {
  92. d.Close()
  93. return 0, newError("failed to dial WebSocket").Base(err)
  94. }
  95. d.dialed <- true
  96. if ed != nil {
  97. return len(ed), nil
  98. }
  99. }
  100. return d.Conn.Write(b)
  101. }
  102. func (d *delayDialConn) Read(b []byte) (int, error) {
  103. if d.closed {
  104. return 0, io.ErrClosedPipe
  105. }
  106. if d.Conn == nil {
  107. select {
  108. case <-d.ctx.Done():
  109. return 0, io.ErrUnexpectedEOF
  110. case <-d.dialed:
  111. }
  112. }
  113. return d.Conn.Read(b)
  114. }
  115. func (d *delayDialConn) Close() error {
  116. d.closed = true
  117. d.cancel()
  118. if d.Conn == nil {
  119. return nil
  120. }
  121. return d.Conn.Close()
  122. }