client.go 5.4 KB

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