dialer.go 5.6 KB

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