1
0

dialer.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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. if config := tls.ConfigFromStreamSettings(streamSettings); config != nil {
  54. protocol = "wss"
  55. tlsConfig := config.GetTLSConfig(tls.WithDestination(dest), tls.WithNextProto("http/1.1"))
  56. dialer.TLSClientConfig = tlsConfig
  57. if fingerprint := tls.GetFingerprint(config.Fingerprint); fingerprint != nil {
  58. dialer.NetDialTLSContext = func(_ context.Context, _, addr string) (gonet.Conn, error) {
  59. // Like the NetDial in the dialer
  60. pconn, err := internet.DialSystem(ctx, dest, streamSettings.SocketSettings)
  61. if err != nil {
  62. errors.LogErrorInner(ctx, err, "failed to dial to "+addr)
  63. return nil, err
  64. }
  65. // TLS and apply the handshake
  66. cn := tls.UClient(pconn, tlsConfig, fingerprint).(*tls.UConn)
  67. if err := cn.WebsocketHandshakeContext(ctx); err != nil {
  68. errors.LogErrorInner(ctx, err, "failed to dial to "+addr)
  69. return nil, err
  70. }
  71. if !tlsConfig.InsecureSkipVerify {
  72. if err := cn.VerifyHostname(tlsConfig.ServerName); err != nil {
  73. errors.LogErrorInner(ctx, err, "failed to dial to "+addr)
  74. return nil, err
  75. }
  76. }
  77. return cn, nil
  78. }
  79. }
  80. }
  81. host := dest.NetAddr()
  82. if (protocol == "ws" && dest.Port == 80) || (protocol == "wss" && dest.Port == 443) {
  83. host = dest.Address.String()
  84. }
  85. uri := protocol + "://" + host + wsSettings.GetNormalizedPath()
  86. if browser_dialer.HasBrowserDialer() {
  87. conn, err := browser_dialer.DialWS(uri, ed)
  88. if err != nil {
  89. return nil, err
  90. }
  91. return NewConnection(conn, conn.RemoteAddr(), nil), nil
  92. }
  93. header := wsSettings.GetRequestHeader()
  94. if ed != nil {
  95. // RawURLEncoding is support by both V2Ray/V2Fly and XRay.
  96. header.Set("Sec-WebSocket-Protocol", base64.RawURLEncoding.EncodeToString(ed))
  97. }
  98. conn, resp, err := dialer.DialContext(ctx, uri, header)
  99. if err != nil {
  100. var reason string
  101. if resp != nil {
  102. reason = resp.Status
  103. }
  104. return nil, errors.New("failed to dial to (", uri, "): ", reason).Base(err)
  105. }
  106. return NewConnection(conn, conn.RemoteAddr(), nil), nil
  107. }
  108. type delayDialConn struct {
  109. net.Conn
  110. closed bool
  111. dialed chan bool
  112. cancel context.CancelFunc
  113. ctx context.Context
  114. dest net.Destination
  115. streamSettings *internet.MemoryStreamConfig
  116. }
  117. func (d *delayDialConn) Write(b []byte) (int, error) {
  118. if d.closed {
  119. return 0, io.ErrClosedPipe
  120. }
  121. if d.Conn == nil {
  122. ed := b
  123. if len(ed) > int(d.streamSettings.ProtocolSettings.(*Config).Ed) {
  124. ed = nil
  125. }
  126. var err error
  127. if d.Conn, err = dialWebSocket(d.ctx, d.dest, d.streamSettings, ed); err != nil {
  128. d.Close()
  129. return 0, errors.New("failed to dial WebSocket").Base(err)
  130. }
  131. d.dialed <- true
  132. if ed != nil {
  133. return len(ed), nil
  134. }
  135. }
  136. return d.Conn.Write(b)
  137. }
  138. func (d *delayDialConn) Read(b []byte) (int, error) {
  139. if d.closed {
  140. return 0, io.ErrClosedPipe
  141. }
  142. if d.Conn == nil {
  143. select {
  144. case <-d.ctx.Done():
  145. return 0, io.ErrUnexpectedEOF
  146. case <-d.dialed:
  147. }
  148. }
  149. return d.Conn.Read(b)
  150. }
  151. func (d *delayDialConn) Close() error {
  152. d.closed = true
  153. d.cancel()
  154. if d.Conn == nil {
  155. return nil
  156. }
  157. return d.Conn.Close()
  158. }