dialer.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. package websocket
  2. import (
  3. "context"
  4. _ "embed"
  5. "encoding/base64"
  6. "io"
  7. gonet "net"
  8. "time"
  9. "github.com/gorilla/websocket"
  10. "github.com/xtls/xray-core/common"
  11. "github.com/xtls/xray-core/common/errors"
  12. "github.com/xtls/xray-core/common/net"
  13. "github.com/xtls/xray-core/transport/internet"
  14. "github.com/xtls/xray-core/transport/internet/browser_dialer"
  15. "github.com/xtls/xray-core/transport/internet/stat"
  16. "github.com/xtls/xray-core/transport/internet/tls"
  17. )
  18. // Dial dials a WebSocket connection to the given destination.
  19. func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.MemoryStreamConfig) (stat.Connection, error) {
  20. errors.LogInfo(ctx, "creating connection to ", dest)
  21. var conn net.Conn
  22. if streamSettings.ProtocolSettings.(*Config).Ed > 0 {
  23. ctx, cancel := context.WithCancel(ctx)
  24. conn = &delayDialConn{
  25. dialed: make(chan bool, 1),
  26. cancel: cancel,
  27. ctx: ctx,
  28. dest: dest,
  29. streamSettings: streamSettings,
  30. }
  31. } else {
  32. var err error
  33. if conn, err = dialWebSocket(ctx, dest, streamSettings, nil); err != nil {
  34. return nil, errors.New("failed to dial WebSocket").Base(err)
  35. }
  36. }
  37. return stat.Connection(conn), nil
  38. }
  39. func init() {
  40. common.Must(internet.RegisterTransportDialer(protocolName, Dial))
  41. }
  42. func dialWebSocket(ctx context.Context, dest net.Destination, streamSettings *internet.MemoryStreamConfig, ed []byte) (net.Conn, error) {
  43. wsSettings := streamSettings.ProtocolSettings.(*Config)
  44. dialer := &websocket.Dialer{
  45. NetDial: func(network, addr string) (net.Conn, error) {
  46. return internet.DialSystem(ctx, dest, streamSettings.SocketSettings)
  47. },
  48. ReadBufferSize: 4 * 1024,
  49. WriteBufferSize: 4 * 1024,
  50. HandshakeTimeout: time.Second * 8,
  51. }
  52. protocol := "ws"
  53. tConfig := tls.ConfigFromStreamSettings(streamSettings)
  54. if tConfig != nil {
  55. protocol = "wss"
  56. tlsConfig := tConfig.GetTLSConfig(tls.WithDestination(dest), tls.WithNextProto("http/1.1"))
  57. dialer.TLSClientConfig = tlsConfig
  58. if fingerprint := tls.GetFingerprint(tConfig.Fingerprint); fingerprint != nil {
  59. dialer.NetDialTLSContext = func(_ context.Context, _, addr string) (gonet.Conn, error) {
  60. // Like the NetDial in the dialer
  61. pconn, err := internet.DialSystem(ctx, dest, streamSettings.SocketSettings)
  62. if err != nil {
  63. errors.LogErrorInner(ctx, err, "failed to dial to "+addr)
  64. return nil, err
  65. }
  66. // TLS and apply the handshake
  67. cn := tls.UClient(pconn, tlsConfig, fingerprint).(*tls.UConn)
  68. if err := cn.WebsocketHandshakeContext(ctx); err != nil {
  69. errors.LogErrorInner(ctx, err, "failed to dial to "+addr)
  70. return nil, err
  71. }
  72. if !tlsConfig.InsecureSkipVerify {
  73. if err := cn.VerifyHostname(tlsConfig.ServerName); err != nil {
  74. errors.LogErrorInner(ctx, err, "failed to dial to "+addr)
  75. return nil, err
  76. }
  77. }
  78. return cn, nil
  79. }
  80. }
  81. }
  82. host := dest.NetAddr()
  83. if (protocol == "ws" && dest.Port == 80) || (protocol == "wss" && dest.Port == 443) {
  84. host = dest.Address.String()
  85. }
  86. uri := protocol + "://" + host + wsSettings.GetNormalizedPath()
  87. if browser_dialer.HasBrowserDialer() {
  88. conn, err := browser_dialer.DialWS(uri, ed)
  89. if err != nil {
  90. return nil, err
  91. }
  92. return NewConnection(conn, conn.RemoteAddr(), nil, wsSettings.HeartbeatPeriod), nil
  93. }
  94. header := wsSettings.GetRequestHeader()
  95. // See dialer.DialContext()
  96. header.Set("Host", wsSettings.Host)
  97. if header.Get("Host") == "" && tConfig != nil {
  98. header.Set("Host", tConfig.ServerName)
  99. }
  100. if header.Get("Host") == "" {
  101. header.Set("Host", dest.Address.String())
  102. }
  103. if ed != nil {
  104. // RawURLEncoding is support by both V2Ray/V2Fly and XRay.
  105. header.Set("Sec-WebSocket-Protocol", base64.RawURLEncoding.EncodeToString(ed))
  106. }
  107. conn, resp, err := dialer.DialContext(ctx, uri, header)
  108. if err != nil {
  109. var reason string
  110. if resp != nil {
  111. reason = resp.Status
  112. }
  113. return nil, errors.New("failed to dial to (", uri, "): ", reason).Base(err)
  114. }
  115. return NewConnection(conn, conn.RemoteAddr(), nil, wsSettings.HeartbeatPeriod), nil
  116. }
  117. type delayDialConn struct {
  118. net.Conn
  119. closed bool
  120. dialed chan bool
  121. cancel context.CancelFunc
  122. ctx context.Context
  123. dest net.Destination
  124. streamSettings *internet.MemoryStreamConfig
  125. }
  126. func (d *delayDialConn) Write(b []byte) (int, error) {
  127. if d.closed {
  128. return 0, io.ErrClosedPipe
  129. }
  130. if d.Conn == nil {
  131. ed := b
  132. if len(ed) > int(d.streamSettings.ProtocolSettings.(*Config).Ed) {
  133. ed = nil
  134. }
  135. var err error
  136. if d.Conn, err = dialWebSocket(d.ctx, d.dest, d.streamSettings, ed); err != nil {
  137. d.Close()
  138. return 0, errors.New("failed to dial WebSocket").Base(err)
  139. }
  140. d.dialed <- true
  141. if ed != nil {
  142. return len(ed), nil
  143. }
  144. }
  145. return d.Conn.Write(b)
  146. }
  147. func (d *delayDialConn) Read(b []byte) (int, error) {
  148. if d.closed {
  149. return 0, io.ErrClosedPipe
  150. }
  151. if d.Conn == nil {
  152. select {
  153. case <-d.ctx.Done():
  154. return 0, io.ErrUnexpectedEOF
  155. case <-d.dialed:
  156. }
  157. }
  158. return d.Conn.Read(b)
  159. }
  160. func (d *delayDialConn) Close() error {
  161. d.closed = true
  162. d.cancel()
  163. if d.Conn == nil {
  164. return nil
  165. }
  166. return d.Conn.Close()
  167. }