dialer.go 5.7 KB

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