client.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. package splithttp
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/base64"
  6. "fmt"
  7. "io"
  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, sessionId, body, uploadOnly
  20. OpenStream(context.Context, string, string, io.Reader, bool) (io.ReadCloser, net.Addr, net.Addr, error)
  21. // ctx, url, sessionId, seqStr, body, contentLength
  22. PostPacket(context.Context, string, string, 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, sessionId string, body io.Reader, uploadOnly bool) (wrc io.ReadCloser, remoteAddr, localAddr net.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 = c.transportConfig.GetNormalizedUplinkHTTPMethod() // stream-up/one
  52. }
  53. req, _ := http.NewRequestWithContext(context.WithoutCancel(ctx), method, url, body)
  54. req.Header = c.transportConfig.GetRequestHeader()
  55. length := int(c.transportConfig.GetNormalizedXPaddingBytes().rand())
  56. config := XPaddingConfig{Length: length}
  57. if c.transportConfig.XPaddingObfsMode {
  58. config.Placement = XPaddingPlacement{
  59. Placement: c.transportConfig.XPaddingPlacement,
  60. Key: c.transportConfig.XPaddingKey,
  61. Header: c.transportConfig.XPaddingHeader,
  62. RawURL: url,
  63. }
  64. config.Method = PaddingMethod(c.transportConfig.XPaddingMethod)
  65. } else {
  66. config.Placement = XPaddingPlacement{
  67. Placement: PlacementQueryInHeader,
  68. Key: "x_padding",
  69. Header: "Referer",
  70. RawURL: url,
  71. }
  72. }
  73. c.transportConfig.ApplyXPaddingToRequest(req, config)
  74. c.transportConfig.ApplyMetaToRequest(req, sessionId, "")
  75. if method == c.transportConfig.GetNormalizedUplinkHTTPMethod() && !c.transportConfig.NoGRPCHeader {
  76. req.Header.Set("Content-Type", "application/grpc")
  77. }
  78. wrc = &WaitReadCloser{Wait: make(chan struct{})}
  79. go func() {
  80. resp, err := c.client.Do(req)
  81. if err != nil {
  82. if !uploadOnly { // stream-down is enough
  83. c.closed = true
  84. errors.LogInfoInner(ctx, err, "failed to "+method+" "+url)
  85. }
  86. gotConn.Close()
  87. wrc.Close()
  88. return
  89. }
  90. if resp.StatusCode != 200 && !uploadOnly {
  91. errors.LogInfo(ctx, "unexpected status ", resp.StatusCode)
  92. }
  93. if resp.StatusCode != 200 || uploadOnly { // stream-up
  94. io.Copy(io.Discard, resp.Body)
  95. resp.Body.Close() // if it is called immediately, the upload will be interrupted also
  96. wrc.Close()
  97. return
  98. }
  99. wrc.(*WaitReadCloser).Set(resp.Body)
  100. }()
  101. <-gotConn.Wait()
  102. return
  103. }
  104. func (c *DefaultDialerClient) PostPacket(ctx context.Context, url string, sessionId string, seqStr string, body io.Reader, contentLength int64) error {
  105. var encodedData string
  106. dataPlacement := c.transportConfig.GetNormalizedUplinkDataPlacement()
  107. if dataPlacement != PlacementBody {
  108. data, err := io.ReadAll(body)
  109. if err != nil {
  110. return err
  111. }
  112. encodedData = base64.RawURLEncoding.EncodeToString(data)
  113. body = nil
  114. contentLength = 0
  115. }
  116. method := c.transportConfig.GetNormalizedUplinkHTTPMethod()
  117. req, err := http.NewRequestWithContext(context.WithoutCancel(ctx), method, url, body)
  118. if err != nil {
  119. return err
  120. }
  121. req.ContentLength = contentLength
  122. req.Header = c.transportConfig.GetRequestHeader()
  123. if dataPlacement != PlacementBody {
  124. key := c.transportConfig.UplinkDataKey
  125. chunkSize := int(c.transportConfig.UplinkChunkSize)
  126. switch dataPlacement {
  127. case PlacementHeader:
  128. for i := 0; i < len(encodedData); i += chunkSize {
  129. end := i + chunkSize
  130. if end > len(encodedData) {
  131. end = len(encodedData)
  132. }
  133. chunk := encodedData[i:end]
  134. headerKey := fmt.Sprintf("%s-%d", key, i/chunkSize)
  135. req.Header.Set(headerKey, chunk)
  136. }
  137. req.Header.Set(key+"-Length", fmt.Sprintf("%d", len(encodedData)))
  138. req.Header.Set(key+"-Upstream", "1")
  139. case PlacementCookie:
  140. for i := 0; i < len(encodedData); i += chunkSize {
  141. end := i + chunkSize
  142. if end > len(encodedData) {
  143. end = len(encodedData)
  144. }
  145. chunk := encodedData[i:end]
  146. cookieName := fmt.Sprintf("%s_%d", key, i/chunkSize)
  147. req.AddCookie(&http.Cookie{Name: cookieName, Value: chunk})
  148. }
  149. req.AddCookie(&http.Cookie{Name: key + "_upstream", Value: "1"})
  150. }
  151. }
  152. length := int(c.transportConfig.GetNormalizedXPaddingBytes().rand())
  153. config := XPaddingConfig{Length: length}
  154. if c.transportConfig.XPaddingObfsMode {
  155. config.Placement = XPaddingPlacement{
  156. Placement: c.transportConfig.XPaddingPlacement,
  157. Key: c.transportConfig.XPaddingKey,
  158. Header: c.transportConfig.XPaddingHeader,
  159. RawURL: url,
  160. }
  161. config.Method = PaddingMethod(c.transportConfig.XPaddingMethod)
  162. } else {
  163. config.Placement = XPaddingPlacement{
  164. Placement: PlacementQueryInHeader,
  165. Key: "x_padding",
  166. Header: "Referer",
  167. RawURL: url,
  168. }
  169. }
  170. c.transportConfig.ApplyXPaddingToRequest(req, config)
  171. c.transportConfig.ApplyMetaToRequest(req, sessionId, seqStr)
  172. if c.httpVersion != "1.1" {
  173. resp, err := c.client.Do(req)
  174. if err != nil {
  175. c.closed = true
  176. return err
  177. }
  178. io.Copy(io.Discard, resp.Body)
  179. defer resp.Body.Close()
  180. if resp.StatusCode != 200 {
  181. return errors.New("bad status code:", resp.Status)
  182. }
  183. } else {
  184. // stringify the entire HTTP/1.1 request so it can be
  185. // safely retried. if instead req.Write is called multiple
  186. // times, the body is already drained after the first
  187. // request
  188. requestBuff := new(bytes.Buffer)
  189. common.Must(req.Write(requestBuff))
  190. var uploadConn any
  191. var h1UploadConn *H1Conn
  192. for {
  193. uploadConn = c.uploadRawPool.Get()
  194. newConnection := uploadConn == nil
  195. if newConnection {
  196. newConn, err := c.dialUploadConn(context.WithoutCancel(ctx))
  197. if err != nil {
  198. return err
  199. }
  200. h1UploadConn = NewH1Conn(newConn)
  201. uploadConn = h1UploadConn
  202. } else {
  203. h1UploadConn = uploadConn.(*H1Conn)
  204. // TODO: Replace 0 here with a config value later
  205. // Or add some other condition for optimization purposes
  206. if h1UploadConn.UnreadedResponsesCount > 0 {
  207. resp, err := http.ReadResponse(h1UploadConn.RespBufReader, req)
  208. if err != nil {
  209. c.closed = true
  210. return fmt.Errorf("error while reading response: %s", err.Error())
  211. }
  212. io.Copy(io.Discard, resp.Body)
  213. defer resp.Body.Close()
  214. if resp.StatusCode != 200 {
  215. return fmt.Errorf("got non-200 error response code: %d", resp.StatusCode)
  216. }
  217. }
  218. }
  219. _, err := h1UploadConn.Write(requestBuff.Bytes())
  220. // if the write failed, we try another connection from
  221. // the pool, until the write on a new connection fails.
  222. // failed writes to a pooled connection are normal when
  223. // the connection has been closed in the meantime.
  224. if err == nil {
  225. break
  226. } else if newConnection {
  227. return err
  228. }
  229. }
  230. c.uploadRawPool.Put(uploadConn)
  231. }
  232. return nil
  233. }
  234. type WaitReadCloser struct {
  235. Wait chan struct{}
  236. io.ReadCloser
  237. }
  238. func (w *WaitReadCloser) Set(rc io.ReadCloser) {
  239. w.ReadCloser = rc
  240. defer func() {
  241. if recover() != nil {
  242. rc.Close()
  243. }
  244. }()
  245. close(w.Wait)
  246. }
  247. func (w *WaitReadCloser) Read(b []byte) (int, error) {
  248. if w.ReadCloser == nil {
  249. if <-w.Wait; w.ReadCloser == nil {
  250. return 0, io.ErrClosedPipe
  251. }
  252. }
  253. return w.ReadCloser.Read(b)
  254. }
  255. func (w *WaitReadCloser) Close() error {
  256. if w.ReadCloser != nil {
  257. return w.ReadCloser.Close()
  258. }
  259. defer func() {
  260. if recover() != nil && w.ReadCloser != nil {
  261. w.ReadCloser.Close()
  262. }
  263. }()
  264. close(w.Wait)
  265. return nil
  266. }