client.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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" // stream-down
  50. if body != nil {
  51. method = "POST" // stream-up/one
  52. }
  53. req, _ := http.NewRequestWithContext(context.WithoutCancel(ctx), method, url, body)
  54. req.Header = c.transportConfig.GetRequestHeader(url)
  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. if !uploadOnly { // stream-down is enough
  63. c.closed = true
  64. errors.LogInfoInner(ctx, err, "failed to "+method+" "+url)
  65. }
  66. gotConn.Close()
  67. wrc.Close()
  68. return
  69. }
  70. if resp.StatusCode != 200 && !uploadOnly {
  71. errors.LogInfo(ctx, "unexpected status ", resp.StatusCode)
  72. }
  73. if resp.StatusCode != 200 || uploadOnly { // stream-up
  74. io.Copy(io.Discard, resp.Body)
  75. resp.Body.Close() // if it is called immediately, the upload will be interrupted also
  76. wrc.Close()
  77. return
  78. }
  79. wrc.(*WaitReadCloser).Set(resp.Body)
  80. }()
  81. <-gotConn.Wait()
  82. return
  83. }
  84. func (c *DefaultDialerClient) PostPacket(ctx context.Context, url string, body io.Reader, contentLength int64) error {
  85. req, err := http.NewRequestWithContext(context.WithoutCancel(ctx), "POST", url, body)
  86. if err != nil {
  87. return err
  88. }
  89. req.ContentLength = contentLength
  90. req.Header = c.transportConfig.GetRequestHeader(url)
  91. if c.httpVersion != "1.1" {
  92. resp, err := c.client.Do(req)
  93. if err != nil {
  94. c.closed = true
  95. return err
  96. }
  97. io.Copy(io.Discard, resp.Body)
  98. defer resp.Body.Close()
  99. if resp.StatusCode != 200 {
  100. return errors.New("bad status code:", resp.Status)
  101. }
  102. } else {
  103. // stringify the entire HTTP/1.1 request so it can be
  104. // safely retried. if instead req.Write is called multiple
  105. // times, the body is already drained after the first
  106. // request
  107. requestBuff := new(bytes.Buffer)
  108. common.Must(req.Write(requestBuff))
  109. var uploadConn any
  110. var h1UploadConn *H1Conn
  111. for {
  112. uploadConn = c.uploadRawPool.Get()
  113. newConnection := uploadConn == nil
  114. if newConnection {
  115. newConn, err := c.dialUploadConn(context.WithoutCancel(ctx))
  116. if err != nil {
  117. return err
  118. }
  119. h1UploadConn = NewH1Conn(newConn)
  120. uploadConn = h1UploadConn
  121. } else {
  122. h1UploadConn = uploadConn.(*H1Conn)
  123. // TODO: Replace 0 here with a config value later
  124. // Or add some other condition for optimization purposes
  125. if h1UploadConn.UnreadedResponsesCount > 0 {
  126. resp, err := http.ReadResponse(h1UploadConn.RespBufReader, req)
  127. if err != nil {
  128. c.closed = true
  129. return fmt.Errorf("error while reading response: %s", err.Error())
  130. }
  131. io.Copy(io.Discard, resp.Body)
  132. defer resp.Body.Close()
  133. if resp.StatusCode != 200 {
  134. return fmt.Errorf("got non-200 error response code: %d", resp.StatusCode)
  135. }
  136. }
  137. }
  138. _, err := h1UploadConn.Write(requestBuff.Bytes())
  139. // if the write failed, we try another connection from
  140. // the pool, until the write on a new connection fails.
  141. // failed writes to a pooled connection are normal when
  142. // the connection has been closed in the meantime.
  143. if err == nil {
  144. break
  145. } else if newConnection {
  146. return err
  147. }
  148. }
  149. c.uploadRawPool.Put(uploadConn)
  150. }
  151. return nil
  152. }
  153. type WaitReadCloser struct {
  154. Wait chan struct{}
  155. io.ReadCloser
  156. }
  157. func (w *WaitReadCloser) Set(rc io.ReadCloser) {
  158. w.ReadCloser = rc
  159. defer func() {
  160. if recover() != nil {
  161. rc.Close()
  162. }
  163. }()
  164. close(w.Wait)
  165. }
  166. func (w *WaitReadCloser) Read(b []byte) (int, error) {
  167. if w.ReadCloser == nil {
  168. if <-w.Wait; w.ReadCloser == nil {
  169. return 0, io.ErrClosedPipe
  170. }
  171. }
  172. return w.ReadCloser.Read(b)
  173. }
  174. func (w *WaitReadCloser) Close() error {
  175. if w.ReadCloser != nil {
  176. return w.ReadCloser.Close()
  177. }
  178. defer func() {
  179. if recover() != nil && w.ReadCloser != nil {
  180. w.ReadCloser.Close()
  181. }
  182. }()
  183. close(w.Wait)
  184. return nil
  185. }