dialer.go 4.6 KB

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