client.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. package splithttp
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "io"
  7. gonet "net"
  8. "net/http"
  9. "net/http/httptrace"
  10. "sync"
  11. "github.com/xtls/xray-core/common"
  12. "github.com/xtls/xray-core/common/errors"
  13. "github.com/xtls/xray-core/common/net"
  14. "github.com/xtls/xray-core/common/signal/done"
  15. )
  16. // interface to abstract between use of browser dialer, vs net/http
  17. type DialerClient interface {
  18. IsClosed() bool
  19. // ctx, url, body, uploadOnly
  20. OpenStream(context.Context, string, io.Reader, bool) (io.ReadCloser, net.Addr, net.Addr, error)
  21. // ctx, url, body, contentLength
  22. PostPacket(context.Context, string, io.Reader, int64) error
  23. }
  24. // implements splithttp.DialerClient in terms of direct network connections
  25. type DefaultDialerClient struct {
  26. transportConfig *Config
  27. client *http.Client
  28. closed bool
  29. httpVersion string
  30. // pool of net.Conn, created using dialUploadConn
  31. uploadRawPool *sync.Pool
  32. dialUploadConn func(ctxInner context.Context) (net.Conn, error)
  33. }
  34. func (c *DefaultDialerClient) IsClosed() bool {
  35. return c.closed
  36. }
  37. func (c *DefaultDialerClient) OpenStream(ctx context.Context, url string, body io.Reader, uploadOnly bool) (wrc io.ReadCloser, remoteAddr, localAddr gonet.Addr, err error) {
  38. // this is done when the TCP/UDP connection to the server was established,
  39. // and we can unblock the Dial function and print correct net addresses in
  40. // logs
  41. gotConn := done.New()
  42. ctx = httptrace.WithClientTrace(ctx, &httptrace.ClientTrace{
  43. GotConn: func(connInfo httptrace.GotConnInfo) {
  44. remoteAddr = connInfo.Conn.RemoteAddr()
  45. localAddr = connInfo.Conn.LocalAddr()
  46. gotConn.Close()
  47. },
  48. })
  49. method := "GET"
  50. if body != nil {
  51. method = "POST"
  52. }
  53. req, _ := http.NewRequestWithContext(ctx, method, url, body)
  54. req.Header = c.transportConfig.GetRequestHeader()
  55. if method == "POST" && !c.transportConfig.NoGRPCHeader {
  56. req.Header.Set("Content-Type", "application/grpc")
  57. }
  58. wrc = &WaitReadCloser{Wait: make(chan struct{})}
  59. go func() {
  60. resp, err := c.client.Do(req)
  61. if err != nil {
  62. errors.LogInfoInner(ctx, err, "failed to "+method+" "+url)
  63. gotConn.Close()
  64. wrc.Close()
  65. return
  66. }
  67. if resp.StatusCode != 200 && !uploadOnly {
  68. // c.closed = true
  69. errors.LogInfo(ctx, "unexpected status ", resp.StatusCode)
  70. }
  71. if resp.StatusCode != 200 || uploadOnly {
  72. resp.Body.Close()
  73. wrc.Close()
  74. return
  75. }
  76. wrc.(*WaitReadCloser).Set(resp.Body)
  77. }()
  78. <-gotConn.Wait()
  79. return
  80. }
  81. func (c *DefaultDialerClient) PostPacket(ctx context.Context, url string, body io.Reader, contentLength int64) error {
  82. req, err := http.NewRequestWithContext(ctx, "POST", url, body)
  83. if err != nil {
  84. return err
  85. }
  86. req.ContentLength = contentLength
  87. req.Header = c.transportConfig.GetRequestHeader()
  88. if c.httpVersion != "1.1" {
  89. resp, err := c.client.Do(req)
  90. if err != nil {
  91. return err
  92. }
  93. defer resp.Body.Close()
  94. if resp.StatusCode != 200 {
  95. // c.closed = true
  96. return errors.New("bad status code:", resp.Status)
  97. }
  98. } else {
  99. // stringify the entire HTTP/1.1 request so it can be
  100. // safely retried. if instead req.Write is called multiple
  101. // times, the body is already drained after the first
  102. // request
  103. requestBuff := new(bytes.Buffer)
  104. common.Must(req.Write(requestBuff))
  105. var uploadConn any
  106. var h1UploadConn *H1Conn
  107. for {
  108. uploadConn = c.uploadRawPool.Get()
  109. newConnection := uploadConn == nil
  110. if newConnection {
  111. newConn, err := c.dialUploadConn(context.WithoutCancel(ctx))
  112. if err != nil {
  113. return err
  114. }
  115. h1UploadConn = NewH1Conn(newConn)
  116. uploadConn = h1UploadConn
  117. } else {
  118. h1UploadConn = uploadConn.(*H1Conn)
  119. // TODO: Replace 0 here with a config value later
  120. // Or add some other condition for optimization purposes
  121. if h1UploadConn.UnreadedResponsesCount > 0 {
  122. resp, err := http.ReadResponse(h1UploadConn.RespBufReader, req)
  123. if err != nil {
  124. return fmt.Errorf("error while reading response: %s", err.Error())
  125. }
  126. if resp.StatusCode != 200 {
  127. // c.closed = true
  128. // resp.Body.Close() // I'm not sure
  129. return fmt.Errorf("got non-200 error response code: %d", resp.StatusCode)
  130. }
  131. }
  132. }
  133. _, err := h1UploadConn.Write(requestBuff.Bytes())
  134. // if the write failed, we try another connection from
  135. // the pool, until the write on a new connection fails.
  136. // failed writes to a pooled connection are normal when
  137. // the connection has been closed in the meantime.
  138. if err == nil {
  139. break
  140. } else if newConnection {
  141. return err
  142. }
  143. }
  144. c.uploadRawPool.Put(uploadConn)
  145. }
  146. return nil
  147. }
  148. type WaitReadCloser struct {
  149. Wait chan struct{}
  150. io.ReadCloser
  151. }
  152. func (w *WaitReadCloser) Set(rc io.ReadCloser) {
  153. w.ReadCloser = rc
  154. defer func() {
  155. if recover() != nil {
  156. rc.Close()
  157. }
  158. }()
  159. close(w.Wait)
  160. }
  161. func (w *WaitReadCloser) Read(b []byte) (int, error) {
  162. if w.ReadCloser == nil {
  163. if <-w.Wait; w.ReadCloser == nil {
  164. return 0, io.ErrClosedPipe
  165. }
  166. }
  167. return w.ReadCloser.Read(b)
  168. }
  169. func (w *WaitReadCloser) Close() error {
  170. if w.ReadCloser != nil {
  171. return w.ReadCloser.Close()
  172. }
  173. defer func() {
  174. if recover() != nil && w.ReadCloser != nil {
  175. w.ReadCloser.Close()
  176. }
  177. }()
  178. close(w.Wait)
  179. return nil
  180. }